sqlite3.c 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.1. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqlite3.h *****************************************/
  29. /*
  30. ** 2001 September 15
  31. **
  32. ** The author disclaims copyright to this source code. In place of
  33. ** a legal notice, here is a blessing:
  34. **
  35. ** May you do good and not evil.
  36. ** May you find forgiveness for yourself and forgive others.
  37. ** May you share freely, never taking more than you give.
  38. **
  39. *************************************************************************
  40. ** This header file defines the interface that the SQLite library
  41. ** presents to client programs. If a C-function, structure, datatype,
  42. ** or constant definition does not appear in this file, then it is
  43. ** not a published API of SQLite, is subject to change without
  44. ** notice, and should not be referenced by programs that use SQLite.
  45. **
  46. ** Some of the definitions that are in this file are marked as
  47. ** "experimental". Experimental interfaces are normally new
  48. ** features recently added to SQLite. We do not anticipate changes
  49. ** to experimental interfaces but reserve the right to make minor changes
  50. ** if experience from use "in the wild" suggest such changes are prudent.
  51. **
  52. ** The official C-language API documentation for SQLite is derived
  53. ** from comments in this file. This file is the authoritative source
  54. ** on how SQLite interfaces are suppose to operate.
  55. **
  56. ** The name of this file under configuration management is "sqlite.h.in".
  57. ** The makefile makes some minor changes to this file (such as inserting
  58. ** the version number) and changes its name to "sqlite3.h" as
  59. ** part of the build process.
  60. */
  61. #ifndef _SQLITE3_H_
  62. #define _SQLITE3_H_
  63. #include <stdarg.h> /* Needed for the definition of va_list */
  64. /*
  65. ** Make sure we can call this stuff from C++.
  66. */
  67. #if 0
  68. extern "C" {
  69. #endif
  70. #include <rtconfig.h>
  71. /*
  72. ** Add the ability to override 'extern'
  73. */
  74. #ifndef SQLITE_EXTERN
  75. # define SQLITE_EXTERN extern
  76. #endif
  77. #ifndef SQLITE_API
  78. # define SQLITE_API
  79. #endif
  80. /*
  81. ** These no-op macros are used in front of interfaces to mark those
  82. ** interfaces as either deprecated or experimental. New applications
  83. ** should not use deprecated interfaces - they are support for backwards
  84. ** compatibility only. Application writers should be aware that
  85. ** experimental interfaces are subject to change in point releases.
  86. **
  87. ** These macros used to resolve to various kinds of compiler magic that
  88. ** would generate warning messages when they were used. But that
  89. ** compiler magic ended up generating such a flurry of bug reports
  90. ** that we have taken it all out and gone back to using simple
  91. ** noop macros.
  92. */
  93. #define SQLITE_DEPRECATED
  94. #define SQLITE_EXPERIMENTAL
  95. /*
  96. ** Ensure these symbols were not defined by some previous header file.
  97. */
  98. #ifdef SQLITE_VERSION
  99. # undef SQLITE_VERSION
  100. #endif
  101. #ifdef SQLITE_VERSION_NUMBER
  102. # undef SQLITE_VERSION_NUMBER
  103. #endif
  104. /*
  105. ** CAPI3REF: Compile-Time Library Version Numbers
  106. **
  107. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  108. ** evaluates to a string literal that is the SQLite version in the
  109. ** format "X.Y.Z" where X is the major version number (always 3 for
  110. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  111. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  112. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  113. ** numbers used in [SQLITE_VERSION].)^
  114. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  115. ** be larger than the release from which it is derived. Either Y will
  116. ** be held constant and Z will be incremented or else Y will be incremented
  117. ** and Z will be reset to zero.
  118. **
  119. ** Since version 3.6.18, SQLite source code has been stored in the
  120. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  121. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  122. ** a string which identifies a particular check-in of SQLite
  123. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  124. ** string contains the date and time of the check-in (UTC) and an SHA1
  125. ** hash of the entire source tree.
  126. **
  127. ** See also: [sqlite3_libversion()],
  128. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  129. ** [sqlite_version()] and [sqlite_source_id()].
  130. */
  131. #define SQLITE_VERSION "3.8.1"
  132. #define SQLITE_VERSION_NUMBER 3008001
  133. #define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a"
  134. /*
  135. ** CAPI3REF: Run-Time Library Version Numbers
  136. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  137. **
  138. ** These interfaces provide the same information as the [SQLITE_VERSION],
  139. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  140. ** but are associated with the library instead of the header file. ^(Cautious
  141. ** programmers might include assert() statements in their application to
  142. ** verify that values returned by these interfaces match the macros in
  143. ** the header, and thus insure that the application is
  144. ** compiled with matching library and header files.
  145. **
  146. ** <blockquote><pre>
  147. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  148. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  149. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  150. ** </pre></blockquote>)^
  151. **
  152. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  153. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  154. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  155. ** function is provided for use in DLLs since DLL users usually do not have
  156. ** direct access to string constants within the DLL. ^The
  157. ** sqlite3_libversion_number() function returns an integer equal to
  158. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  159. ** a pointer to a string constant whose value is the same as the
  160. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  161. **
  162. ** See also: [sqlite_version()] and [sqlite_source_id()].
  163. */
  164. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  165. SQLITE_API const char *sqlite3_libversion(void);
  166. SQLITE_API const char *sqlite3_sourceid(void);
  167. SQLITE_API int sqlite3_libversion_number(void);
  168. /*
  169. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  170. **
  171. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  172. ** indicating whether the specified option was defined at
  173. ** compile time. ^The SQLITE_ prefix may be omitted from the
  174. ** option name passed to sqlite3_compileoption_used().
  175. **
  176. ** ^The sqlite3_compileoption_get() function allows iterating
  177. ** over the list of options that were defined at compile time by
  178. ** returning the N-th compile time option string. ^If N is out of range,
  179. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  180. ** prefix is omitted from any strings returned by
  181. ** sqlite3_compileoption_get().
  182. **
  183. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  184. ** and sqlite3_compileoption_get() may be omitted by specifying the
  185. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  186. **
  187. ** See also: SQL functions [sqlite_compileoption_used()] and
  188. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  189. */
  190. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  191. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  192. SQLITE_API const char *sqlite3_compileoption_get(int N);
  193. #endif
  194. /*
  195. ** CAPI3REF: Test To See If The Library Is Threadsafe
  196. **
  197. ** ^The sqlite3_threadsafe() function returns zero if and only if
  198. ** SQLite was compiled with mutexing code omitted due to the
  199. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  200. **
  201. ** SQLite can be compiled with or without mutexes. When
  202. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  203. ** are enabled and SQLite is threadsafe. When the
  204. ** [SQLITE_THREADSAFE] macro is 0,
  205. ** the mutexes are omitted. Without the mutexes, it is not safe
  206. ** to use SQLite concurrently from more than one thread.
  207. **
  208. ** Enabling mutexes incurs a measurable performance penalty.
  209. ** So if speed is of utmost importance, it makes sense to disable
  210. ** the mutexes. But for maximum safety, mutexes should be enabled.
  211. ** ^The default behavior is for mutexes to be enabled.
  212. **
  213. ** This interface can be used by an application to make sure that the
  214. ** version of SQLite that it is linking against was compiled with
  215. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  216. **
  217. ** This interface only reports on the compile-time mutex setting
  218. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  219. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  220. ** can be fully or partially disabled using a call to [sqlite3_config()]
  221. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  222. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  223. ** sqlite3_threadsafe() function shows only the compile-time setting of
  224. ** thread safety, not any run-time changes to that setting made by
  225. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  226. ** is unchanged by calls to sqlite3_config().)^
  227. **
  228. ** See the [threading mode] documentation for additional information.
  229. */
  230. SQLITE_API int sqlite3_threadsafe(void);
  231. /*
  232. ** CAPI3REF: Database Connection Handle
  233. ** KEYWORDS: {database connection} {database connections}
  234. **
  235. ** Each open SQLite database is represented by a pointer to an instance of
  236. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  237. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  238. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  239. ** and [sqlite3_close_v2()] are its destructors. There are many other
  240. ** interfaces (such as
  241. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  242. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  243. ** sqlite3 object.
  244. */
  245. typedef struct sqlite3 sqlite3;
  246. /*
  247. ** CAPI3REF: 64-Bit Integer Types
  248. ** KEYWORDS: sqlite_int64 sqlite_uint64
  249. **
  250. ** Because there is no cross-platform way to specify 64-bit integer types
  251. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  252. **
  253. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  254. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  255. ** compatibility only.
  256. **
  257. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  258. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  259. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  260. ** between 0 and +18446744073709551615 inclusive.
  261. */
  262. #ifdef SQLITE_INT64_TYPE
  263. typedef SQLITE_INT64_TYPE sqlite_int64;
  264. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  265. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  266. typedef __int64 sqlite_int64;
  267. typedef unsigned __int64 sqlite_uint64;
  268. #else
  269. typedef long long int sqlite_int64;
  270. typedef unsigned long long int sqlite_uint64;
  271. #endif
  272. typedef sqlite_int64 sqlite3_int64;
  273. typedef sqlite_uint64 sqlite3_uint64;
  274. /*
  275. ** If compiling for a processor that lacks floating point support,
  276. ** substitute integer for floating-point.
  277. */
  278. #ifdef SQLITE_OMIT_FLOATING_POINT
  279. # define double sqlite3_int64
  280. #endif
  281. /*
  282. ** CAPI3REF: Closing A Database Connection
  283. **
  284. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  285. ** for the [sqlite3] object.
  286. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  287. ** the [sqlite3] object is successfully destroyed and all associated
  288. ** resources are deallocated.
  289. **
  290. ** ^If the database connection is associated with unfinalized prepared
  291. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  292. ** will leave the database connection open and return [SQLITE_BUSY].
  293. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  294. ** and unfinished sqlite3_backups, then the database connection becomes
  295. ** an unusable "zombie" which will automatically be deallocated when the
  296. ** last prepared statement is finalized or the last sqlite3_backup is
  297. ** finished. The sqlite3_close_v2() interface is intended for use with
  298. ** host languages that are garbage collected, and where the order in which
  299. ** destructors are called is arbitrary.
  300. **
  301. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  302. ** [sqlite3_blob_close | close] all [BLOB handles], and
  303. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  304. ** with the [sqlite3] object prior to attempting to close the object. ^If
  305. ** sqlite3_close_v2() is called on a [database connection] that still has
  306. ** outstanding [prepared statements], [BLOB handles], and/or
  307. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  308. ** of resources is deferred until all [prepared statements], [BLOB handles],
  309. ** and [sqlite3_backup] objects are also destroyed.
  310. **
  311. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  312. ** the transaction is automatically rolled back.
  313. **
  314. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  315. ** must be either a NULL
  316. ** pointer or an [sqlite3] object pointer obtained
  317. ** from [sqlite3_open()], [sqlite3_open16()], or
  318. ** [sqlite3_open_v2()], and not previously closed.
  319. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  320. ** argument is a harmless no-op.
  321. */
  322. SQLITE_API int sqlite3_close(sqlite3*);
  323. SQLITE_API int sqlite3_close_v2(sqlite3*);
  324. /*
  325. ** The type for a callback function.
  326. ** This is legacy and deprecated. It is included for historical
  327. ** compatibility and is not documented.
  328. */
  329. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  330. /*
  331. ** CAPI3REF: One-Step Query Execution Interface
  332. **
  333. ** The sqlite3_exec() interface is a convenience wrapper around
  334. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  335. ** that allows an application to run multiple statements of SQL
  336. ** without having to use a lot of C code.
  337. **
  338. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  339. ** semicolon-separate SQL statements passed into its 2nd argument,
  340. ** in the context of the [database connection] passed in as its 1st
  341. ** argument. ^If the callback function of the 3rd argument to
  342. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  343. ** coming out of the evaluated SQL statements. ^The 4th argument to
  344. ** sqlite3_exec() is relayed through to the 1st argument of each
  345. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  346. ** is NULL, then no callback is ever invoked and result rows are
  347. ** ignored.
  348. **
  349. ** ^If an error occurs while evaluating the SQL statements passed into
  350. ** sqlite3_exec(), then execution of the current statement stops and
  351. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  352. ** is not NULL then any error message is written into memory obtained
  353. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  354. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  355. ** on error message strings returned through the 5th parameter of
  356. ** of sqlite3_exec() after the error message string is no longer needed.
  357. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  358. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  359. ** NULL before returning.
  360. **
  361. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  362. ** routine returns SQLITE_ABORT without invoking the callback again and
  363. ** without running any subsequent SQL statements.
  364. **
  365. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  366. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  367. ** callback is an array of pointers to strings obtained as if from
  368. ** [sqlite3_column_text()], one for each column. ^If an element of a
  369. ** result row is NULL then the corresponding string pointer for the
  370. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  371. ** sqlite3_exec() callback is an array of pointers to strings where each
  372. ** entry represents the name of corresponding result column as obtained
  373. ** from [sqlite3_column_name()].
  374. **
  375. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  376. ** to an empty string, or a pointer that contains only whitespace and/or
  377. ** SQL comments, then no SQL statements are evaluated and the database
  378. ** is not changed.
  379. **
  380. ** Restrictions:
  381. **
  382. ** <ul>
  383. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  384. ** is a valid and open [database connection].
  385. ** <li> The application must not close [database connection] specified by
  386. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  387. ** <li> The application must not modify the SQL statement text passed into
  388. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  389. ** </ul>
  390. */
  391. SQLITE_API int sqlite3_exec(
  392. sqlite3*, /* An open database */
  393. const char *sql, /* SQL to be evaluated */
  394. int (*callback)(void*,int,char**,char**), /* Callback function */
  395. void *, /* 1st argument to callback */
  396. char **errmsg /* Error msg written here */
  397. );
  398. /*
  399. ** CAPI3REF: Result Codes
  400. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  401. ** KEYWORDS: {result code} {result codes}
  402. **
  403. ** Many SQLite functions return an integer result code from the set shown
  404. ** here in order to indicate success or failure.
  405. **
  406. ** New error codes may be added in future versions of SQLite.
  407. **
  408. ** See also: [SQLITE_IOERR_READ | extended result codes],
  409. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  410. */
  411. #define SQLITE_OK 0 /* Successful result */
  412. /* beginning-of-error-codes */
  413. #define SQLITE_ERROR 1 /* SQL error or missing database */
  414. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  415. #define SQLITE_PERM 3 /* Access permission denied */
  416. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  417. #define SQLITE_BUSY 5 /* The database file is locked */
  418. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  419. #define SQLITE_NOMEM 7 /* A malloc() failed */
  420. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  421. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  422. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  423. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  424. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  425. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  426. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  427. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  428. #define SQLITE_EMPTY 16 /* Database is empty */
  429. #define SQLITE_SCHEMA 17 /* The database schema changed */
  430. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  431. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  432. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  433. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  434. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  435. #define SQLITE_AUTH 23 /* Authorization denied */
  436. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  437. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  438. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  439. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  440. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  441. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  442. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  443. /* end-of-error-codes */
  444. /*
  445. ** CAPI3REF: Extended Result Codes
  446. ** KEYWORDS: {extended error code} {extended error codes}
  447. ** KEYWORDS: {extended result code} {extended result codes}
  448. **
  449. ** In its default configuration, SQLite API routines return one of 26 integer
  450. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  451. ** these result codes are too coarse-grained. They do not provide as
  452. ** much information about problems as programmers might like. In an effort to
  453. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  454. ** support for additional result codes that provide more detailed information
  455. ** about errors. The extended result codes are enabled or disabled
  456. ** on a per database connection basis using the
  457. ** [sqlite3_extended_result_codes()] API.
  458. **
  459. ** Some of the available extended result codes are listed here.
  460. ** One may expect the number of extended result codes will be expand
  461. ** over time. Software that uses extended result codes should expect
  462. ** to see new result codes in future releases of SQLite.
  463. **
  464. ** The SQLITE_OK result code will never be extended. It will always
  465. ** be exactly zero.
  466. */
  467. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  468. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  469. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  470. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  471. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  472. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  473. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  474. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  475. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  476. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  477. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  478. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  479. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  480. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  481. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  482. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  483. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  484. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  485. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  486. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  487. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  488. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  489. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  490. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  491. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  492. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  493. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  494. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  495. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  496. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  497. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  498. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  499. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  500. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  501. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  502. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  503. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  504. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  505. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  506. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  507. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  508. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  509. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  510. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  511. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  512. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  513. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  514. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  515. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  516. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  517. /*
  518. ** CAPI3REF: Flags For File Open Operations
  519. **
  520. ** These bit values are intended for use in the
  521. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  522. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  523. */
  524. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  525. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  526. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  527. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  528. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  529. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  530. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  531. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  532. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  533. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  534. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  535. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  536. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  537. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  538. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  539. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  540. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  541. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  542. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  543. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  544. /* Reserved: 0x00F00000 */
  545. /*
  546. ** CAPI3REF: Device Characteristics
  547. **
  548. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  549. ** object returns an integer which is a vector of these
  550. ** bit values expressing I/O characteristics of the mass storage
  551. ** device that holds the file that the [sqlite3_io_methods]
  552. ** refers to.
  553. **
  554. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  555. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  556. ** mean that writes of blocks that are nnn bytes in size and
  557. ** are aligned to an address which is an integer multiple of
  558. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  559. ** that when data is appended to a file, the data is appended
  560. ** first then the size of the file is extended, never the other
  561. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  562. ** information is written to disk in the same order as calls
  563. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  564. ** after reboot following a crash or power loss, the only bytes in a
  565. ** file that were written at the application level might have changed
  566. ** and that adjacent bytes, even bytes within the same sector are
  567. ** guaranteed to be unchanged.
  568. */
  569. #define SQLITE_IOCAP_ATOMIC 0x00000001
  570. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  571. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  572. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  573. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  574. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  575. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  576. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  577. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  578. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  579. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  580. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  581. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  582. /*
  583. ** CAPI3REF: File Locking Levels
  584. **
  585. ** SQLite uses one of these integer values as the second
  586. ** argument to calls it makes to the xLock() and xUnlock() methods
  587. ** of an [sqlite3_io_methods] object.
  588. */
  589. #define SQLITE_LOCK_NONE 0
  590. #define SQLITE_LOCK_SHARED 1
  591. #define SQLITE_LOCK_RESERVED 2
  592. #define SQLITE_LOCK_PENDING 3
  593. #define SQLITE_LOCK_EXCLUSIVE 4
  594. /*
  595. ** CAPI3REF: Synchronization Type Flags
  596. **
  597. ** When SQLite invokes the xSync() method of an
  598. ** [sqlite3_io_methods] object it uses a combination of
  599. ** these integer values as the second argument.
  600. **
  601. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  602. ** sync operation only needs to flush data to mass storage. Inode
  603. ** information need not be flushed. If the lower four bits of the flag
  604. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  605. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  606. ** to use Mac OS X style fullsync instead of fsync().
  607. **
  608. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  609. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  610. ** settings. The [synchronous pragma] determines when calls to the
  611. ** xSync VFS method occur and applies uniformly across all platforms.
  612. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  613. ** energetic or rigorous or forceful the sync operations are and
  614. ** only make a difference on Mac OSX for the default SQLite code.
  615. ** (Third-party VFS implementations might also make the distinction
  616. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  617. ** operating systems natively supported by SQLite, only Mac OSX
  618. ** cares about the difference.)
  619. */
  620. #define SQLITE_SYNC_NORMAL 0x00002
  621. #define SQLITE_SYNC_FULL 0x00003
  622. #define SQLITE_SYNC_DATAONLY 0x00010
  623. /*
  624. ** CAPI3REF: OS Interface Open File Handle
  625. **
  626. ** An [sqlite3_file] object represents an open file in the
  627. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  628. ** implementations will
  629. ** want to subclass this object by appending additional fields
  630. ** for their own use. The pMethods entry is a pointer to an
  631. ** [sqlite3_io_methods] object that defines methods for performing
  632. ** I/O operations on the open file.
  633. */
  634. typedef struct sqlite3_file sqlite3_file;
  635. struct sqlite3_file {
  636. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  637. };
  638. /*
  639. ** CAPI3REF: OS Interface File Virtual Methods Object
  640. **
  641. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  642. ** [sqlite3_file] object (or, more commonly, a subclass of the
  643. ** [sqlite3_file] object) with a pointer to an instance of this object.
  644. ** This object defines the methods used to perform various operations
  645. ** against the open file represented by the [sqlite3_file] object.
  646. **
  647. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  648. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  649. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  650. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  651. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  652. ** to NULL.
  653. **
  654. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  655. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  656. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  657. ** flag may be ORed in to indicate that only the data of the file
  658. ** and not its inode needs to be synced.
  659. **
  660. ** The integer values to xLock() and xUnlock() are one of
  661. ** <ul>
  662. ** <li> [SQLITE_LOCK_NONE],
  663. ** <li> [SQLITE_LOCK_SHARED],
  664. ** <li> [SQLITE_LOCK_RESERVED],
  665. ** <li> [SQLITE_LOCK_PENDING], or
  666. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  667. ** </ul>
  668. ** xLock() increases the lock. xUnlock() decreases the lock.
  669. ** The xCheckReservedLock() method checks whether any database connection,
  670. ** either in this process or in some other process, is holding a RESERVED,
  671. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  672. ** if such a lock exists and false otherwise.
  673. **
  674. ** The xFileControl() method is a generic interface that allows custom
  675. ** VFS implementations to directly control an open file using the
  676. ** [sqlite3_file_control()] interface. The second "op" argument is an
  677. ** integer opcode. The third argument is a generic pointer intended to
  678. ** point to a structure that may contain arguments or space in which to
  679. ** write return values. Potential uses for xFileControl() might be
  680. ** functions to enable blocking locks with timeouts, to change the
  681. ** locking strategy (for example to use dot-file locks), to inquire
  682. ** about the status of a lock, or to break stale locks. The SQLite
  683. ** core reserves all opcodes less than 100 for its own use.
  684. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  685. ** Applications that define a custom xFileControl method should use opcodes
  686. ** greater than 100 to avoid conflicts. VFS implementations should
  687. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  688. ** recognize.
  689. **
  690. ** The xSectorSize() method returns the sector size of the
  691. ** device that underlies the file. The sector size is the
  692. ** minimum write that can be performed without disturbing
  693. ** other bytes in the file. The xDeviceCharacteristics()
  694. ** method returns a bit vector describing behaviors of the
  695. ** underlying device:
  696. **
  697. ** <ul>
  698. ** <li> [SQLITE_IOCAP_ATOMIC]
  699. ** <li> [SQLITE_IOCAP_ATOMIC512]
  700. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  701. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  702. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  703. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  704. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  705. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  706. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  707. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  708. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  709. ** </ul>
  710. **
  711. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  712. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  713. ** mean that writes of blocks that are nnn bytes in size and
  714. ** are aligned to an address which is an integer multiple of
  715. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  716. ** that when data is appended to a file, the data is appended
  717. ** first then the size of the file is extended, never the other
  718. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  719. ** information is written to disk in the same order as calls
  720. ** to xWrite().
  721. **
  722. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  723. ** in the unread portions of the buffer with zeros. A VFS that
  724. ** fails to zero-fill short reads might seem to work. However,
  725. ** failure to zero-fill short reads will eventually lead to
  726. ** database corruption.
  727. */
  728. typedef struct sqlite3_io_methods sqlite3_io_methods;
  729. struct sqlite3_io_methods {
  730. int iVersion;
  731. int (*xClose)(sqlite3_file*);
  732. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  733. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  734. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  735. int (*xSync)(sqlite3_file*, int flags);
  736. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  737. int (*xLock)(sqlite3_file*, int);
  738. int (*xUnlock)(sqlite3_file*, int);
  739. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  740. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  741. int (*xSectorSize)(sqlite3_file*);
  742. int (*xDeviceCharacteristics)(sqlite3_file*);
  743. /* Methods above are valid for version 1 */
  744. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  745. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  746. void (*xShmBarrier)(sqlite3_file*);
  747. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  748. /* Methods above are valid for version 2 */
  749. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  750. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  751. /* Methods above are valid for version 3 */
  752. /* Additional methods may be added in future releases */
  753. };
  754. /*
  755. ** CAPI3REF: Standard File Control Opcodes
  756. **
  757. ** These integer constants are opcodes for the xFileControl method
  758. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  759. ** interface.
  760. **
  761. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  762. ** opcode causes the xFileControl method to write the current state of
  763. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  764. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  765. ** into an integer that the pArg argument points to. This capability
  766. ** is used during testing and only needs to be supported when SQLITE_TEST
  767. ** is defined.
  768. ** <ul>
  769. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  770. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  771. ** layer a hint of how large the database file will grow to be during the
  772. ** current transaction. This hint is not guaranteed to be accurate but it
  773. ** is often close. The underlying VFS might choose to preallocate database
  774. ** file space based on this hint in order to help writes to the database
  775. ** file run faster.
  776. **
  777. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  778. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  779. ** extends and truncates the database file in chunks of a size specified
  780. ** by the user. The fourth argument to [sqlite3_file_control()] should
  781. ** point to an integer (type int) containing the new chunk-size to use
  782. ** for the nominated database. Allocating database file space in large
  783. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  784. ** improve performance on some systems.
  785. **
  786. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  787. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  788. ** to the [sqlite3_file] object associated with a particular database
  789. ** connection. See the [sqlite3_file_control()] documentation for
  790. ** additional information.
  791. **
  792. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  793. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  794. ** SQLite and sent to all VFSes in place of a call to the xSync method
  795. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  796. ** Some specialized VFSes need this signal in order to operate correctly
  797. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  798. ** VFSes do not need this signal and should silently ignore this opcode.
  799. ** Applications should not call [sqlite3_file_control()] with this
  800. ** opcode as doing so may disrupt the operation of the specialized VFSes
  801. ** that do require it.
  802. **
  803. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  804. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  805. ** retry counts and intervals for certain disk I/O operations for the
  806. ** windows [VFS] in order to provide robustness in the presence of
  807. ** anti-virus programs. By default, the windows VFS will retry file read,
  808. ** file write, and file delete operations up to 10 times, with a delay
  809. ** of 25 milliseconds before the first retry and with the delay increasing
  810. ** by an additional 25 milliseconds with each subsequent retry. This
  811. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  812. ** to be adjusted. The values are changed for all database connections
  813. ** within the same process. The argument is a pointer to an array of two
  814. ** integers where the first integer i the new retry count and the second
  815. ** integer is the delay. If either integer is negative, then the setting
  816. ** is not changed but instead the prior value of that setting is written
  817. ** into the array entry, allowing the current retry settings to be
  818. ** interrogated. The zDbName parameter is ignored.
  819. **
  820. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  821. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  822. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  823. ** write ahead log and shared memory files used for transaction control
  824. ** are automatically deleted when the latest connection to the database
  825. ** closes. Setting persistent WAL mode causes those files to persist after
  826. ** close. Persisting the files is useful when other processes that do not
  827. ** have write permission on the directory containing the database file want
  828. ** to read the database file, as the WAL and shared memory files must exist
  829. ** in order for the database to be readable. The fourth parameter to
  830. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  831. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  832. ** WAL mode. If the integer is -1, then it is overwritten with the current
  833. ** WAL persistence setting.
  834. **
  835. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  836. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  837. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  838. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  839. ** xDeviceCharacteristics methods. The fourth parameter to
  840. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  841. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  842. ** mode. If the integer is -1, then it is overwritten with the current
  843. ** zero-damage mode setting.
  844. **
  845. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  846. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  847. ** a write transaction to indicate that, unless it is rolled back for some
  848. ** reason, the entire database file will be overwritten by the current
  849. ** transaction. This is used by VACUUM operations.
  850. **
  851. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  852. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  853. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  854. ** final bottom-level VFS are written into memory obtained from
  855. ** [sqlite3_malloc()] and the result is stored in the char* variable
  856. ** that the fourth parameter of [sqlite3_file_control()] points to.
  857. ** The caller is responsible for freeing the memory when done. As with
  858. ** all file-control actions, there is no guarantee that this will actually
  859. ** do anything. Callers should initialize the char* variable to a NULL
  860. ** pointer in case this file-control is not implemented. This file-control
  861. ** is intended for diagnostic use only.
  862. **
  863. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  864. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  865. ** file control is sent to the open [sqlite3_file] object corresponding
  866. ** to the database file to which the pragma statement refers. ^The argument
  867. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  868. ** pointers to strings (char**) in which the second element of the array
  869. ** is the name of the pragma and the third element is the argument to the
  870. ** pragma or NULL if the pragma has no argument. ^The handler for an
  871. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  872. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  873. ** or the equivalent and that string will become the result of the pragma or
  874. ** the error message if the pragma fails. ^If the
  875. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  876. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  877. ** file control returns [SQLITE_OK], then the parser assumes that the
  878. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  879. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  880. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  881. ** that the VFS encountered an error while handling the [PRAGMA] and the
  882. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  883. ** file control occurs at the beginning of pragma statement analysis and so
  884. ** it is able to override built-in [PRAGMA] statements.
  885. **
  886. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  887. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  888. ** file-control may be invoked by SQLite on the database file handle
  889. ** shortly after it is opened in order to provide a custom VFS with access
  890. ** to the connections busy-handler callback. The argument is of type (void **)
  891. ** - an array of two (void *) values. The first (void *) actually points
  892. ** to a function of type (int (*)(void *)). In order to invoke the connections
  893. ** busy-handler, this function should be invoked with the second (void *) in
  894. ** the array as the only argument. If it returns non-zero, then the operation
  895. ** should be retried. If it returns zero, the custom VFS should abandon the
  896. ** current operation.
  897. **
  898. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  899. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  900. ** to have SQLite generate a
  901. ** temporary filename using the same algorithm that is followed to generate
  902. ** temporary filenames for TEMP tables and other internal uses. The
  903. ** argument should be a char** which will be filled with the filename
  904. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  905. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  906. **
  907. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  908. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  909. ** maximum number of bytes that will be used for memory-mapped I/O.
  910. ** The argument is a pointer to a value of type sqlite3_int64 that
  911. ** is an advisory maximum number of bytes in the file to memory map. The
  912. ** pointer is overwritten with the old value. The limit is not changed if
  913. ** the value originally pointed to is negative, and so the current limit
  914. ** can be queried by passing in a pointer to a negative number. This
  915. ** file-control is used internally to implement [PRAGMA mmap_size].
  916. **
  917. ** </ul>
  918. */
  919. #define SQLITE_FCNTL_LOCKSTATE 1
  920. #define SQLITE_GET_LOCKPROXYFILE 2
  921. #define SQLITE_SET_LOCKPROXYFILE 3
  922. #define SQLITE_LAST_ERRNO 4
  923. #define SQLITE_FCNTL_SIZE_HINT 5
  924. #define SQLITE_FCNTL_CHUNK_SIZE 6
  925. #define SQLITE_FCNTL_FILE_POINTER 7
  926. #define SQLITE_FCNTL_SYNC_OMITTED 8
  927. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  928. #define SQLITE_FCNTL_PERSIST_WAL 10
  929. #define SQLITE_FCNTL_OVERWRITE 11
  930. #define SQLITE_FCNTL_VFSNAME 12
  931. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  932. #define SQLITE_FCNTL_PRAGMA 14
  933. #define SQLITE_FCNTL_BUSYHANDLER 15
  934. #define SQLITE_FCNTL_TEMPFILENAME 16
  935. #define SQLITE_FCNTL_MMAP_SIZE 18
  936. /*
  937. ** CAPI3REF: Mutex Handle
  938. **
  939. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  940. ** abstract type for a mutex object. The SQLite core never looks
  941. ** at the internal representation of an [sqlite3_mutex]. It only
  942. ** deals with pointers to the [sqlite3_mutex] object.
  943. **
  944. ** Mutexes are created using [sqlite3_mutex_alloc()].
  945. */
  946. typedef struct sqlite3_mutex sqlite3_mutex;
  947. /*
  948. ** CAPI3REF: OS Interface Object
  949. **
  950. ** An instance of the sqlite3_vfs object defines the interface between
  951. ** the SQLite core and the underlying operating system. The "vfs"
  952. ** in the name of the object stands for "virtual file system". See
  953. ** the [VFS | VFS documentation] for further information.
  954. **
  955. ** The value of the iVersion field is initially 1 but may be larger in
  956. ** future versions of SQLite. Additional fields may be appended to this
  957. ** object when the iVersion value is increased. Note that the structure
  958. ** of the sqlite3_vfs object changes in the transaction between
  959. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  960. ** modified.
  961. **
  962. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  963. ** structure used by this VFS. mxPathname is the maximum length of
  964. ** a pathname in this VFS.
  965. **
  966. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  967. ** the pNext pointer. The [sqlite3_vfs_register()]
  968. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  969. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  970. ** searches the list. Neither the application code nor the VFS
  971. ** implementation should use the pNext pointer.
  972. **
  973. ** The pNext field is the only field in the sqlite3_vfs
  974. ** structure that SQLite will ever modify. SQLite will only access
  975. ** or modify this field while holding a particular static mutex.
  976. ** The application should never modify anything within the sqlite3_vfs
  977. ** object once the object has been registered.
  978. **
  979. ** The zName field holds the name of the VFS module. The name must
  980. ** be unique across all VFS modules.
  981. **
  982. ** [[sqlite3_vfs.xOpen]]
  983. ** ^SQLite guarantees that the zFilename parameter to xOpen
  984. ** is either a NULL pointer or string obtained
  985. ** from xFullPathname() with an optional suffix added.
  986. ** ^If a suffix is added to the zFilename parameter, it will
  987. ** consist of a single "-" character followed by no more than
  988. ** 11 alphanumeric and/or "-" characters.
  989. ** ^SQLite further guarantees that
  990. ** the string will be valid and unchanged until xClose() is
  991. ** called. Because of the previous sentence,
  992. ** the [sqlite3_file] can safely store a pointer to the
  993. ** filename if it needs to remember the filename for some reason.
  994. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  995. ** must invent its own temporary name for the file. ^Whenever the
  996. ** xFilename parameter is NULL it will also be the case that the
  997. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  998. **
  999. ** The flags argument to xOpen() includes all bits set in
  1000. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1001. ** or [sqlite3_open16()] is used, then flags includes at least
  1002. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1003. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1004. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1005. **
  1006. ** ^(SQLite will also add one of the following flags to the xOpen()
  1007. ** call, depending on the object being opened:
  1008. **
  1009. ** <ul>
  1010. ** <li> [SQLITE_OPEN_MAIN_DB]
  1011. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1012. ** <li> [SQLITE_OPEN_TEMP_DB]
  1013. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1014. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1015. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1016. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1017. ** <li> [SQLITE_OPEN_WAL]
  1018. ** </ul>)^
  1019. **
  1020. ** The file I/O implementation can use the object type flags to
  1021. ** change the way it deals with files. For example, an application
  1022. ** that does not care about crash recovery or rollback might make
  1023. ** the open of a journal file a no-op. Writes to this journal would
  1024. ** also be no-ops, and any attempt to read the journal would return
  1025. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1026. ** file will be doing page-aligned sector reads and writes in a random
  1027. ** order and set up its I/O subsystem accordingly.
  1028. **
  1029. ** SQLite might also add one of the following flags to the xOpen method:
  1030. **
  1031. ** <ul>
  1032. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1033. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1034. ** </ul>
  1035. **
  1036. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1037. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1038. ** will be set for TEMP databases and their journals, transient
  1039. ** databases, and subjournals.
  1040. **
  1041. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1042. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1043. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1044. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1045. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1046. ** be created, and that it is an error if it already exists.
  1047. ** It is <i>not</i> used to indicate the file should be opened
  1048. ** for exclusive access.
  1049. **
  1050. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1051. ** to hold the [sqlite3_file] structure passed as the third
  1052. ** argument to xOpen. The xOpen method does not have to
  1053. ** allocate the structure; it should just fill it in. Note that
  1054. ** the xOpen method must set the sqlite3_file.pMethods to either
  1055. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1056. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1057. ** element will be valid after xOpen returns regardless of the success
  1058. ** or failure of the xOpen call.
  1059. **
  1060. ** [[sqlite3_vfs.xAccess]]
  1061. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1062. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1063. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1064. ** to test whether a file is at least readable. The file can be a
  1065. ** directory.
  1066. **
  1067. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1068. ** output buffer xFullPathname. The exact size of the output buffer
  1069. ** is also passed as a parameter to both methods. If the output buffer
  1070. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1071. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1072. ** to prevent this by setting mxPathname to a sufficiently large value.
  1073. **
  1074. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1075. ** interfaces are not strictly a part of the filesystem, but they are
  1076. ** included in the VFS structure for completeness.
  1077. ** The xRandomness() function attempts to return nBytes bytes
  1078. ** of good-quality randomness into zOut. The return value is
  1079. ** the actual number of bytes of randomness obtained.
  1080. ** The xSleep() method causes the calling thread to sleep for at
  1081. ** least the number of microseconds given. ^The xCurrentTime()
  1082. ** method returns a Julian Day Number for the current date and time as
  1083. ** a floating point value.
  1084. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1085. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1086. ** a 24-hour day).
  1087. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1088. ** date and time if that method is available (if iVersion is 2 or
  1089. ** greater and the function pointer is not NULL) and will fall back
  1090. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1091. **
  1092. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1093. ** are not used by the SQLite core. These optional interfaces are provided
  1094. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1095. ** system calls with functions under its control, a test program can
  1096. ** simulate faults and error conditions that would otherwise be difficult
  1097. ** or impossible to induce. The set of system calls that can be overridden
  1098. ** varies from one VFS to another, and from one version of the same VFS to the
  1099. ** next. Applications that use these interfaces must be prepared for any
  1100. ** or all of these interfaces to be NULL or for their behavior to change
  1101. ** from one release to the next. Applications must not attempt to access
  1102. ** any of these methods if the iVersion of the VFS is less than 3.
  1103. */
  1104. typedef struct sqlite3_vfs sqlite3_vfs;
  1105. typedef void (*sqlite3_syscall_ptr)(void);
  1106. struct sqlite3_vfs {
  1107. int iVersion; /* Structure version number (currently 3) */
  1108. int szOsFile; /* Size of subclassed sqlite3_file */
  1109. int mxPathname; /* Maximum file pathname length */
  1110. sqlite3_vfs *pNext; /* Next registered VFS */
  1111. const char *zName; /* Name of this virtual file system */
  1112. void *pAppData; /* Pointer to application-specific data */
  1113. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1114. int flags, int *pOutFlags);
  1115. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1116. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1117. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1118. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1119. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1120. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1121. void (*xDlClose)(sqlite3_vfs*, void*);
  1122. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1123. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1124. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1125. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1126. /*
  1127. ** The methods above are in version 1 of the sqlite_vfs object
  1128. ** definition. Those that follow are added in version 2 or later
  1129. */
  1130. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1131. /*
  1132. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1133. ** Those below are for version 3 and greater.
  1134. */
  1135. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1136. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1137. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1138. /*
  1139. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1140. ** New fields may be appended in figure versions. The iVersion
  1141. ** value will increment whenever this happens.
  1142. */
  1143. };
  1144. /*
  1145. ** CAPI3REF: Flags for the xAccess VFS method
  1146. **
  1147. ** These integer constants can be used as the third parameter to
  1148. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1149. ** what kind of permissions the xAccess method is looking for.
  1150. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1151. ** simply checks whether the file exists.
  1152. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1153. ** checks whether the named directory is both readable and writable
  1154. ** (in other words, if files can be added, removed, and renamed within
  1155. ** the directory).
  1156. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1157. ** [temp_store_directory pragma], though this could change in a future
  1158. ** release of SQLite.
  1159. ** With SQLITE_ACCESS_READ, the xAccess method
  1160. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1161. ** currently unused, though it might be used in a future release of
  1162. ** SQLite.
  1163. */
  1164. #define SQLITE_ACCESS_EXISTS 0
  1165. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1166. #define SQLITE_ACCESS_READ 2 /* Unused */
  1167. /*
  1168. ** CAPI3REF: Flags for the xShmLock VFS method
  1169. **
  1170. ** These integer constants define the various locking operations
  1171. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1172. ** following are the only legal combinations of flags to the
  1173. ** xShmLock method:
  1174. **
  1175. ** <ul>
  1176. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1177. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1178. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1179. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1180. ** </ul>
  1181. **
  1182. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1183. ** was given no the corresponding lock.
  1184. **
  1185. ** The xShmLock method can transition between unlocked and SHARED or
  1186. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1187. ** and EXCLUSIVE.
  1188. */
  1189. #define SQLITE_SHM_UNLOCK 1
  1190. #define SQLITE_SHM_LOCK 2
  1191. #define SQLITE_SHM_SHARED 4
  1192. #define SQLITE_SHM_EXCLUSIVE 8
  1193. /*
  1194. ** CAPI3REF: Maximum xShmLock index
  1195. **
  1196. ** The xShmLock method on [sqlite3_io_methods] may use values
  1197. ** between 0 and this upper bound as its "offset" argument.
  1198. ** The SQLite core will never attempt to acquire or release a
  1199. ** lock outside of this range
  1200. */
  1201. #define SQLITE_SHM_NLOCK 8
  1202. /*
  1203. ** CAPI3REF: Initialize The SQLite Library
  1204. **
  1205. ** ^The sqlite3_initialize() routine initializes the
  1206. ** SQLite library. ^The sqlite3_shutdown() routine
  1207. ** deallocates any resources that were allocated by sqlite3_initialize().
  1208. ** These routines are designed to aid in process initialization and
  1209. ** shutdown on embedded systems. Workstation applications using
  1210. ** SQLite normally do not need to invoke either of these routines.
  1211. **
  1212. ** A call to sqlite3_initialize() is an "effective" call if it is
  1213. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1214. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1215. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1216. ** of sqlite3_initialize() does any initialization. All other calls
  1217. ** are harmless no-ops.)^
  1218. **
  1219. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1220. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1221. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1222. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1223. **
  1224. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1225. ** is not. The sqlite3_shutdown() interface must only be called from a
  1226. ** single thread. All open [database connections] must be closed and all
  1227. ** other SQLite resources must be deallocated prior to invoking
  1228. ** sqlite3_shutdown().
  1229. **
  1230. ** Among other things, ^sqlite3_initialize() will invoke
  1231. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1232. ** will invoke sqlite3_os_end().
  1233. **
  1234. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1235. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1236. ** the library (perhaps it is unable to allocate a needed resource such
  1237. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1238. **
  1239. ** ^The sqlite3_initialize() routine is called internally by many other
  1240. ** SQLite interfaces so that an application usually does not need to
  1241. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1242. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1243. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1244. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1245. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1246. ** are omitted and the application must call sqlite3_initialize() directly
  1247. ** prior to using any other SQLite interface. For maximum portability,
  1248. ** it is recommended that applications always invoke sqlite3_initialize()
  1249. ** directly prior to using any other SQLite interface. Future releases
  1250. ** of SQLite may require this. In other words, the behavior exhibited
  1251. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1252. ** default behavior in some future release of SQLite.
  1253. **
  1254. ** The sqlite3_os_init() routine does operating-system specific
  1255. ** initialization of the SQLite library. The sqlite3_os_end()
  1256. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1257. ** performed by these routines include allocation or deallocation
  1258. ** of static resources, initialization of global variables,
  1259. ** setting up a default [sqlite3_vfs] module, or setting up
  1260. ** a default configuration using [sqlite3_config()].
  1261. **
  1262. ** The application should never invoke either sqlite3_os_init()
  1263. ** or sqlite3_os_end() directly. The application should only invoke
  1264. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1265. ** interface is called automatically by sqlite3_initialize() and
  1266. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1267. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1268. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1269. ** When [custom builds | built for other platforms]
  1270. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1271. ** option) the application must supply a suitable implementation for
  1272. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1273. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1274. ** must return [SQLITE_OK] on success and some other [error code] upon
  1275. ** failure.
  1276. */
  1277. SQLITE_API int sqlite3_initialize(void);
  1278. SQLITE_API int sqlite3_shutdown(void);
  1279. SQLITE_API int sqlite3_os_init(void);
  1280. SQLITE_API int sqlite3_os_end(void);
  1281. /*
  1282. ** CAPI3REF: Configuring The SQLite Library
  1283. **
  1284. ** The sqlite3_config() interface is used to make global configuration
  1285. ** changes to SQLite in order to tune SQLite to the specific needs of
  1286. ** the application. The default configuration is recommended for most
  1287. ** applications and so this routine is usually not necessary. It is
  1288. ** provided to support rare applications with unusual needs.
  1289. **
  1290. ** The sqlite3_config() interface is not threadsafe. The application
  1291. ** must insure that no other SQLite interfaces are invoked by other
  1292. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1293. ** may only be invoked prior to library initialization using
  1294. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1295. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1296. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1297. ** Note, however, that ^sqlite3_config() can be called as part of the
  1298. ** implementation of an application-defined [sqlite3_os_init()].
  1299. **
  1300. ** The first argument to sqlite3_config() is an integer
  1301. ** [configuration option] that determines
  1302. ** what property of SQLite is to be configured. Subsequent arguments
  1303. ** vary depending on the [configuration option]
  1304. ** in the first argument.
  1305. **
  1306. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1307. ** ^If the option is unknown or SQLite is unable to set the option
  1308. ** then this routine returns a non-zero [error code].
  1309. */
  1310. SQLITE_API int sqlite3_config(int, ...);
  1311. /*
  1312. ** CAPI3REF: Configure database connections
  1313. **
  1314. ** The sqlite3_db_config() interface is used to make configuration
  1315. ** changes to a [database connection]. The interface is similar to
  1316. ** [sqlite3_config()] except that the changes apply to a single
  1317. ** [database connection] (specified in the first argument).
  1318. **
  1319. ** The second argument to sqlite3_db_config(D,V,...) is the
  1320. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1321. ** that indicates what aspect of the [database connection] is being configured.
  1322. ** Subsequent arguments vary depending on the configuration verb.
  1323. **
  1324. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1325. ** the call is considered successful.
  1326. */
  1327. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1328. /*
  1329. ** CAPI3REF: Memory Allocation Routines
  1330. **
  1331. ** An instance of this object defines the interface between SQLite
  1332. ** and low-level memory allocation routines.
  1333. **
  1334. ** This object is used in only one place in the SQLite interface.
  1335. ** A pointer to an instance of this object is the argument to
  1336. ** [sqlite3_config()] when the configuration option is
  1337. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1338. ** By creating an instance of this object
  1339. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1340. ** during configuration, an application can specify an alternative
  1341. ** memory allocation subsystem for SQLite to use for all of its
  1342. ** dynamic memory needs.
  1343. **
  1344. ** Note that SQLite comes with several [built-in memory allocators]
  1345. ** that are perfectly adequate for the overwhelming majority of applications
  1346. ** and that this object is only useful to a tiny minority of applications
  1347. ** with specialized memory allocation requirements. This object is
  1348. ** also used during testing of SQLite in order to specify an alternative
  1349. ** memory allocator that simulates memory out-of-memory conditions in
  1350. ** order to verify that SQLite recovers gracefully from such
  1351. ** conditions.
  1352. **
  1353. ** The xMalloc, xRealloc, and xFree methods must work like the
  1354. ** malloc(), realloc() and free() functions from the standard C library.
  1355. ** ^SQLite guarantees that the second argument to
  1356. ** xRealloc is always a value returned by a prior call to xRoundup.
  1357. **
  1358. ** xSize should return the allocated size of a memory allocation
  1359. ** previously obtained from xMalloc or xRealloc. The allocated size
  1360. ** is always at least as big as the requested size but may be larger.
  1361. **
  1362. ** The xRoundup method returns what would be the allocated size of
  1363. ** a memory allocation given a particular requested size. Most memory
  1364. ** allocators round up memory allocations at least to the next multiple
  1365. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1366. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1367. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1368. ** that causes the corresponding memory allocation to fail.
  1369. **
  1370. ** The xInit method initializes the memory allocator. (For example,
  1371. ** it might allocate any require mutexes or initialize internal data
  1372. ** structures. The xShutdown method is invoked (indirectly) by
  1373. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1374. ** by xInit. The pAppData pointer is used as the only parameter to
  1375. ** xInit and xShutdown.
  1376. **
  1377. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1378. ** the xInit method, so the xInit method need not be threadsafe. The
  1379. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1380. ** not need to be threadsafe either. For all other methods, SQLite
  1381. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1382. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1383. ** it is by default) and so the methods are automatically serialized.
  1384. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1385. ** methods must be threadsafe or else make their own arrangements for
  1386. ** serialization.
  1387. **
  1388. ** SQLite will never invoke xInit() more than once without an intervening
  1389. ** call to xShutdown().
  1390. */
  1391. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1392. struct sqlite3_mem_methods {
  1393. void *(*xMalloc)(int); /* Memory allocation function */
  1394. void (*xFree)(void*); /* Free a prior allocation */
  1395. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1396. int (*xSize)(void*); /* Return the size of an allocation */
  1397. int (*xRoundup)(int); /* Round up request size to allocation size */
  1398. int (*xInit)(void*); /* Initialize the memory allocator */
  1399. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1400. void *pAppData; /* Argument to xInit() and xShutdown() */
  1401. };
  1402. /*
  1403. ** CAPI3REF: Configuration Options
  1404. ** KEYWORDS: {configuration option}
  1405. **
  1406. ** These constants are the available integer configuration options that
  1407. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1408. **
  1409. ** New configuration options may be added in future releases of SQLite.
  1410. ** Existing configuration options might be discontinued. Applications
  1411. ** should check the return code from [sqlite3_config()] to make sure that
  1412. ** the call worked. The [sqlite3_config()] interface will return a
  1413. ** non-zero [error code] if a discontinued or unsupported configuration option
  1414. ** is invoked.
  1415. **
  1416. ** <dl>
  1417. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1418. ** <dd>There are no arguments to this option. ^This option sets the
  1419. ** [threading mode] to Single-thread. In other words, it disables
  1420. ** all mutexing and puts SQLite into a mode where it can only be used
  1421. ** by a single thread. ^If SQLite is compiled with
  1422. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1423. ** it is not possible to change the [threading mode] from its default
  1424. ** value of Single-thread and so [sqlite3_config()] will return
  1425. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1426. ** configuration option.</dd>
  1427. **
  1428. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1429. ** <dd>There are no arguments to this option. ^This option sets the
  1430. ** [threading mode] to Multi-thread. In other words, it disables
  1431. ** mutexing on [database connection] and [prepared statement] objects.
  1432. ** The application is responsible for serializing access to
  1433. ** [database connections] and [prepared statements]. But other mutexes
  1434. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1435. ** environment as long as no two threads attempt to use the same
  1436. ** [database connection] at the same time. ^If SQLite is compiled with
  1437. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1438. ** it is not possible to set the Multi-thread [threading mode] and
  1439. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1440. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1441. **
  1442. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1443. ** <dd>There are no arguments to this option. ^This option sets the
  1444. ** [threading mode] to Serialized. In other words, this option enables
  1445. ** all mutexes including the recursive
  1446. ** mutexes on [database connection] and [prepared statement] objects.
  1447. ** In this mode (which is the default when SQLite is compiled with
  1448. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1449. ** to [database connections] and [prepared statements] so that the
  1450. ** application is free to use the same [database connection] or the
  1451. ** same [prepared statement] in different threads at the same time.
  1452. ** ^If SQLite is compiled with
  1453. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1454. ** it is not possible to set the Serialized [threading mode] and
  1455. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1456. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1457. **
  1458. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1459. ** <dd> ^(This option takes a single argument which is a pointer to an
  1460. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1461. ** alternative low-level memory allocation routines to be used in place of
  1462. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1463. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1464. ** before the [sqlite3_config()] call returns.</dd>
  1465. **
  1466. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1467. ** <dd> ^(This option takes a single argument which is a pointer to an
  1468. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1469. ** structure is filled with the currently defined memory allocation routines.)^
  1470. ** This option can be used to overload the default memory allocation
  1471. ** routines with a wrapper that simulations memory allocation failure or
  1472. ** tracks memory usage, for example. </dd>
  1473. **
  1474. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1475. ** <dd> ^This option takes single argument of type int, interpreted as a
  1476. ** boolean, which enables or disables the collection of memory allocation
  1477. ** statistics. ^(When memory allocation statistics are disabled, the
  1478. ** following SQLite interfaces become non-operational:
  1479. ** <ul>
  1480. ** <li> [sqlite3_memory_used()]
  1481. ** <li> [sqlite3_memory_highwater()]
  1482. ** <li> [sqlite3_soft_heap_limit64()]
  1483. ** <li> [sqlite3_status()]
  1484. ** </ul>)^
  1485. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1486. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1487. ** allocation statistics are disabled by default.
  1488. ** </dd>
  1489. **
  1490. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1491. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1492. ** scratch memory. There are three arguments: A pointer an 8-byte
  1493. ** aligned memory buffer from which the scratch allocations will be
  1494. ** drawn, the size of each scratch allocation (sz),
  1495. ** and the maximum number of scratch allocations (N). The sz
  1496. ** argument must be a multiple of 16.
  1497. ** The first argument must be a pointer to an 8-byte aligned buffer
  1498. ** of at least sz*N bytes of memory.
  1499. ** ^SQLite will use no more than two scratch buffers per thread. So
  1500. ** N should be set to twice the expected maximum number of threads.
  1501. ** ^SQLite will never require a scratch buffer that is more than 6
  1502. ** times the database page size. ^If SQLite needs needs additional
  1503. ** scratch memory beyond what is provided by this configuration option, then
  1504. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1505. **
  1506. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1507. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1508. ** the database page cache with the default page cache implementation.
  1509. ** This configuration should not be used if an application-define page
  1510. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1511. ** There are three arguments to this option: A pointer to 8-byte aligned
  1512. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1513. ** The sz argument should be the size of the largest database page
  1514. ** (a power of two between 512 and 32768) plus a little extra for each
  1515. ** page header. ^The page header size is 20 to 40 bytes depending on
  1516. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1517. ** to make sz a little too large. The first
  1518. ** argument should point to an allocation of at least sz*N bytes of memory.
  1519. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1520. ** memory needs for the first N pages that it adds to cache. ^If additional
  1521. ** page cache memory is needed beyond what is provided by this option, then
  1522. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1523. ** The pointer in the first argument must
  1524. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1525. ** will be undefined.</dd>
  1526. **
  1527. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1528. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1529. ** for all of its dynamic memory allocation needs beyond those provided
  1530. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1531. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1532. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1533. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1534. ** to using its default memory allocator (the system malloc() implementation),
  1535. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1536. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1537. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1538. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1539. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1540. ** boundary or subsequent behavior of SQLite will be undefined.
  1541. ** The minimum allocation size is capped at 2**12. Reasonable values
  1542. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1543. **
  1544. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1545. ** <dd> ^(This option takes a single argument which is a pointer to an
  1546. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1547. ** alternative low-level mutex routines to be used in place
  1548. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1549. ** content of the [sqlite3_mutex_methods] structure before the call to
  1550. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1551. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1552. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1553. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1554. ** return [SQLITE_ERROR].</dd>
  1555. **
  1556. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1557. ** <dd> ^(This option takes a single argument which is a pointer to an
  1558. ** instance of the [sqlite3_mutex_methods] structure. The
  1559. ** [sqlite3_mutex_methods]
  1560. ** structure is filled with the currently defined mutex routines.)^
  1561. ** This option can be used to overload the default mutex allocation
  1562. ** routines with a wrapper used to track mutex usage for performance
  1563. ** profiling or testing, for example. ^If SQLite is compiled with
  1564. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1565. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1566. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1567. ** return [SQLITE_ERROR].</dd>
  1568. **
  1569. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1570. ** <dd> ^(This option takes two arguments that determine the default
  1571. ** memory allocation for the lookaside memory allocator on each
  1572. ** [database connection]. The first argument is the
  1573. ** size of each lookaside buffer slot and the second is the number of
  1574. ** slots allocated to each database connection.)^ ^(This option sets the
  1575. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1576. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1577. ** configuration on individual connections.)^ </dd>
  1578. **
  1579. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1580. ** <dd> ^(This option takes a single argument which is a pointer to
  1581. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1582. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1583. ** object and uses it for page cache memory allocations.</dd>
  1584. **
  1585. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1586. ** <dd> ^(This option takes a single argument which is a pointer to an
  1587. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1588. ** page cache implementation into that object.)^ </dd>
  1589. **
  1590. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1591. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1592. ** global [error log].
  1593. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1594. ** function with a call signature of void(*)(void*,int,const char*),
  1595. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1596. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1597. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1598. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1599. ** passed through as the first parameter to the application-defined logger
  1600. ** function whenever that function is invoked. ^The second parameter to
  1601. ** the logger function is a copy of the first parameter to the corresponding
  1602. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1603. ** [extended result code]. ^The third parameter passed to the logger is
  1604. ** log message after formatting via [sqlite3_snprintf()].
  1605. ** The SQLite logging interface is not reentrant; the logger function
  1606. ** supplied by the application must not invoke any SQLite interface.
  1607. ** In a multi-threaded application, the application-defined logger
  1608. ** function must be threadsafe. </dd>
  1609. **
  1610. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1611. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1612. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1613. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1614. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1615. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1616. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1617. ** connection is opened. ^If it is globally disabled, filenames are
  1618. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1619. ** database connection is opened. ^(By default, URI handling is globally
  1620. ** disabled. The default value may be changed by compiling with the
  1621. ** [SQLITE_USE_URI] symbol defined.)^
  1622. **
  1623. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1624. ** <dd>^This option takes a single integer argument which is interpreted as
  1625. ** a boolean in order to enable or disable the use of covering indices for
  1626. ** full table scans in the query optimizer. ^The default setting is determined
  1627. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1628. ** if that compile-time option is omitted.
  1629. ** The ability to disable the use of covering indices for full table scans
  1630. ** is because some incorrectly coded legacy applications might malfunction
  1631. ** when the optimization is enabled. Providing the ability to
  1632. ** disable the optimization allows the older, buggy application code to work
  1633. ** without change even with newer versions of SQLite.
  1634. **
  1635. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1636. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1637. ** <dd> These options are obsolete and should not be used by new code.
  1638. ** They are retained for backwards compatibility but are now no-ops.
  1639. ** </dd>
  1640. **
  1641. ** [[SQLITE_CONFIG_SQLLOG]]
  1642. ** <dt>SQLITE_CONFIG_SQLLOG
  1643. ** <dd>This option is only available if sqlite is compiled with the
  1644. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1645. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1646. ** The second should be of type (void*). The callback is invoked by the library
  1647. ** in three separate circumstances, identified by the value passed as the
  1648. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1649. ** passed as the second argument has just been opened. The third argument
  1650. ** points to a buffer containing the name of the main database file. If the
  1651. ** fourth parameter is 1, then the SQL statement that the third parameter
  1652. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1653. ** the connection being passed as the second parameter is being closed. The
  1654. ** third parameter is passed NULL In this case. An example of using this
  1655. ** configuration option can be seen in the "test_sqllog.c" source file in
  1656. ** the canonical SQLite source tree.</dd>
  1657. **
  1658. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1659. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1660. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1661. ** that are the default mmap size limit (the default setting for
  1662. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1663. ** ^The default setting can be overridden by each database connection using
  1664. ** either the [PRAGMA mmap_size] command, or by using the
  1665. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1666. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1667. ** exceed the compile-time maximum mmap size set by the
  1668. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1669. ** ^If either argument to this option is negative, then that argument is
  1670. ** changed to its compile-time default.
  1671. ** </dl>
  1672. */
  1673. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1674. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1675. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1676. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1677. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1678. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1679. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1680. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1681. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1682. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1683. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1684. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1685. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1686. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1687. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1688. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1689. #define SQLITE_CONFIG_URI 17 /* int */
  1690. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1691. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1692. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1693. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1694. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1695. /*
  1696. ** CAPI3REF: Database Connection Configuration Options
  1697. **
  1698. ** These constants are the available integer configuration options that
  1699. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1700. **
  1701. ** New configuration options may be added in future releases of SQLite.
  1702. ** Existing configuration options might be discontinued. Applications
  1703. ** should check the return code from [sqlite3_db_config()] to make sure that
  1704. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1705. ** non-zero [error code] if a discontinued or unsupported configuration option
  1706. ** is invoked.
  1707. **
  1708. ** <dl>
  1709. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1710. ** <dd> ^This option takes three additional arguments that determine the
  1711. ** [lookaside memory allocator] configuration for the [database connection].
  1712. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1713. ** pointer to a memory buffer to use for lookaside memory.
  1714. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1715. ** may be NULL in which case SQLite will allocate the
  1716. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1717. ** size of each lookaside buffer slot. ^The third argument is the number of
  1718. ** slots. The size of the buffer in the first argument must be greater than
  1719. ** or equal to the product of the second and third arguments. The buffer
  1720. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1721. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1722. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1723. ** configuration for a database connection can only be changed when that
  1724. ** connection is not currently using lookaside memory, or in other words
  1725. ** when the "current value" returned by
  1726. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1727. ** Any attempt to change the lookaside memory configuration when lookaside
  1728. ** memory is in use leaves the configuration unchanged and returns
  1729. ** [SQLITE_BUSY].)^</dd>
  1730. **
  1731. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1732. ** <dd> ^This option is used to enable or disable the enforcement of
  1733. ** [foreign key constraints]. There should be two additional arguments.
  1734. ** The first argument is an integer which is 0 to disable FK enforcement,
  1735. ** positive to enable FK enforcement or negative to leave FK enforcement
  1736. ** unchanged. The second parameter is a pointer to an integer into which
  1737. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1738. ** following this call. The second parameter may be a NULL pointer, in
  1739. ** which case the FK enforcement setting is not reported back. </dd>
  1740. **
  1741. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1742. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1743. ** There should be two additional arguments.
  1744. ** The first argument is an integer which is 0 to disable triggers,
  1745. ** positive to enable triggers or negative to leave the setting unchanged.
  1746. ** The second parameter is a pointer to an integer into which
  1747. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1748. ** following this call. The second parameter may be a NULL pointer, in
  1749. ** which case the trigger setting is not reported back. </dd>
  1750. **
  1751. ** </dl>
  1752. */
  1753. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1754. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1755. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1756. /*
  1757. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1758. **
  1759. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1760. ** [extended result codes] feature of SQLite. ^The extended result
  1761. ** codes are disabled by default for historical compatibility.
  1762. */
  1763. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1764. /*
  1765. ** CAPI3REF: Last Insert Rowid
  1766. **
  1767. ** ^Each entry in an SQLite table has a unique 64-bit signed
  1768. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1769. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1770. ** names are not also used by explicitly declared columns. ^If
  1771. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1772. ** is another alias for the rowid.
  1773. **
  1774. ** ^This routine returns the [rowid] of the most recent
  1775. ** successful [INSERT] into the database from the [database connection]
  1776. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  1777. ** records the last insert rowid of both ordinary tables and [virtual tables].
  1778. ** ^If no successful [INSERT]s
  1779. ** have ever occurred on that database connection, zero is returned.
  1780. **
  1781. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1782. ** method, then this routine will return the [rowid] of the inserted
  1783. ** row as long as the trigger or virtual table method is running.
  1784. ** But once the trigger or virtual table method ends, the value returned
  1785. ** by this routine reverts to what it was before the trigger or virtual
  1786. ** table method began.)^
  1787. **
  1788. ** ^An [INSERT] that fails due to a constraint violation is not a
  1789. ** successful [INSERT] and does not change the value returned by this
  1790. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1791. ** and INSERT OR ABORT make no changes to the return value of this
  1792. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1793. ** encounters a constraint violation, it does not fail. The
  1794. ** INSERT continues to completion after deleting rows that caused
  1795. ** the constraint problem so INSERT OR REPLACE will always change
  1796. ** the return value of this interface.)^
  1797. **
  1798. ** ^For the purposes of this routine, an [INSERT] is considered to
  1799. ** be successful even if it is subsequently rolled back.
  1800. **
  1801. ** This function is accessible to SQL statements via the
  1802. ** [last_insert_rowid() SQL function].
  1803. **
  1804. ** If a separate thread performs a new [INSERT] on the same
  1805. ** database connection while the [sqlite3_last_insert_rowid()]
  1806. ** function is running and thus changes the last insert [rowid],
  1807. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1808. ** unpredictable and might not equal either the old or the new
  1809. ** last insert [rowid].
  1810. */
  1811. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1812. /*
  1813. ** CAPI3REF: Count The Number Of Rows Modified
  1814. **
  1815. ** ^This function returns the number of database rows that were changed
  1816. ** or inserted or deleted by the most recently completed SQL statement
  1817. ** on the [database connection] specified by the first parameter.
  1818. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1819. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1820. ** triggers or [foreign key actions] are not counted.)^ Use the
  1821. ** [sqlite3_total_changes()] function to find the total number of changes
  1822. ** including changes caused by triggers and foreign key actions.
  1823. **
  1824. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1825. ** are not counted. Only real table changes are counted.
  1826. **
  1827. ** ^(A "row change" is a change to a single row of a single table
  1828. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1829. ** are changed as side effects of [REPLACE] constraint resolution,
  1830. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1831. ** mechanisms do not count as direct row changes.)^
  1832. **
  1833. ** A "trigger context" is a scope of execution that begins and
  1834. ** ends with the script of a [CREATE TRIGGER | trigger].
  1835. ** Most SQL statements are
  1836. ** evaluated outside of any trigger. This is the "top level"
  1837. ** trigger context. If a trigger fires from the top level, a
  1838. ** new trigger context is entered for the duration of that one
  1839. ** trigger. Subtriggers create subcontexts for their duration.
  1840. **
  1841. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1842. ** not create a new trigger context.
  1843. **
  1844. ** ^This function returns the number of direct row changes in the
  1845. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1846. ** trigger context.
  1847. **
  1848. ** ^Thus, when called from the top level, this function returns the
  1849. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1850. ** that also occurred at the top level. ^(Within the body of a trigger,
  1851. ** the sqlite3_changes() interface can be called to find the number of
  1852. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1853. ** statement within the body of the same trigger.
  1854. ** However, the number returned does not include changes
  1855. ** caused by subtriggers since those have their own context.)^
  1856. **
  1857. ** See also the [sqlite3_total_changes()] interface, the
  1858. ** [count_changes pragma], and the [changes() SQL function].
  1859. **
  1860. ** If a separate thread makes changes on the same database connection
  1861. ** while [sqlite3_changes()] is running then the value returned
  1862. ** is unpredictable and not meaningful.
  1863. */
  1864. SQLITE_API int sqlite3_changes(sqlite3*);
  1865. /*
  1866. ** CAPI3REF: Total Number Of Rows Modified
  1867. **
  1868. ** ^This function returns the number of row changes caused by [INSERT],
  1869. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  1870. ** ^(The count returned by sqlite3_total_changes() includes all changes
  1871. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  1872. ** [foreign key actions]. However,
  1873. ** the count does not include changes used to implement [REPLACE] constraints,
  1874. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  1875. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  1876. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  1877. ** are counted.)^
  1878. ** ^The sqlite3_total_changes() function counts the changes as soon as
  1879. ** the statement that makes them is completed (when the statement handle
  1880. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  1881. **
  1882. ** See also the [sqlite3_changes()] interface, the
  1883. ** [count_changes pragma], and the [total_changes() SQL function].
  1884. **
  1885. ** If a separate thread makes changes on the same database connection
  1886. ** while [sqlite3_total_changes()] is running then the value
  1887. ** returned is unpredictable and not meaningful.
  1888. */
  1889. SQLITE_API int sqlite3_total_changes(sqlite3*);
  1890. /*
  1891. ** CAPI3REF: Interrupt A Long-Running Query
  1892. **
  1893. ** ^This function causes any pending database operation to abort and
  1894. ** return at its earliest opportunity. This routine is typically
  1895. ** called in response to a user action such as pressing "Cancel"
  1896. ** or Ctrl-C where the user wants a long query operation to halt
  1897. ** immediately.
  1898. **
  1899. ** ^It is safe to call this routine from a thread different from the
  1900. ** thread that is currently running the database operation. But it
  1901. ** is not safe to call this routine with a [database connection] that
  1902. ** is closed or might close before sqlite3_interrupt() returns.
  1903. **
  1904. ** ^If an SQL operation is very nearly finished at the time when
  1905. ** sqlite3_interrupt() is called, then it might not have an opportunity
  1906. ** to be interrupted and might continue to completion.
  1907. **
  1908. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1909. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1910. ** that is inside an explicit transaction, then the entire transaction
  1911. ** will be rolled back automatically.
  1912. **
  1913. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  1914. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  1915. ** that are started after the sqlite3_interrupt() call and before the
  1916. ** running statements reaches zero are interrupted as if they had been
  1917. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  1918. ** that are started after the running statement count reaches zero are
  1919. ** not effected by the sqlite3_interrupt().
  1920. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  1921. ** SQL statements is a no-op and has no effect on SQL statements
  1922. ** that are started after the sqlite3_interrupt() call returns.
  1923. **
  1924. ** If the database connection closes while [sqlite3_interrupt()]
  1925. ** is running then bad things will likely happen.
  1926. */
  1927. SQLITE_API void sqlite3_interrupt(sqlite3*);
  1928. /*
  1929. ** CAPI3REF: Determine If An SQL Statement Is Complete
  1930. **
  1931. ** These routines are useful during command-line input to determine if the
  1932. ** currently entered text seems to form a complete SQL statement or
  1933. ** if additional input is needed before sending the text into
  1934. ** SQLite for parsing. ^These routines return 1 if the input string
  1935. ** appears to be a complete SQL statement. ^A statement is judged to be
  1936. ** complete if it ends with a semicolon token and is not a prefix of a
  1937. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  1938. ** string literals or quoted identifier names or comments are not
  1939. ** independent tokens (they are part of the token in which they are
  1940. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  1941. ** and comments that follow the final semicolon are ignored.
  1942. **
  1943. ** ^These routines return 0 if the statement is incomplete. ^If a
  1944. ** memory allocation fails, then SQLITE_NOMEM is returned.
  1945. **
  1946. ** ^These routines do not parse the SQL statements thus
  1947. ** will not detect syntactically incorrect SQL.
  1948. **
  1949. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  1950. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  1951. ** automatically by sqlite3_complete16(). If that initialization fails,
  1952. ** then the return value from sqlite3_complete16() will be non-zero
  1953. ** regardless of whether or not the input SQL is complete.)^
  1954. **
  1955. ** The input to [sqlite3_complete()] must be a zero-terminated
  1956. ** UTF-8 string.
  1957. **
  1958. ** The input to [sqlite3_complete16()] must be a zero-terminated
  1959. ** UTF-16 string in native byte order.
  1960. */
  1961. SQLITE_API int sqlite3_complete(const char *sql);
  1962. SQLITE_API int sqlite3_complete16(const void *sql);
  1963. /*
  1964. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  1965. **
  1966. ** ^This routine sets a callback function that might be invoked whenever
  1967. ** an attempt is made to open a database table that another thread
  1968. ** or process has locked.
  1969. **
  1970. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  1971. ** is returned immediately upon encountering the lock. ^If the busy callback
  1972. ** is not NULL, then the callback might be invoked with two arguments.
  1973. **
  1974. ** ^The first argument to the busy handler is a copy of the void* pointer which
  1975. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  1976. ** the busy handler callback is the number of times that the busy handler has
  1977. ** been invoked for this locking event. ^If the
  1978. ** busy callback returns 0, then no additional attempts are made to
  1979. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  1980. ** ^If the callback returns non-zero, then another attempt
  1981. ** is made to open the database for reading and the cycle repeats.
  1982. **
  1983. ** The presence of a busy handler does not guarantee that it will be invoked
  1984. ** when there is lock contention. ^If SQLite determines that invoking the busy
  1985. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  1986. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  1987. ** Consider a scenario where one process is holding a read lock that
  1988. ** it is trying to promote to a reserved lock and
  1989. ** a second process is holding a reserved lock that it is trying
  1990. ** to promote to an exclusive lock. The first process cannot proceed
  1991. ** because it is blocked by the second and the second process cannot
  1992. ** proceed because it is blocked by the first. If both processes
  1993. ** invoke the busy handlers, neither will make any progress. Therefore,
  1994. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  1995. ** will induce the first process to release its read lock and allow
  1996. ** the second process to proceed.
  1997. **
  1998. ** ^The default busy callback is NULL.
  1999. **
  2000. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2001. ** when SQLite is in the middle of a large transaction where all the
  2002. ** changes will not fit into the in-memory cache. SQLite will
  2003. ** already hold a RESERVED lock on the database file, but it needs
  2004. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2005. ** pages into the database file without harm to concurrent
  2006. ** readers. ^If it is unable to promote the lock, then the in-memory
  2007. ** cache will be left in an inconsistent state and so the error
  2008. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2009. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2010. ** forces an automatic rollback of the changes. See the
  2011. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2012. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2013. ** this is important.
  2014. **
  2015. ** ^(There can only be a single busy handler defined for each
  2016. ** [database connection]. Setting a new busy handler clears any
  2017. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2018. ** will also set or clear the busy handler.
  2019. **
  2020. ** The busy callback should not take any actions which modify the
  2021. ** database connection that invoked the busy handler. Any such actions
  2022. ** result in undefined behavior.
  2023. **
  2024. ** A busy handler must not close the database connection
  2025. ** or [prepared statement] that invoked the busy handler.
  2026. */
  2027. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2028. /*
  2029. ** CAPI3REF: Set A Busy Timeout
  2030. **
  2031. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2032. ** for a specified amount of time when a table is locked. ^The handler
  2033. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2034. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2035. ** the handler returns 0 which causes [sqlite3_step()] to return
  2036. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2037. **
  2038. ** ^Calling this routine with an argument less than or equal to zero
  2039. ** turns off all busy handlers.
  2040. **
  2041. ** ^(There can only be a single busy handler for a particular
  2042. ** [database connection] any any given moment. If another busy handler
  2043. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2044. ** this routine, that other busy handler is cleared.)^
  2045. */
  2046. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2047. /*
  2048. ** CAPI3REF: Convenience Routines For Running Queries
  2049. **
  2050. ** This is a legacy interface that is preserved for backwards compatibility.
  2051. ** Use of this interface is not recommended.
  2052. **
  2053. ** Definition: A <b>result table</b> is memory data structure created by the
  2054. ** [sqlite3_get_table()] interface. A result table records the
  2055. ** complete query results from one or more queries.
  2056. **
  2057. ** The table conceptually has a number of rows and columns. But
  2058. ** these numbers are not part of the result table itself. These
  2059. ** numbers are obtained separately. Let N be the number of rows
  2060. ** and M be the number of columns.
  2061. **
  2062. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2063. ** There are (N+1)*M elements in the array. The first M pointers point
  2064. ** to zero-terminated strings that contain the names of the columns.
  2065. ** The remaining entries all point to query results. NULL values result
  2066. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2067. ** string representation as returned by [sqlite3_column_text()].
  2068. **
  2069. ** A result table might consist of one or more memory allocations.
  2070. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2071. ** A result table should be deallocated using [sqlite3_free_table()].
  2072. **
  2073. ** ^(As an example of the result table format, suppose a query result
  2074. ** is as follows:
  2075. **
  2076. ** <blockquote><pre>
  2077. ** Name | Age
  2078. ** -----------------------
  2079. ** Alice | 43
  2080. ** Bob | 28
  2081. ** Cindy | 21
  2082. ** </pre></blockquote>
  2083. **
  2084. ** There are two column (M==2) and three rows (N==3). Thus the
  2085. ** result table has 8 entries. Suppose the result table is stored
  2086. ** in an array names azResult. Then azResult holds this content:
  2087. **
  2088. ** <blockquote><pre>
  2089. ** azResult&#91;0] = "Name";
  2090. ** azResult&#91;1] = "Age";
  2091. ** azResult&#91;2] = "Alice";
  2092. ** azResult&#91;3] = "43";
  2093. ** azResult&#91;4] = "Bob";
  2094. ** azResult&#91;5] = "28";
  2095. ** azResult&#91;6] = "Cindy";
  2096. ** azResult&#91;7] = "21";
  2097. ** </pre></blockquote>)^
  2098. **
  2099. ** ^The sqlite3_get_table() function evaluates one or more
  2100. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2101. ** string of its 2nd parameter and returns a result table to the
  2102. ** pointer given in its 3rd parameter.
  2103. **
  2104. ** After the application has finished with the result from sqlite3_get_table(),
  2105. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2106. ** release the memory that was malloced. Because of the way the
  2107. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2108. ** function must not try to call [sqlite3_free()] directly. Only
  2109. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2110. **
  2111. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2112. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2113. ** to any internal data structures of SQLite. It uses only the public
  2114. ** interface defined here. As a consequence, errors that occur in the
  2115. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2116. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2117. ** [sqlite3_errmsg()].
  2118. */
  2119. SQLITE_API int sqlite3_get_table(
  2120. sqlite3 *db, /* An open database */
  2121. const char *zSql, /* SQL to be evaluated */
  2122. char ***pazResult, /* Results of the query */
  2123. int *pnRow, /* Number of result rows written here */
  2124. int *pnColumn, /* Number of result columns written here */
  2125. char **pzErrmsg /* Error msg written here */
  2126. );
  2127. SQLITE_API void sqlite3_free_table(char **result);
  2128. /*
  2129. ** CAPI3REF: Formatted String Printing Functions
  2130. **
  2131. ** These routines are work-alikes of the "printf()" family of functions
  2132. ** from the standard C library.
  2133. **
  2134. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2135. ** results into memory obtained from [sqlite3_malloc()].
  2136. ** The strings returned by these two routines should be
  2137. ** released by [sqlite3_free()]. ^Both routines return a
  2138. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2139. ** memory to hold the resulting string.
  2140. **
  2141. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2142. ** the standard C library. The result is written into the
  2143. ** buffer supplied as the second parameter whose size is given by
  2144. ** the first parameter. Note that the order of the
  2145. ** first two parameters is reversed from snprintf().)^ This is an
  2146. ** historical accident that cannot be fixed without breaking
  2147. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2148. ** returns a pointer to its buffer instead of the number of
  2149. ** characters actually written into the buffer.)^ We admit that
  2150. ** the number of characters written would be a more useful return
  2151. ** value but we cannot change the implementation of sqlite3_snprintf()
  2152. ** now without breaking compatibility.
  2153. **
  2154. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2155. ** guarantees that the buffer is always zero-terminated. ^The first
  2156. ** parameter "n" is the total size of the buffer, including space for
  2157. ** the zero terminator. So the longest string that can be completely
  2158. ** written will be n-1 characters.
  2159. **
  2160. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2161. **
  2162. ** These routines all implement some additional formatting
  2163. ** options that are useful for constructing SQL statements.
  2164. ** All of the usual printf() formatting options apply. In addition, there
  2165. ** is are "%q", "%Q", and "%z" options.
  2166. **
  2167. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2168. ** string from the argument list. But %q also doubles every '\'' character.
  2169. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2170. ** character it escapes that character and allows it to be inserted into
  2171. ** the string.
  2172. **
  2173. ** For example, assume the string variable zText contains text as follows:
  2174. **
  2175. ** <blockquote><pre>
  2176. ** char *zText = "It's a happy day!";
  2177. ** </pre></blockquote>
  2178. **
  2179. ** One can use this text in an SQL statement as follows:
  2180. **
  2181. ** <blockquote><pre>
  2182. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2183. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2184. ** sqlite3_free(zSQL);
  2185. ** </pre></blockquote>
  2186. **
  2187. ** Because the %q format string is used, the '\'' character in zText
  2188. ** is escaped and the SQL generated is as follows:
  2189. **
  2190. ** <blockquote><pre>
  2191. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2192. ** </pre></blockquote>
  2193. **
  2194. ** This is correct. Had we used %s instead of %q, the generated SQL
  2195. ** would have looked like this:
  2196. **
  2197. ** <blockquote><pre>
  2198. ** INSERT INTO table1 VALUES('It's a happy day!');
  2199. ** </pre></blockquote>
  2200. **
  2201. ** This second example is an SQL syntax error. As a general rule you should
  2202. ** always use %q instead of %s when inserting text into a string literal.
  2203. **
  2204. ** ^(The %Q option works like %q except it also adds single quotes around
  2205. ** the outside of the total string. Additionally, if the parameter in the
  2206. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2207. ** single quotes).)^ So, for example, one could say:
  2208. **
  2209. ** <blockquote><pre>
  2210. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2211. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2212. ** sqlite3_free(zSQL);
  2213. ** </pre></blockquote>
  2214. **
  2215. ** The code above will render a correct SQL statement in the zSQL
  2216. ** variable even if the zText variable is a NULL pointer.
  2217. **
  2218. ** ^(The "%z" formatting option works like "%s" but with the
  2219. ** addition that after the string has been read and copied into
  2220. ** the result, [sqlite3_free()] is called on the input string.)^
  2221. */
  2222. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2223. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2224. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2225. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2226. /*
  2227. ** CAPI3REF: Memory Allocation Subsystem
  2228. **
  2229. ** The SQLite core uses these three routines for all of its own
  2230. ** internal memory allocation needs. "Core" in the previous sentence
  2231. ** does not include operating-system specific VFS implementation. The
  2232. ** Windows VFS uses native malloc() and free() for some operations.
  2233. **
  2234. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2235. ** of memory at least N bytes in length, where N is the parameter.
  2236. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2237. ** memory, it returns a NULL pointer. ^If the parameter N to
  2238. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2239. ** a NULL pointer.
  2240. **
  2241. ** ^Calling sqlite3_free() with a pointer previously returned
  2242. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2243. ** that it might be reused. ^The sqlite3_free() routine is
  2244. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2245. ** to sqlite3_free() is harmless. After being freed, memory
  2246. ** should neither be read nor written. Even reading previously freed
  2247. ** memory might result in a segmentation fault or other severe error.
  2248. ** Memory corruption, a segmentation fault, or other severe error
  2249. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2250. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2251. **
  2252. ** ^(The sqlite3_realloc() interface attempts to resize a
  2253. ** prior memory allocation to be at least N bytes, where N is the
  2254. ** second parameter. The memory allocation to be resized is the first
  2255. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2256. ** is a NULL pointer then its behavior is identical to calling
  2257. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2258. ** ^If the second parameter to sqlite3_realloc() is zero or
  2259. ** negative then the behavior is exactly the same as calling
  2260. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2261. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2262. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2263. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2264. ** of the prior allocation are copied into the beginning of buffer returned
  2265. ** by sqlite3_realloc() and the prior allocation is freed.
  2266. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2267. ** is not freed.
  2268. **
  2269. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2270. ** is always aligned to at least an 8 byte boundary, or to a
  2271. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2272. ** option is used.
  2273. **
  2274. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2275. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2276. ** implementation of these routines to be omitted. That capability
  2277. ** is no longer provided. Only built-in memory allocators can be used.
  2278. **
  2279. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2280. ** the system malloc() and free() directly when converting
  2281. ** filenames between the UTF-8 encoding used by SQLite
  2282. ** and whatever filename encoding is used by the particular Windows
  2283. ** installation. Memory allocation errors were detected, but
  2284. ** they were reported back as [SQLITE_CANTOPEN] or
  2285. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2286. **
  2287. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2288. ** must be either NULL or else pointers obtained from a prior
  2289. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2290. ** not yet been released.
  2291. **
  2292. ** The application must not read or write any part of
  2293. ** a block of memory after it has been released using
  2294. ** [sqlite3_free()] or [sqlite3_realloc()].
  2295. */
  2296. SQLITE_API void *sqlite3_malloc(int);
  2297. SQLITE_API void *sqlite3_realloc(void*, int);
  2298. SQLITE_API void sqlite3_free(void*);
  2299. /*
  2300. ** CAPI3REF: Memory Allocator Statistics
  2301. **
  2302. ** SQLite provides these two interfaces for reporting on the status
  2303. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2304. ** routines, which form the built-in memory allocation subsystem.
  2305. **
  2306. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2307. ** of memory currently outstanding (malloced but not freed).
  2308. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2309. ** value of [sqlite3_memory_used()] since the high-water mark
  2310. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2311. ** [sqlite3_memory_highwater()] include any overhead
  2312. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2313. ** but not overhead added by the any underlying system library
  2314. ** routines that [sqlite3_malloc()] may call.
  2315. **
  2316. ** ^The memory high-water mark is reset to the current value of
  2317. ** [sqlite3_memory_used()] if and only if the parameter to
  2318. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2319. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2320. ** prior to the reset.
  2321. */
  2322. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2323. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2324. /*
  2325. ** CAPI3REF: Pseudo-Random Number Generator
  2326. **
  2327. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2328. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2329. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2330. ** the build-in random() and randomblob() SQL functions. This interface allows
  2331. ** applications to access the same PRNG for other purposes.
  2332. **
  2333. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2334. **
  2335. ** ^The first time this routine is invoked (either internally or by
  2336. ** the application) the PRNG is seeded using randomness obtained
  2337. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2338. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2339. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2340. ** method.
  2341. */
  2342. SQLITE_API void sqlite3_randomness(int N, void *P);
  2343. /*
  2344. ** CAPI3REF: Compile-Time Authorization Callbacks
  2345. **
  2346. ** ^This routine registers an authorizer callback with a particular
  2347. ** [database connection], supplied in the first argument.
  2348. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2349. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2350. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2351. ** points during the compilation process, as logic is being created
  2352. ** to perform various actions, the authorizer callback is invoked to
  2353. ** see if those actions are allowed. ^The authorizer callback should
  2354. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2355. ** specific action but allow the SQL statement to continue to be
  2356. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2357. ** rejected with an error. ^If the authorizer callback returns
  2358. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2359. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2360. ** the authorizer will fail with an error message.
  2361. **
  2362. ** When the callback returns [SQLITE_OK], that means the operation
  2363. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2364. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2365. ** authorizer will fail with an error message explaining that
  2366. ** access is denied.
  2367. **
  2368. ** ^The first parameter to the authorizer callback is a copy of the third
  2369. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2370. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2371. ** the particular action to be authorized. ^The third through sixth parameters
  2372. ** to the callback are zero-terminated strings that contain additional
  2373. ** details about the action to be authorized.
  2374. **
  2375. ** ^If the action code is [SQLITE_READ]
  2376. ** and the callback returns [SQLITE_IGNORE] then the
  2377. ** [prepared statement] statement is constructed to substitute
  2378. ** a NULL value in place of the table column that would have
  2379. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2380. ** return can be used to deny an untrusted user access to individual
  2381. ** columns of a table.
  2382. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2383. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2384. ** [truncate optimization] is disabled and all rows are deleted individually.
  2385. **
  2386. ** An authorizer is used when [sqlite3_prepare | preparing]
  2387. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2388. ** do not try to access data they are not allowed to see, or that they do not
  2389. ** try to execute malicious statements that damage the database. For
  2390. ** example, an application may allow a user to enter arbitrary
  2391. ** SQL queries for evaluation by a database. But the application does
  2392. ** not want the user to be able to make arbitrary changes to the
  2393. ** database. An authorizer could then be put in place while the
  2394. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2395. ** disallows everything except [SELECT] statements.
  2396. **
  2397. ** Applications that need to process SQL from untrusted sources
  2398. ** might also consider lowering resource limits using [sqlite3_limit()]
  2399. ** and limiting database size using the [max_page_count] [PRAGMA]
  2400. ** in addition to using an authorizer.
  2401. **
  2402. ** ^(Only a single authorizer can be in place on a database connection
  2403. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2404. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2405. ** The authorizer is disabled by default.
  2406. **
  2407. ** The authorizer callback must not do anything that will modify
  2408. ** the database connection that invoked the authorizer callback.
  2409. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2410. ** database connections for the meaning of "modify" in this paragraph.
  2411. **
  2412. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2413. ** statement might be re-prepared during [sqlite3_step()] due to a
  2414. ** schema change. Hence, the application should ensure that the
  2415. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2416. **
  2417. ** ^Note that the authorizer callback is invoked only during
  2418. ** [sqlite3_prepare()] or its variants. Authorization is not
  2419. ** performed during statement evaluation in [sqlite3_step()], unless
  2420. ** as stated in the previous paragraph, sqlite3_step() invokes
  2421. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2422. */
  2423. SQLITE_API int sqlite3_set_authorizer(
  2424. sqlite3*,
  2425. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2426. void *pUserData
  2427. );
  2428. /*
  2429. ** CAPI3REF: Authorizer Return Codes
  2430. **
  2431. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2432. ** return either [SQLITE_OK] or one of these two constants in order
  2433. ** to signal SQLite whether or not the action is permitted. See the
  2434. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2435. ** information.
  2436. **
  2437. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2438. ** from the [sqlite3_vtab_on_conflict()] interface.
  2439. */
  2440. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2441. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2442. /*
  2443. ** CAPI3REF: Authorizer Action Codes
  2444. **
  2445. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2446. ** that is invoked to authorize certain SQL statement actions. The
  2447. ** second parameter to the callback is an integer code that specifies
  2448. ** what action is being authorized. These are the integer action codes that
  2449. ** the authorizer callback may be passed.
  2450. **
  2451. ** These action code values signify what kind of operation is to be
  2452. ** authorized. The 3rd and 4th parameters to the authorization
  2453. ** callback function will be parameters or NULL depending on which of these
  2454. ** codes is used as the second parameter. ^(The 5th parameter to the
  2455. ** authorizer callback is the name of the database ("main", "temp",
  2456. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2457. ** is the name of the inner-most trigger or view that is responsible for
  2458. ** the access attempt or NULL if this access attempt is directly from
  2459. ** top-level SQL code.
  2460. */
  2461. /******************************************* 3rd ************ 4th ***********/
  2462. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2463. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2464. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2465. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2466. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2467. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2468. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2469. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2470. #define SQLITE_DELETE 9 /* Table Name NULL */
  2471. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2472. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2473. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2474. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2475. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2476. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2477. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2478. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2479. #define SQLITE_INSERT 18 /* Table Name NULL */
  2480. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2481. #define SQLITE_READ 20 /* Table Name Column Name */
  2482. #define SQLITE_SELECT 21 /* NULL NULL */
  2483. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2484. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2485. #define SQLITE_ATTACH 24 /* Filename NULL */
  2486. #define SQLITE_DETACH 25 /* Database Name NULL */
  2487. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2488. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2489. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2490. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2491. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2492. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2493. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2494. #define SQLITE_COPY 0 /* No longer used */
  2495. /*
  2496. ** CAPI3REF: Tracing And Profiling Functions
  2497. **
  2498. ** These routines register callback functions that can be used for
  2499. ** tracing and profiling the execution of SQL statements.
  2500. **
  2501. ** ^The callback function registered by sqlite3_trace() is invoked at
  2502. ** various times when an SQL statement is being run by [sqlite3_step()].
  2503. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2504. ** SQL statement text as the statement first begins executing.
  2505. ** ^(Additional sqlite3_trace() callbacks might occur
  2506. ** as each triggered subprogram is entered. The callbacks for triggers
  2507. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2508. **
  2509. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2510. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2511. **
  2512. ** ^The callback function registered by sqlite3_profile() is invoked
  2513. ** as each SQL statement finishes. ^The profile callback contains
  2514. ** the original statement text and an estimate of wall-clock time
  2515. ** of how long that statement took to run. ^The profile callback
  2516. ** time is in units of nanoseconds, however the current implementation
  2517. ** is only capable of millisecond resolution so the six least significant
  2518. ** digits in the time are meaningless. Future versions of SQLite
  2519. ** might provide greater resolution on the profiler callback. The
  2520. ** sqlite3_profile() function is considered experimental and is
  2521. ** subject to change in future versions of SQLite.
  2522. */
  2523. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2524. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2525. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2526. /*
  2527. ** CAPI3REF: Query Progress Callbacks
  2528. **
  2529. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2530. ** function X to be invoked periodically during long running calls to
  2531. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2532. ** database connection D. An example use for this
  2533. ** interface is to keep a GUI updated during a large query.
  2534. **
  2535. ** ^The parameter P is passed through as the only parameter to the
  2536. ** callback function X. ^The parameter N is the approximate number of
  2537. ** [virtual machine instructions] that are evaluated between successive
  2538. ** invocations of the callback X. ^If N is less than one then the progress
  2539. ** handler is disabled.
  2540. **
  2541. ** ^Only a single progress handler may be defined at one time per
  2542. ** [database connection]; setting a new progress handler cancels the
  2543. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2544. ** ^The progress handler is also disabled by setting N to a value less
  2545. ** than 1.
  2546. **
  2547. ** ^If the progress callback returns non-zero, the operation is
  2548. ** interrupted. This feature can be used to implement a
  2549. ** "Cancel" button on a GUI progress dialog box.
  2550. **
  2551. ** The progress handler callback must not do anything that will modify
  2552. ** the database connection that invoked the progress handler.
  2553. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2554. ** database connections for the meaning of "modify" in this paragraph.
  2555. **
  2556. */
  2557. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2558. /*
  2559. ** CAPI3REF: Opening A New Database Connection
  2560. **
  2561. ** ^These routines open an SQLite database file as specified by the
  2562. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2563. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2564. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2565. ** returned in *ppDb, even if an error occurs. The only exception is that
  2566. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2567. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2568. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2569. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2570. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2571. ** an English language description of the error following a failure of any
  2572. ** of the sqlite3_open() routines.
  2573. **
  2574. ** ^The default encoding for the database will be UTF-8 if
  2575. ** sqlite3_open() or sqlite3_open_v2() is called and
  2576. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2577. **
  2578. ** Whether or not an error occurs when it is opened, resources
  2579. ** associated with the [database connection] handle should be released by
  2580. ** passing it to [sqlite3_close()] when it is no longer required.
  2581. **
  2582. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2583. ** except that it accepts two additional parameters for additional control
  2584. ** over the new database connection. ^(The flags parameter to
  2585. ** sqlite3_open_v2() can take one of
  2586. ** the following three values, optionally combined with the
  2587. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2588. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2589. **
  2590. ** <dl>
  2591. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2592. ** <dd>The database is opened in read-only mode. If the database does not
  2593. ** already exist, an error is returned.</dd>)^
  2594. **
  2595. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2596. ** <dd>The database is opened for reading and writing if possible, or reading
  2597. ** only if the file is write protected by the operating system. In either
  2598. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2599. **
  2600. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2601. ** <dd>The database is opened for reading and writing, and is created if
  2602. ** it does not already exist. This is the behavior that is always used for
  2603. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2604. ** </dl>
  2605. **
  2606. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2607. ** combinations shown above optionally combined with other
  2608. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2609. ** then the behavior is undefined.
  2610. **
  2611. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2612. ** opens in the multi-thread [threading mode] as long as the single-thread
  2613. ** mode has not been set at compile-time or start-time. ^If the
  2614. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2615. ** in the serialized [threading mode] unless single-thread was
  2616. ** previously selected at compile-time or start-time.
  2617. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2618. ** eligible to use [shared cache mode], regardless of whether or not shared
  2619. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2620. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2621. ** participate in [shared cache mode] even if it is enabled.
  2622. **
  2623. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2624. ** [sqlite3_vfs] object that defines the operating system interface that
  2625. ** the new database connection should use. ^If the fourth parameter is
  2626. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2627. **
  2628. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2629. ** is created for the connection. ^This in-memory database will vanish when
  2630. ** the database connection is closed. Future versions of SQLite might
  2631. ** make use of additional special filenames that begin with the ":" character.
  2632. ** It is recommended that when a database filename actually does begin with
  2633. ** a ":" character you should prefix the filename with a pathname such as
  2634. ** "./" to avoid ambiguity.
  2635. **
  2636. ** ^If the filename is an empty string, then a private, temporary
  2637. ** on-disk database will be created. ^This private database will be
  2638. ** automatically deleted as soon as the database connection is closed.
  2639. **
  2640. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2641. **
  2642. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2643. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2644. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2645. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2646. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2647. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2648. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2649. ** by default, but future releases of SQLite might enable URI filename
  2650. ** interpretation by default. See "[URI filenames]" for additional
  2651. ** information.
  2652. **
  2653. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2654. ** authority, then it must be either an empty string or the string
  2655. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2656. ** error is returned to the caller. ^The fragment component of a URI, if
  2657. ** present, is ignored.
  2658. **
  2659. ** ^SQLite uses the path component of the URI as the name of the disk file
  2660. ** which contains the database. ^If the path begins with a '/' character,
  2661. ** then it is interpreted as an absolute path. ^If the path does not begin
  2662. ** with a '/' (meaning that the authority section is omitted from the URI)
  2663. ** then the path is interpreted as a relative path.
  2664. ** ^On windows, the first component of an absolute path
  2665. ** is a drive specification (e.g. "C:").
  2666. **
  2667. ** [[core URI query parameters]]
  2668. ** The query component of a URI may contain parameters that are interpreted
  2669. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2670. ** SQLite interprets the following three query parameters:
  2671. **
  2672. ** <ul>
  2673. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2674. ** a VFS object that provides the operating system interface that should
  2675. ** be used to access the database file on disk. ^If this option is set to
  2676. ** an empty string the default VFS object is used. ^Specifying an unknown
  2677. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2678. ** present, then the VFS specified by the option takes precedence over
  2679. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2680. **
  2681. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2682. ** "rwc", or "memory". Attempting to set it to any other value is
  2683. ** an error)^.
  2684. ** ^If "ro" is specified, then the database is opened for read-only
  2685. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2686. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2687. ** "rw", then the database is opened for read-write (but not create)
  2688. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2689. ** been set. ^Value "rwc" is equivalent to setting both
  2690. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2691. ** set to "memory" then a pure [in-memory database] that never reads
  2692. ** or writes from disk is used. ^It is an error to specify a value for
  2693. ** the mode parameter that is less restrictive than that specified by
  2694. ** the flags passed in the third parameter to sqlite3_open_v2().
  2695. **
  2696. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2697. ** "private". ^Setting it to "shared" is equivalent to setting the
  2698. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2699. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2700. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2701. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2702. ** a URI filename, its value overrides any behavior requested by setting
  2703. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2704. ** </ul>
  2705. **
  2706. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2707. ** error. Future versions of SQLite might understand additional query
  2708. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2709. ** additional information.
  2710. **
  2711. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2712. **
  2713. ** <table border="1" align=center cellpadding=5>
  2714. ** <tr><th> URI filenames <th> Results
  2715. ** <tr><td> file:data.db <td>
  2716. ** Open the file "data.db" in the current directory.
  2717. ** <tr><td> file:/home/fred/data.db<br>
  2718. ** file:///home/fred/data.db <br>
  2719. ** file://localhost/home/fred/data.db <br> <td>
  2720. ** Open the database file "/home/fred/data.db".
  2721. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2722. ** An error. "darkstar" is not a recognized authority.
  2723. ** <tr><td style="white-space:nowrap">
  2724. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2725. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2726. ** C:. Note that the %20 escaping in this example is not strictly
  2727. ** necessary - space characters can be used literally
  2728. ** in URI filenames.
  2729. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2730. ** Open file "data.db" in the current directory for read-only access.
  2731. ** Regardless of whether or not shared-cache mode is enabled by
  2732. ** default, use a private cache.
  2733. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  2734. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  2735. ** <tr><td> file:data.db?mode=readonly <td>
  2736. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2737. ** </table>
  2738. **
  2739. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2740. ** query components of a URI. A hexadecimal escape sequence consists of a
  2741. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2742. ** specifying an octet value. ^Before the path or query components of a
  2743. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2744. ** hexadecimal escape sequences replaced by a single byte containing the
  2745. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2746. ** the results are undefined.
  2747. **
  2748. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2749. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2750. ** codepage is currently defined. Filenames containing international
  2751. ** characters must be converted to UTF-8 prior to passing them into
  2752. ** sqlite3_open() or sqlite3_open_v2().
  2753. **
  2754. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2755. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2756. ** features that require the use of temporary files may fail.
  2757. **
  2758. ** See also: [sqlite3_temp_directory]
  2759. */
  2760. SQLITE_API int sqlite3_open(
  2761. const char *filename, /* Database filename (UTF-8) */
  2762. sqlite3 **ppDb /* OUT: SQLite db handle */
  2763. );
  2764. SQLITE_API int sqlite3_open16(
  2765. const void *filename, /* Database filename (UTF-16) */
  2766. sqlite3 **ppDb /* OUT: SQLite db handle */
  2767. );
  2768. SQLITE_API int sqlite3_open_v2(
  2769. const char *filename, /* Database filename (UTF-8) */
  2770. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2771. int flags, /* Flags */
  2772. const char *zVfs /* Name of VFS module to use */
  2773. );
  2774. /*
  2775. ** CAPI3REF: Obtain Values For URI Parameters
  2776. **
  2777. ** These are utility routines, useful to VFS implementations, that check
  2778. ** to see if a database file was a URI that contained a specific query
  2779. ** parameter, and if so obtains the value of that query parameter.
  2780. **
  2781. ** If F is the database filename pointer passed into the xOpen() method of
  2782. ** a VFS implementation when the flags parameter to xOpen() has one or
  2783. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2784. ** P is the name of the query parameter, then
  2785. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2786. ** parameter if it exists or a NULL pointer if P does not appear as a
  2787. ** query parameter on F. If P is a query parameter of F
  2788. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2789. ** a pointer to an empty string.
  2790. **
  2791. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2792. ** parameter and returns true (1) or false (0) according to the value
  2793. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2794. ** value of query parameter P is one of "yes", "true", or "on" in any
  2795. ** case or if the value begins with a non-zero number. The
  2796. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2797. ** query parameter P is one of "no", "false", or "off" in any case or
  2798. ** if the value begins with a numeric zero. If P is not a query
  2799. ** parameter on F or if the value of P is does not match any of the
  2800. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2801. **
  2802. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2803. ** 64-bit signed integer and returns that integer, or D if P does not
  2804. ** exist. If the value of P is something other than an integer, then
  2805. ** zero is returned.
  2806. **
  2807. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2808. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2809. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2810. ** VFS method, then the behavior of this routine is undefined and probably
  2811. ** undesirable.
  2812. */
  2813. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2814. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  2815. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2816. /*
  2817. ** CAPI3REF: Error Codes And Messages
  2818. **
  2819. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2820. ** [extended result code] for the most recent failed sqlite3_* API call
  2821. ** associated with a [database connection]. If a prior API call failed
  2822. ** but the most recent API call succeeded, the return value from
  2823. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  2824. ** interface is the same except that it always returns the
  2825. ** [extended result code] even when extended result codes are
  2826. ** disabled.
  2827. **
  2828. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2829. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2830. ** ^(Memory to hold the error message string is managed internally.
  2831. ** The application does not need to worry about freeing the result.
  2832. ** However, the error string might be overwritten or deallocated by
  2833. ** subsequent calls to other SQLite interface functions.)^
  2834. **
  2835. ** ^The sqlite3_errstr() interface returns the English-language text
  2836. ** that describes the [result code], as UTF-8.
  2837. ** ^(Memory to hold the error message string is managed internally
  2838. ** and must not be freed by the application)^.
  2839. **
  2840. ** When the serialized [threading mode] is in use, it might be the
  2841. ** case that a second error occurs on a separate thread in between
  2842. ** the time of the first error and the call to these interfaces.
  2843. ** When that happens, the second error will be reported since these
  2844. ** interfaces always report the most recent result. To avoid
  2845. ** this, each thread can obtain exclusive use of the [database connection] D
  2846. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2847. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2848. ** all calls to the interfaces listed here are completed.
  2849. **
  2850. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2851. ** was invoked incorrectly by the application. In that case, the
  2852. ** error code and message may or may not be set.
  2853. */
  2854. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2855. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2856. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2857. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2858. SQLITE_API const char *sqlite3_errstr(int);
  2859. /*
  2860. ** CAPI3REF: SQL Statement Object
  2861. ** KEYWORDS: {prepared statement} {prepared statements}
  2862. **
  2863. ** An instance of this object represents a single SQL statement.
  2864. ** This object is variously known as a "prepared statement" or a
  2865. ** "compiled SQL statement" or simply as a "statement".
  2866. **
  2867. ** The life of a statement object goes something like this:
  2868. **
  2869. ** <ol>
  2870. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2871. ** function.
  2872. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2873. ** interfaces.
  2874. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2875. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2876. ** to step 2. Do this zero or more times.
  2877. ** <li> Destroy the object using [sqlite3_finalize()].
  2878. ** </ol>
  2879. **
  2880. ** Refer to documentation on individual methods above for additional
  2881. ** information.
  2882. */
  2883. typedef struct sqlite3_stmt sqlite3_stmt;
  2884. /*
  2885. ** CAPI3REF: Run-time Limits
  2886. **
  2887. ** ^(This interface allows the size of various constructs to be limited
  2888. ** on a connection by connection basis. The first parameter is the
  2889. ** [database connection] whose limit is to be set or queried. The
  2890. ** second parameter is one of the [limit categories] that define a
  2891. ** class of constructs to be size limited. The third parameter is the
  2892. ** new limit for that construct.)^
  2893. **
  2894. ** ^If the new limit is a negative number, the limit is unchanged.
  2895. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  2896. ** [limits | hard upper bound]
  2897. ** set at compile-time by a C preprocessor macro called
  2898. ** [limits | SQLITE_MAX_<i>NAME</i>].
  2899. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  2900. ** ^Attempts to increase a limit above its hard upper bound are
  2901. ** silently truncated to the hard upper bound.
  2902. **
  2903. ** ^Regardless of whether or not the limit was changed, the
  2904. ** [sqlite3_limit()] interface returns the prior value of the limit.
  2905. ** ^Hence, to find the current value of a limit without changing it,
  2906. ** simply invoke this interface with the third parameter set to -1.
  2907. **
  2908. ** Run-time limits are intended for use in applications that manage
  2909. ** both their own internal database and also databases that are controlled
  2910. ** by untrusted external sources. An example application might be a
  2911. ** web browser that has its own databases for storing history and
  2912. ** separate databases controlled by JavaScript applications downloaded
  2913. ** off the Internet. The internal databases can be given the
  2914. ** large, default limits. Databases managed by external sources can
  2915. ** be given much smaller limits designed to prevent a denial of service
  2916. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2917. ** interface to further control untrusted SQL. The size of the database
  2918. ** created by an untrusted script can be contained using the
  2919. ** [max_page_count] [PRAGMA].
  2920. **
  2921. ** New run-time limit categories may be added in future releases.
  2922. */
  2923. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2924. /*
  2925. ** CAPI3REF: Run-Time Limit Categories
  2926. ** KEYWORDS: {limit category} {*limit categories}
  2927. **
  2928. ** These constants define various performance limits
  2929. ** that can be lowered at run-time using [sqlite3_limit()].
  2930. ** The synopsis of the meanings of the various limits is shown below.
  2931. ** Additional information is available at [limits | Limits in SQLite].
  2932. **
  2933. ** <dl>
  2934. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  2935. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  2936. **
  2937. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2938. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  2939. **
  2940. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  2941. ** <dd>The maximum number of columns in a table definition or in the
  2942. ** result set of a [SELECT] or the maximum number of columns in an index
  2943. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  2944. **
  2945. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2946. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  2947. **
  2948. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2949. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  2950. **
  2951. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  2952. ** <dd>The maximum number of instructions in a virtual machine program
  2953. ** used to implement an SQL statement. This limit is not currently
  2954. ** enforced, though that might be added in some future release of
  2955. ** SQLite.</dd>)^
  2956. **
  2957. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  2958. ** <dd>The maximum number of arguments on a function.</dd>)^
  2959. **
  2960. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  2961. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  2962. **
  2963. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  2964. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  2965. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  2966. ** [GLOB] operators.</dd>)^
  2967. **
  2968. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  2969. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  2970. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  2971. **
  2972. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  2973. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  2974. ** </dl>
  2975. */
  2976. #define SQLITE_LIMIT_LENGTH 0
  2977. #define SQLITE_LIMIT_SQL_LENGTH 1
  2978. #define SQLITE_LIMIT_COLUMN 2
  2979. #define SQLITE_LIMIT_EXPR_DEPTH 3
  2980. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  2981. #define SQLITE_LIMIT_VDBE_OP 5
  2982. #define SQLITE_LIMIT_FUNCTION_ARG 6
  2983. #define SQLITE_LIMIT_ATTACHED 7
  2984. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  2985. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  2986. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  2987. /*
  2988. ** CAPI3REF: Compiling An SQL Statement
  2989. ** KEYWORDS: {SQL statement compiler}
  2990. **
  2991. ** To execute an SQL query, it must first be compiled into a byte-code
  2992. ** program using one of these routines.
  2993. **
  2994. ** The first argument, "db", is a [database connection] obtained from a
  2995. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  2996. ** [sqlite3_open16()]. The database connection must not have been closed.
  2997. **
  2998. ** The second argument, "zSql", is the statement to be compiled, encoded
  2999. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3000. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3001. ** use UTF-16.
  3002. **
  3003. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3004. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3005. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3006. ** zSql string ends at either the first '\000' or '\u0000' character or
  3007. ** the nByte-th byte, whichever comes first. If the caller knows
  3008. ** that the supplied string is nul-terminated, then there is a small
  3009. ** performance advantage to be gained by passing an nByte parameter that
  3010. ** is equal to the number of bytes in the input string <i>including</i>
  3011. ** the nul-terminator bytes as this saves SQLite from having to
  3012. ** make a copy of the input string.
  3013. **
  3014. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3015. ** past the end of the first SQL statement in zSql. These routines only
  3016. ** compile the first statement in zSql, so *pzTail is left pointing to
  3017. ** what remains uncompiled.
  3018. **
  3019. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3020. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3021. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3022. ** string or a comment) then *ppStmt is set to NULL.
  3023. ** The calling procedure is responsible for deleting the compiled
  3024. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3025. ** ppStmt may not be NULL.
  3026. **
  3027. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3028. ** otherwise an [error code] is returned.
  3029. **
  3030. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3031. ** recommended for all new programs. The two older interfaces are retained
  3032. ** for backwards compatibility, but their use is discouraged.
  3033. ** ^In the "v2" interfaces, the prepared statement
  3034. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3035. ** original SQL text. This causes the [sqlite3_step()] interface to
  3036. ** behave differently in three ways:
  3037. **
  3038. ** <ol>
  3039. ** <li>
  3040. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3041. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3042. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3043. ** retries will occur before sqlite3_step() gives up and returns an error.
  3044. ** </li>
  3045. **
  3046. ** <li>
  3047. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3048. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3049. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3050. ** and the application would have to make a second call to [sqlite3_reset()]
  3051. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3052. ** interfaces, the underlying reason for the error is returned immediately.
  3053. ** </li>
  3054. **
  3055. ** <li>
  3056. ** ^If the specific value bound to [parameter | host parameter] in the
  3057. ** WHERE clause might influence the choice of query plan for a statement,
  3058. ** then the statement will be automatically recompiled, as if there had been
  3059. ** a schema change, on the first [sqlite3_step()] call following any change
  3060. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3061. ** ^The specific value of WHERE-clause [parameter] might influence the
  3062. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3063. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3064. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3065. ** the
  3066. ** </li>
  3067. ** </ol>
  3068. */
  3069. SQLITE_API int sqlite3_prepare(
  3070. sqlite3 *db, /* Database handle */
  3071. const char *zSql, /* SQL statement, UTF-8 encoded */
  3072. int nByte, /* Maximum length of zSql in bytes. */
  3073. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3074. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3075. );
  3076. SQLITE_API int sqlite3_prepare_v2(
  3077. sqlite3 *db, /* Database handle */
  3078. const char *zSql, /* SQL statement, UTF-8 encoded */
  3079. int nByte, /* Maximum length of zSql in bytes. */
  3080. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3081. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3082. );
  3083. SQLITE_API int sqlite3_prepare16(
  3084. sqlite3 *db, /* Database handle */
  3085. const void *zSql, /* SQL statement, UTF-16 encoded */
  3086. int nByte, /* Maximum length of zSql in bytes. */
  3087. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3088. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3089. );
  3090. SQLITE_API int sqlite3_prepare16_v2(
  3091. sqlite3 *db, /* Database handle */
  3092. const void *zSql, /* SQL statement, UTF-16 encoded */
  3093. int nByte, /* Maximum length of zSql in bytes. */
  3094. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3095. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3096. );
  3097. /*
  3098. ** CAPI3REF: Retrieving Statement SQL
  3099. **
  3100. ** ^This interface can be used to retrieve a saved copy of the original
  3101. ** SQL text used to create a [prepared statement] if that statement was
  3102. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3103. */
  3104. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3105. /*
  3106. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3107. **
  3108. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3109. ** and only if the [prepared statement] X makes no direct changes to
  3110. ** the content of the database file.
  3111. **
  3112. ** Note that [application-defined SQL functions] or
  3113. ** [virtual tables] might change the database indirectly as a side effect.
  3114. ** ^(For example, if an application defines a function "eval()" that
  3115. ** calls [sqlite3_exec()], then the following SQL statement would
  3116. ** change the database file through side-effects:
  3117. **
  3118. ** <blockquote><pre>
  3119. ** SELECT eval('DELETE FROM t1') FROM t2;
  3120. ** </pre></blockquote>
  3121. **
  3122. ** But because the [SELECT] statement does not change the database file
  3123. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3124. **
  3125. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3126. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3127. ** since the statements themselves do not actually modify the database but
  3128. ** rather they control the timing of when other statements modify the
  3129. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3130. ** sqlite3_stmt_readonly() to return true since, while those statements
  3131. ** change the configuration of a database connection, they do not make
  3132. ** changes to the content of the database files on disk.
  3133. */
  3134. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3135. /*
  3136. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3137. **
  3138. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3139. ** [prepared statement] S has been stepped at least once using
  3140. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3141. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3142. ** interface returns false if S is a NULL pointer. If S is not a
  3143. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3144. ** object, then the behavior is undefined and probably undesirable.
  3145. **
  3146. ** This interface can be used in combination [sqlite3_next_stmt()]
  3147. ** to locate all prepared statements associated with a database
  3148. ** connection that are in need of being reset. This can be used,
  3149. ** for example, in diagnostic routines to search for prepared
  3150. ** statements that are holding a transaction open.
  3151. */
  3152. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3153. /*
  3154. ** CAPI3REF: Dynamically Typed Value Object
  3155. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3156. **
  3157. ** SQLite uses the sqlite3_value object to represent all values
  3158. ** that can be stored in a database table. SQLite uses dynamic typing
  3159. ** for the values it stores. ^Values stored in sqlite3_value objects
  3160. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3161. **
  3162. ** An sqlite3_value object may be either "protected" or "unprotected".
  3163. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3164. ** will accept either a protected or an unprotected sqlite3_value.
  3165. ** Every interface that accepts sqlite3_value arguments specifies
  3166. ** whether or not it requires a protected sqlite3_value.
  3167. **
  3168. ** The terms "protected" and "unprotected" refer to whether or not
  3169. ** a mutex is held. An internal mutex is held for a protected
  3170. ** sqlite3_value object but no mutex is held for an unprotected
  3171. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3172. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3173. ** or if SQLite is run in one of reduced mutex modes
  3174. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3175. ** then there is no distinction between protected and unprotected
  3176. ** sqlite3_value objects and they can be used interchangeably. However,
  3177. ** for maximum code portability it is recommended that applications
  3178. ** still make the distinction between protected and unprotected
  3179. ** sqlite3_value objects even when not strictly required.
  3180. **
  3181. ** ^The sqlite3_value objects that are passed as parameters into the
  3182. ** implementation of [application-defined SQL functions] are protected.
  3183. ** ^The sqlite3_value object returned by
  3184. ** [sqlite3_column_value()] is unprotected.
  3185. ** Unprotected sqlite3_value objects may only be used with
  3186. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3187. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3188. ** interfaces require protected sqlite3_value objects.
  3189. */
  3190. typedef struct Mem sqlite3_value;
  3191. /*
  3192. ** CAPI3REF: SQL Function Context Object
  3193. **
  3194. ** The context in which an SQL function executes is stored in an
  3195. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3196. ** is always first parameter to [application-defined SQL functions].
  3197. ** The application-defined SQL function implementation will pass this
  3198. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3199. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3200. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3201. ** and/or [sqlite3_set_auxdata()].
  3202. */
  3203. typedef struct sqlite3_context sqlite3_context;
  3204. /*
  3205. ** CAPI3REF: Binding Values To Prepared Statements
  3206. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3207. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3208. **
  3209. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3210. ** literals may be replaced by a [parameter] that matches one of following
  3211. ** templates:
  3212. **
  3213. ** <ul>
  3214. ** <li> ?
  3215. ** <li> ?NNN
  3216. ** <li> :VVV
  3217. ** <li> @VVV
  3218. ** <li> $VVV
  3219. ** </ul>
  3220. **
  3221. ** In the templates above, NNN represents an integer literal,
  3222. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3223. ** parameters (also called "host parameter names" or "SQL parameters")
  3224. ** can be set using the sqlite3_bind_*() routines defined here.
  3225. **
  3226. ** ^The first argument to the sqlite3_bind_*() routines is always
  3227. ** a pointer to the [sqlite3_stmt] object returned from
  3228. ** [sqlite3_prepare_v2()] or its variants.
  3229. **
  3230. ** ^The second argument is the index of the SQL parameter to be set.
  3231. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3232. ** SQL parameter is used more than once, second and subsequent
  3233. ** occurrences have the same index as the first occurrence.
  3234. ** ^The index for named parameters can be looked up using the
  3235. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3236. ** for "?NNN" parameters is the value of NNN.
  3237. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3238. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3239. **
  3240. ** ^The third argument is the value to bind to the parameter.
  3241. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3242. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3243. ** is ignored and the end result is the same as sqlite3_bind_null().
  3244. **
  3245. ** ^(In those routines that have a fourth argument, its value is the
  3246. ** number of bytes in the parameter. To be clear: the value is the
  3247. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3248. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3249. ** is negative, then the length of the string is
  3250. ** the number of bytes up to the first zero terminator.
  3251. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3252. ** the behavior is undefined.
  3253. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3254. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3255. ** where the NUL terminator would occur assuming the string were NUL
  3256. ** terminated. If any NUL characters occur at byte offsets less than
  3257. ** the value of the fourth parameter then the resulting string value will
  3258. ** contain embedded NULs. The result of expressions involving strings
  3259. ** with embedded NULs is undefined.
  3260. **
  3261. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3262. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3263. ** string after SQLite has finished with it. ^The destructor is called
  3264. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3265. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3266. ** ^If the fifth argument is
  3267. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3268. ** information is in static, unmanaged space and does not need to be freed.
  3269. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3270. ** SQLite makes its own private copy of the data immediately, before
  3271. ** the sqlite3_bind_*() routine returns.
  3272. **
  3273. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3274. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3275. ** (just an integer to hold its size) while it is being processed.
  3276. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3277. ** content is later written using
  3278. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3279. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3280. **
  3281. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3282. ** for the [prepared statement] or with a prepared statement for which
  3283. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3284. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3285. ** routine is passed a [prepared statement] that has been finalized, the
  3286. ** result is undefined and probably harmful.
  3287. **
  3288. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3289. ** ^Unbound parameters are interpreted as NULL.
  3290. **
  3291. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3292. ** [error code] if anything goes wrong.
  3293. ** ^[SQLITE_RANGE] is returned if the parameter
  3294. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3295. **
  3296. ** See also: [sqlite3_bind_parameter_count()],
  3297. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3298. */
  3299. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3300. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3301. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3302. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3303. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3304. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3305. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3306. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3307. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3308. /*
  3309. ** CAPI3REF: Number Of SQL Parameters
  3310. **
  3311. ** ^This routine can be used to find the number of [SQL parameters]
  3312. ** in a [prepared statement]. SQL parameters are tokens of the
  3313. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3314. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3315. ** to the parameters at a later time.
  3316. **
  3317. ** ^(This routine actually returns the index of the largest (rightmost)
  3318. ** parameter. For all forms except ?NNN, this will correspond to the
  3319. ** number of unique parameters. If parameters of the ?NNN form are used,
  3320. ** there may be gaps in the list.)^
  3321. **
  3322. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3323. ** [sqlite3_bind_parameter_name()], and
  3324. ** [sqlite3_bind_parameter_index()].
  3325. */
  3326. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3327. /*
  3328. ** CAPI3REF: Name Of A Host Parameter
  3329. **
  3330. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3331. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3332. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3333. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3334. ** respectively.
  3335. ** In other words, the initial ":" or "$" or "@" or "?"
  3336. ** is included as part of the name.)^
  3337. ** ^Parameters of the form "?" without a following integer have no name
  3338. ** and are referred to as "nameless" or "anonymous parameters".
  3339. **
  3340. ** ^The first host parameter has an index of 1, not 0.
  3341. **
  3342. ** ^If the value N is out of range or if the N-th parameter is
  3343. ** nameless, then NULL is returned. ^The returned string is
  3344. ** always in UTF-8 encoding even if the named parameter was
  3345. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3346. ** [sqlite3_prepare16_v2()].
  3347. **
  3348. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3349. ** [sqlite3_bind_parameter_count()], and
  3350. ** [sqlite3_bind_parameter_index()].
  3351. */
  3352. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3353. /*
  3354. ** CAPI3REF: Index Of A Parameter With A Given Name
  3355. **
  3356. ** ^Return the index of an SQL parameter given its name. ^The
  3357. ** index value returned is suitable for use as the second
  3358. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3359. ** is returned if no matching parameter is found. ^The parameter
  3360. ** name must be given in UTF-8 even if the original statement
  3361. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3362. **
  3363. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3364. ** [sqlite3_bind_parameter_count()], and
  3365. ** [sqlite3_bind_parameter_index()].
  3366. */
  3367. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3368. /*
  3369. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3370. **
  3371. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3372. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3373. ** ^Use this routine to reset all host parameters to NULL.
  3374. */
  3375. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3376. /*
  3377. ** CAPI3REF: Number Of Columns In A Result Set
  3378. **
  3379. ** ^Return the number of columns in the result set returned by the
  3380. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3381. ** statement that does not return data (for example an [UPDATE]).
  3382. **
  3383. ** See also: [sqlite3_data_count()]
  3384. */
  3385. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3386. /*
  3387. ** CAPI3REF: Column Names In A Result Set
  3388. **
  3389. ** ^These routines return the name assigned to a particular column
  3390. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3391. ** interface returns a pointer to a zero-terminated UTF-8 string
  3392. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3393. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3394. ** that implements the [SELECT] statement. ^The second parameter is the
  3395. ** column number. ^The leftmost column is number 0.
  3396. **
  3397. ** ^The returned string pointer is valid until either the [prepared statement]
  3398. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3399. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3400. ** or until the next call to
  3401. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3402. **
  3403. ** ^If sqlite3_malloc() fails during the processing of either routine
  3404. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3405. ** NULL pointer is returned.
  3406. **
  3407. ** ^The name of a result column is the value of the "AS" clause for
  3408. ** that column, if there is an AS clause. If there is no AS clause
  3409. ** then the name of the column is unspecified and may change from
  3410. ** one release of SQLite to the next.
  3411. */
  3412. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3413. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3414. /*
  3415. ** CAPI3REF: Source Of Data In A Query Result
  3416. **
  3417. ** ^These routines provide a means to determine the database, table, and
  3418. ** table column that is the origin of a particular result column in
  3419. ** [SELECT] statement.
  3420. ** ^The name of the database or table or column can be returned as
  3421. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3422. ** the database name, the _table_ routines return the table name, and
  3423. ** the origin_ routines return the column name.
  3424. ** ^The returned string is valid until the [prepared statement] is destroyed
  3425. ** using [sqlite3_finalize()] or until the statement is automatically
  3426. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3427. ** or until the same information is requested
  3428. ** again in a different encoding.
  3429. **
  3430. ** ^The names returned are the original un-aliased names of the
  3431. ** database, table, and column.
  3432. **
  3433. ** ^The first argument to these interfaces is a [prepared statement].
  3434. ** ^These functions return information about the Nth result column returned by
  3435. ** the statement, where N is the second function argument.
  3436. ** ^The left-most column is column 0 for these routines.
  3437. **
  3438. ** ^If the Nth column returned by the statement is an expression or
  3439. ** subquery and is not a column value, then all of these functions return
  3440. ** NULL. ^These routine might also return NULL if a memory allocation error
  3441. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3442. ** or column that query result column was extracted from.
  3443. **
  3444. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3445. ** UTF-16 encoded strings and the other functions return UTF-8.
  3446. **
  3447. ** ^These APIs are only available if the library was compiled with the
  3448. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3449. **
  3450. ** If two or more threads call one or more of these routines against the same
  3451. ** prepared statement and column at the same time then the results are
  3452. ** undefined.
  3453. **
  3454. ** If two or more threads call one or more
  3455. ** [sqlite3_column_database_name | column metadata interfaces]
  3456. ** for the same [prepared statement] and result column
  3457. ** at the same time then the results are undefined.
  3458. */
  3459. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3460. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3461. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3462. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3463. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3464. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3465. /*
  3466. ** CAPI3REF: Declared Datatype Of A Query Result
  3467. **
  3468. ** ^(The first parameter is a [prepared statement].
  3469. ** If this statement is a [SELECT] statement and the Nth column of the
  3470. ** returned result set of that [SELECT] is a table column (not an
  3471. ** expression or subquery) then the declared type of the table
  3472. ** column is returned.)^ ^If the Nth column of the result set is an
  3473. ** expression or subquery, then a NULL pointer is returned.
  3474. ** ^The returned string is always UTF-8 encoded.
  3475. **
  3476. ** ^(For example, given the database schema:
  3477. **
  3478. ** CREATE TABLE t1(c1 VARIANT);
  3479. **
  3480. ** and the following statement to be compiled:
  3481. **
  3482. ** SELECT c1 + 1, c1 FROM t1;
  3483. **
  3484. ** this routine would return the string "VARIANT" for the second result
  3485. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3486. **
  3487. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3488. ** is declared to contain a particular type does not mean that the
  3489. ** data stored in that column is of the declared type. SQLite is
  3490. ** strongly typed, but the typing is dynamic not static. ^Type
  3491. ** is associated with individual values, not with the containers
  3492. ** used to hold those values.
  3493. */
  3494. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3495. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3496. /*
  3497. ** CAPI3REF: Evaluate An SQL Statement
  3498. **
  3499. ** After a [prepared statement] has been prepared using either
  3500. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3501. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3502. ** must be called one or more times to evaluate the statement.
  3503. **
  3504. ** The details of the behavior of the sqlite3_step() interface depend
  3505. ** on whether the statement was prepared using the newer "v2" interface
  3506. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3507. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3508. ** new "v2" interface is recommended for new applications but the legacy
  3509. ** interface will continue to be supported.
  3510. **
  3511. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3512. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3513. ** ^With the "v2" interface, any of the other [result codes] or
  3514. ** [extended result codes] might be returned as well.
  3515. **
  3516. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3517. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3518. ** or occurs outside of an explicit transaction, then you can retry the
  3519. ** statement. If the statement is not a [COMMIT] and occurs within an
  3520. ** explicit transaction then you should rollback the transaction before
  3521. ** continuing.
  3522. **
  3523. ** ^[SQLITE_DONE] means that the statement has finished executing
  3524. ** successfully. sqlite3_step() should not be called again on this virtual
  3525. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3526. ** machine back to its initial state.
  3527. **
  3528. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3529. ** is returned each time a new row of data is ready for processing by the
  3530. ** caller. The values may be accessed using the [column access functions].
  3531. ** sqlite3_step() is called again to retrieve the next row of data.
  3532. **
  3533. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3534. ** violation) has occurred. sqlite3_step() should not be called again on
  3535. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3536. ** ^With the legacy interface, a more specific error code (for example,
  3537. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3538. ** can be obtained by calling [sqlite3_reset()] on the
  3539. ** [prepared statement]. ^In the "v2" interface,
  3540. ** the more specific error code is returned directly by sqlite3_step().
  3541. **
  3542. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3543. ** Perhaps it was called on a [prepared statement] that has
  3544. ** already been [sqlite3_finalize | finalized] or on one that had
  3545. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3546. ** be the case that the same database connection is being used by two or
  3547. ** more threads at the same moment in time.
  3548. **
  3549. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3550. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3551. ** other than [SQLITE_ROW] before any subsequent invocation of
  3552. ** sqlite3_step(). Failure to reset the prepared statement using
  3553. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3554. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3555. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3556. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3557. ** break because any application that ever receives an SQLITE_MISUSE error
  3558. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3559. ** can be used to restore the legacy behavior.
  3560. **
  3561. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3562. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3563. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3564. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3565. ** specific [error codes] that better describes the error.
  3566. ** We admit that this is a goofy design. The problem has been fixed
  3567. ** with the "v2" interface. If you prepare all of your SQL statements
  3568. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3569. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3570. ** then the more specific [error codes] are returned directly
  3571. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3572. */
  3573. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3574. /*
  3575. ** CAPI3REF: Number of columns in a result set
  3576. **
  3577. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3578. ** current row of the result set of [prepared statement] P.
  3579. ** ^If prepared statement P does not have results ready to return
  3580. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3581. ** interfaces) then sqlite3_data_count(P) returns 0.
  3582. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3583. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3584. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3585. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3586. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3587. ** where it always returns zero since each step of that multi-step
  3588. ** pragma returns 0 columns of data.
  3589. **
  3590. ** See also: [sqlite3_column_count()]
  3591. */
  3592. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3593. /*
  3594. ** CAPI3REF: Fundamental Datatypes
  3595. ** KEYWORDS: SQLITE_TEXT
  3596. **
  3597. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3598. **
  3599. ** <ul>
  3600. ** <li> 64-bit signed integer
  3601. ** <li> 64-bit IEEE floating point number
  3602. ** <li> string
  3603. ** <li> BLOB
  3604. ** <li> NULL
  3605. ** </ul>)^
  3606. **
  3607. ** These constants are codes for each of those types.
  3608. **
  3609. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3610. ** for a completely different meaning. Software that links against both
  3611. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3612. ** SQLITE_TEXT.
  3613. */
  3614. #define SQLITE_INTEGER 1
  3615. #define SQLITE_FLOAT 2
  3616. #define SQLITE_BLOB 4
  3617. #define SQLITE_NULL 5
  3618. #ifdef SQLITE_TEXT
  3619. # undef SQLITE_TEXT
  3620. #else
  3621. # define SQLITE_TEXT 3
  3622. #endif
  3623. #define SQLITE3_TEXT 3
  3624. /*
  3625. ** CAPI3REF: Result Values From A Query
  3626. ** KEYWORDS: {column access functions}
  3627. **
  3628. ** These routines form the "result set" interface.
  3629. **
  3630. ** ^These routines return information about a single column of the current
  3631. ** result row of a query. ^In every case the first argument is a pointer
  3632. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3633. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3634. ** and the second argument is the index of the column for which information
  3635. ** should be returned. ^The leftmost column of the result set has the index 0.
  3636. ** ^The number of columns in the result can be determined using
  3637. ** [sqlite3_column_count()].
  3638. **
  3639. ** If the SQL statement does not currently point to a valid row, or if the
  3640. ** column index is out of range, the result is undefined.
  3641. ** These routines may only be called when the most recent call to
  3642. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3643. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3644. ** If any of these routines are called after [sqlite3_reset()] or
  3645. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3646. ** something other than [SQLITE_ROW], the results are undefined.
  3647. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3648. ** are called from a different thread while any of these routines
  3649. ** are pending, then the results are undefined.
  3650. **
  3651. ** ^The sqlite3_column_type() routine returns the
  3652. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3653. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3654. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3655. ** returned by sqlite3_column_type() is only meaningful if no type
  3656. ** conversions have occurred as described below. After a type conversion,
  3657. ** the value returned by sqlite3_column_type() is undefined. Future
  3658. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3659. ** following a type conversion.
  3660. **
  3661. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3662. ** routine returns the number of bytes in that BLOB or string.
  3663. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3664. ** the string to UTF-8 and then returns the number of bytes.
  3665. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3666. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3667. ** the number of bytes in that string.
  3668. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3669. **
  3670. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3671. ** routine returns the number of bytes in that BLOB or string.
  3672. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3673. ** the string to UTF-16 and then returns the number of bytes.
  3674. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3675. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3676. ** the number of bytes in that string.
  3677. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3678. **
  3679. ** ^The values returned by [sqlite3_column_bytes()] and
  3680. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3681. ** of the string. ^For clarity: the values returned by
  3682. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3683. ** bytes in the string, not the number of characters.
  3684. **
  3685. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3686. ** even empty strings, are always zero-terminated. ^The return
  3687. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3688. **
  3689. ** ^The object returned by [sqlite3_column_value()] is an
  3690. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3691. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3692. ** If the [unprotected sqlite3_value] object returned by
  3693. ** [sqlite3_column_value()] is used in any other way, including calls
  3694. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3695. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3696. **
  3697. ** These routines attempt to convert the value where appropriate. ^For
  3698. ** example, if the internal representation is FLOAT and a text result
  3699. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3700. ** conversion automatically. ^(The following table details the conversions
  3701. ** that are applied:
  3702. **
  3703. ** <blockquote>
  3704. ** <table border="1">
  3705. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3706. **
  3707. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3708. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3709. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3710. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3711. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3712. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3713. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3714. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3715. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3716. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3717. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3718. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3719. ** <tr><td> TEXT <td> BLOB <td> No change
  3720. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3721. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3722. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3723. ** </table>
  3724. ** </blockquote>)^
  3725. **
  3726. ** The table above makes reference to standard C library functions atoi()
  3727. ** and atof(). SQLite does not really use these functions. It has its
  3728. ** own equivalent internal routines. The atoi() and atof() names are
  3729. ** used in the table for brevity and because they are familiar to most
  3730. ** C programmers.
  3731. **
  3732. ** Note that when type conversions occur, pointers returned by prior
  3733. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3734. ** sqlite3_column_text16() may be invalidated.
  3735. ** Type conversions and pointer invalidations might occur
  3736. ** in the following cases:
  3737. **
  3738. ** <ul>
  3739. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3740. ** sqlite3_column_text16() is called. A zero-terminator might
  3741. ** need to be added to the string.</li>
  3742. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3743. ** sqlite3_column_text16() is called. The content must be converted
  3744. ** to UTF-16.</li>
  3745. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3746. ** sqlite3_column_text() is called. The content must be converted
  3747. ** to UTF-8.</li>
  3748. ** </ul>
  3749. **
  3750. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3751. ** not invalidate a prior pointer, though of course the content of the buffer
  3752. ** that the prior pointer references will have been modified. Other kinds
  3753. ** of conversion are done in place when it is possible, but sometimes they
  3754. ** are not possible and in those cases prior pointers are invalidated.
  3755. **
  3756. ** The safest and easiest to remember policy is to invoke these routines
  3757. ** in one of the following ways:
  3758. **
  3759. ** <ul>
  3760. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3761. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3762. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3763. ** </ul>
  3764. **
  3765. ** In other words, you should call sqlite3_column_text(),
  3766. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3767. ** into the desired format, then invoke sqlite3_column_bytes() or
  3768. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3769. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3770. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3771. ** with calls to sqlite3_column_bytes().
  3772. **
  3773. ** ^The pointers returned are valid until a type conversion occurs as
  3774. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3775. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3776. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3777. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3778. ** [sqlite3_free()].
  3779. **
  3780. ** ^(If a memory allocation error occurs during the evaluation of any
  3781. ** of these routines, a default value is returned. The default value
  3782. ** is either the integer 0, the floating point number 0.0, or a NULL
  3783. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3784. ** [SQLITE_NOMEM].)^
  3785. */
  3786. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3787. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3788. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3789. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3790. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3791. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3792. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3793. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3794. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3795. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3796. /*
  3797. ** CAPI3REF: Destroy A Prepared Statement Object
  3798. **
  3799. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  3800. ** ^If the most recent evaluation of the statement encountered no errors
  3801. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  3802. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  3803. ** sqlite3_finalize(S) returns the appropriate [error code] or
  3804. ** [extended error code].
  3805. **
  3806. ** ^The sqlite3_finalize(S) routine can be called at any point during
  3807. ** the life cycle of [prepared statement] S:
  3808. ** before statement S is ever evaluated, after
  3809. ** one or more calls to [sqlite3_reset()], or after any call
  3810. ** to [sqlite3_step()] regardless of whether or not the statement has
  3811. ** completed execution.
  3812. **
  3813. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  3814. **
  3815. ** The application must finalize every [prepared statement] in order to avoid
  3816. ** resource leaks. It is a grievous error for the application to try to use
  3817. ** a prepared statement after it has been finalized. Any use of a prepared
  3818. ** statement after it has been finalized can result in undefined and
  3819. ** undesirable behavior such as segfaults and heap corruption.
  3820. */
  3821. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3822. /*
  3823. ** CAPI3REF: Reset A Prepared Statement Object
  3824. **
  3825. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3826. ** object back to its initial state, ready to be re-executed.
  3827. ** ^Any SQL statement variables that had values bound to them using
  3828. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3829. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3830. **
  3831. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3832. ** back to the beginning of its program.
  3833. **
  3834. ** ^If the most recent call to [sqlite3_step(S)] for the
  3835. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3836. ** or if [sqlite3_step(S)] has never before been called on S,
  3837. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3838. **
  3839. ** ^If the most recent call to [sqlite3_step(S)] for the
  3840. ** [prepared statement] S indicated an error, then
  3841. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3842. **
  3843. ** ^The [sqlite3_reset(S)] interface does not change the values
  3844. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3845. */
  3846. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3847. /*
  3848. ** CAPI3REF: Create Or Redefine SQL Functions
  3849. ** KEYWORDS: {function creation routines}
  3850. ** KEYWORDS: {application-defined SQL function}
  3851. ** KEYWORDS: {application-defined SQL functions}
  3852. **
  3853. ** ^These functions (collectively known as "function creation routines")
  3854. ** are used to add SQL functions or aggregates or to redefine the behavior
  3855. ** of existing SQL functions or aggregates. The only differences between
  3856. ** these routines are the text encoding expected for
  3857. ** the second parameter (the name of the function being created)
  3858. ** and the presence or absence of a destructor callback for
  3859. ** the application data pointer.
  3860. **
  3861. ** ^The first parameter is the [database connection] to which the SQL
  3862. ** function is to be added. ^If an application uses more than one database
  3863. ** connection then application-defined SQL functions must be added
  3864. ** to each database connection separately.
  3865. **
  3866. ** ^The second parameter is the name of the SQL function to be created or
  3867. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  3868. ** representation, exclusive of the zero-terminator. ^Note that the name
  3869. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  3870. ** ^Any attempt to create a function with a longer name
  3871. ** will result in [SQLITE_MISUSE] being returned.
  3872. **
  3873. ** ^The third parameter (nArg)
  3874. ** is the number of arguments that the SQL function or
  3875. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  3876. ** aggregate may take any number of arguments between 0 and the limit
  3877. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  3878. ** parameter is less than -1 or greater than 127 then the behavior is
  3879. ** undefined.
  3880. **
  3881. ** ^The fourth parameter, eTextRep, specifies what
  3882. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3883. ** its parameters. Every SQL function implementation must be able to work
  3884. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3885. ** more efficient with one encoding than another. ^An application may
  3886. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3887. ** times with the same function but with different values of eTextRep.
  3888. ** ^When multiple implementations of the same function are available, SQLite
  3889. ** will pick the one that involves the least amount of data conversion.
  3890. ** If there is only a single implementation which does not care what text
  3891. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3892. **
  3893. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  3894. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  3895. **
  3896. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  3897. ** pointers to C-language functions that implement the SQL function or
  3898. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  3899. ** callback only; NULL pointers must be passed as the xStep and xFinal
  3900. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  3901. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  3902. ** SQL function or aggregate, pass NULL pointers for all three function
  3903. ** callbacks.
  3904. **
  3905. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  3906. ** then it is destructor for the application data pointer.
  3907. ** The destructor is invoked when the function is deleted, either by being
  3908. ** overloaded or when the database connection closes.)^
  3909. ** ^The destructor is also invoked if the call to
  3910. ** sqlite3_create_function_v2() fails.
  3911. ** ^When the destructor callback of the tenth parameter is invoked, it
  3912. ** is passed a single argument which is a copy of the application data
  3913. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  3914. **
  3915. ** ^It is permitted to register multiple implementations of the same
  3916. ** functions with the same name but with either differing numbers of
  3917. ** arguments or differing preferred text encodings. ^SQLite will use
  3918. ** the implementation that most closely matches the way in which the
  3919. ** SQL function is used. ^A function implementation with a non-negative
  3920. ** nArg parameter is a better match than a function implementation with
  3921. ** a negative nArg. ^A function where the preferred text encoding
  3922. ** matches the database encoding is a better
  3923. ** match than a function where the encoding is different.
  3924. ** ^A function where the encoding difference is between UTF16le and UTF16be
  3925. ** is a closer match than a function where the encoding difference is
  3926. ** between UTF8 and UTF16.
  3927. **
  3928. ** ^Built-in functions may be overloaded by new application-defined functions.
  3929. **
  3930. ** ^An application-defined function is permitted to call other
  3931. ** SQLite interfaces. However, such calls must not
  3932. ** close the database connection nor finalize or reset the prepared
  3933. ** statement in which the function is running.
  3934. */
  3935. SQLITE_API int sqlite3_create_function(
  3936. sqlite3 *db,
  3937. const char *zFunctionName,
  3938. int nArg,
  3939. int eTextRep,
  3940. void *pApp,
  3941. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3942. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3943. void (*xFinal)(sqlite3_context*)
  3944. );
  3945. SQLITE_API int sqlite3_create_function16(
  3946. sqlite3 *db,
  3947. const void *zFunctionName,
  3948. int nArg,
  3949. int eTextRep,
  3950. void *pApp,
  3951. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3952. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3953. void (*xFinal)(sqlite3_context*)
  3954. );
  3955. SQLITE_API int sqlite3_create_function_v2(
  3956. sqlite3 *db,
  3957. const char *zFunctionName,
  3958. int nArg,
  3959. int eTextRep,
  3960. void *pApp,
  3961. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3962. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3963. void (*xFinal)(sqlite3_context*),
  3964. void(*xDestroy)(void*)
  3965. );
  3966. /*
  3967. ** CAPI3REF: Text Encodings
  3968. **
  3969. ** These constant define integer codes that represent the various
  3970. ** text encodings supported by SQLite.
  3971. */
  3972. #define SQLITE_UTF8 1
  3973. #define SQLITE_UTF16LE 2
  3974. #define SQLITE_UTF16BE 3
  3975. #define SQLITE_UTF16 4 /* Use native byte order */
  3976. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  3977. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  3978. /*
  3979. ** CAPI3REF: Deprecated Functions
  3980. ** DEPRECATED
  3981. **
  3982. ** These functions are [deprecated]. In order to maintain
  3983. ** backwards compatibility with older code, these functions continue
  3984. ** to be supported. However, new applications should avoid
  3985. ** the use of these functions. To help encourage people to avoid
  3986. ** using these functions, we are not going to tell you what they do.
  3987. */
  3988. #ifndef SQLITE_OMIT_DEPRECATED
  3989. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  3990. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  3991. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  3992. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  3993. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  3994. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  3995. void*,sqlite3_int64);
  3996. #endif
  3997. /*
  3998. ** CAPI3REF: Obtaining SQL Function Parameter Values
  3999. **
  4000. ** The C-language implementation of SQL functions and aggregates uses
  4001. ** this set of interface routines to access the parameter values on
  4002. ** the function or aggregate.
  4003. **
  4004. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4005. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4006. ** define callbacks that implement the SQL functions and aggregates.
  4007. ** The 3rd parameter to these callbacks is an array of pointers to
  4008. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4009. ** each parameter to the SQL function. These routines are used to
  4010. ** extract values from the [sqlite3_value] objects.
  4011. **
  4012. ** These routines work only with [protected sqlite3_value] objects.
  4013. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4014. ** object results in undefined behavior.
  4015. **
  4016. ** ^These routines work just like the corresponding [column access functions]
  4017. ** except that these routines take a single [protected sqlite3_value] object
  4018. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4019. **
  4020. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4021. ** in the native byte-order of the host machine. ^The
  4022. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4023. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4024. **
  4025. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4026. ** numeric affinity to the value. This means that an attempt is
  4027. ** made to convert the value to an integer or floating point. If
  4028. ** such a conversion is possible without loss of information (in other
  4029. ** words, if the value is a string that looks like a number)
  4030. ** then the conversion is performed. Otherwise no conversion occurs.
  4031. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4032. **
  4033. ** Please pay particular attention to the fact that the pointer returned
  4034. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4035. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4036. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4037. ** or [sqlite3_value_text16()].
  4038. **
  4039. ** These routines must be called from the same thread as
  4040. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4041. */
  4042. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4043. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4044. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4045. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4046. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4047. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4048. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4049. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4050. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4051. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4052. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4053. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4054. /*
  4055. ** CAPI3REF: Obtain Aggregate Function Context
  4056. **
  4057. ** Implementations of aggregate SQL functions use this
  4058. ** routine to allocate memory for storing their state.
  4059. **
  4060. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4061. ** for a particular aggregate function, SQLite
  4062. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4063. ** to the new memory. ^On second and subsequent calls to
  4064. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4065. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4066. ** called once for each invocation of the xStep callback and then one
  4067. ** last time when the xFinal callback is invoked. ^(When no rows match
  4068. ** an aggregate query, the xStep() callback of the aggregate function
  4069. ** implementation is never called and xFinal() is called exactly once.
  4070. ** In those cases, sqlite3_aggregate_context() might be called for the
  4071. ** first time from within xFinal().)^
  4072. **
  4073. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4074. ** when first called if N is less than or equal to zero or if a memory
  4075. ** allocate error occurs.
  4076. **
  4077. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4078. ** determined by the N parameter on first successful call. Changing the
  4079. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4080. ** the same aggregate function instance will not resize the memory
  4081. ** allocation.)^ Within the xFinal callback, it is customary to set
  4082. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4083. ** pointless memory allocations occur.
  4084. **
  4085. ** ^SQLite automatically frees the memory allocated by
  4086. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4087. **
  4088. ** The first parameter must be a copy of the
  4089. ** [sqlite3_context | SQL function context] that is the first parameter
  4090. ** to the xStep or xFinal callback routine that implements the aggregate
  4091. ** function.
  4092. **
  4093. ** This routine must be called from the same thread in which
  4094. ** the aggregate SQL function is running.
  4095. */
  4096. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4097. /*
  4098. ** CAPI3REF: User Data For Functions
  4099. **
  4100. ** ^The sqlite3_user_data() interface returns a copy of
  4101. ** the pointer that was the pUserData parameter (the 5th parameter)
  4102. ** of the [sqlite3_create_function()]
  4103. ** and [sqlite3_create_function16()] routines that originally
  4104. ** registered the application defined function.
  4105. **
  4106. ** This routine must be called from the same thread in which
  4107. ** the application-defined function is running.
  4108. */
  4109. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4110. /*
  4111. ** CAPI3REF: Database Connection For Functions
  4112. **
  4113. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4114. ** the pointer to the [database connection] (the 1st parameter)
  4115. ** of the [sqlite3_create_function()]
  4116. ** and [sqlite3_create_function16()] routines that originally
  4117. ** registered the application defined function.
  4118. */
  4119. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4120. /*
  4121. ** CAPI3REF: Function Auxiliary Data
  4122. **
  4123. ** These functions may be used by (non-aggregate) SQL functions to
  4124. ** associate metadata with argument values. If the same value is passed to
  4125. ** multiple invocations of the same SQL function during query execution, under
  4126. ** some circumstances the associated metadata may be preserved. An example
  4127. ** of where this might be useful is in a regular-expression matching
  4128. ** function. The compiled version of the regular expression can be stored as
  4129. ** metadata associated with the pattern string.
  4130. ** Then as long as the pattern string remains the same,
  4131. ** the compiled regular expression can be reused on multiple
  4132. ** invocations of the same function.
  4133. **
  4134. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4135. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4136. ** value to the application-defined function. ^If there is no metadata
  4137. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4138. ** returns a NULL pointer.
  4139. **
  4140. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4141. ** argument of the application-defined function. ^Subsequent
  4142. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4143. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4144. ** NULL if the metadata has been discarded.
  4145. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4146. ** SQLite will invoke the destructor function X with parameter P exactly
  4147. ** once, when the metadata is discarded.
  4148. ** SQLite is free to discard the metadata at any time, including: <ul>
  4149. ** <li> when the corresponding function parameter changes, or
  4150. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4151. ** SQL statement, or
  4152. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4153. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4154. ** allocation error occurs. </ul>)^
  4155. **
  4156. ** Note the last bullet in particular. The destructor X in
  4157. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4158. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4159. ** should be called near the end of the function implementation and the
  4160. ** function implementation should not make any use of P after
  4161. ** sqlite3_set_auxdata() has been called.
  4162. **
  4163. ** ^(In practice, metadata is preserved between function calls for
  4164. ** function parameters that are compile-time constants, including literal
  4165. ** values and [parameters] and expressions composed from the same.)^
  4166. **
  4167. ** These routines must be called from the same thread in which
  4168. ** the SQL function is running.
  4169. */
  4170. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4171. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4172. /*
  4173. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4174. **
  4175. ** These are special values for the destructor that is passed in as the
  4176. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4177. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4178. ** and will never change. It does not need to be destroyed. ^The
  4179. ** SQLITE_TRANSIENT value means that the content will likely change in
  4180. ** the near future and that SQLite should make its own private copy of
  4181. ** the content before returning.
  4182. **
  4183. ** The typedef is necessary to work around problems in certain
  4184. ** C++ compilers.
  4185. */
  4186. typedef void (*sqlite3_destructor_type)(void*);
  4187. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4188. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4189. /*
  4190. ** CAPI3REF: Setting The Result Of An SQL Function
  4191. **
  4192. ** These routines are used by the xFunc or xFinal callbacks that
  4193. ** implement SQL functions and aggregates. See
  4194. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4195. ** for additional information.
  4196. **
  4197. ** These functions work very much like the [parameter binding] family of
  4198. ** functions used to bind values to host parameters in prepared statements.
  4199. ** Refer to the [SQL parameter] documentation for additional information.
  4200. **
  4201. ** ^The sqlite3_result_blob() interface sets the result from
  4202. ** an application-defined function to be the BLOB whose content is pointed
  4203. ** to by the second parameter and which is N bytes long where N is the
  4204. ** third parameter.
  4205. **
  4206. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4207. ** the application-defined function to be a BLOB containing all zero
  4208. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4209. **
  4210. ** ^The sqlite3_result_double() interface sets the result from
  4211. ** an application-defined function to be a floating point value specified
  4212. ** by its 2nd argument.
  4213. **
  4214. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4215. ** cause the implemented SQL function to throw an exception.
  4216. ** ^SQLite uses the string pointed to by the
  4217. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4218. ** as the text of an error message. ^SQLite interprets the error
  4219. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4220. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4221. ** byte order. ^If the third parameter to sqlite3_result_error()
  4222. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4223. ** message all text up through the first zero character.
  4224. ** ^If the third parameter to sqlite3_result_error() or
  4225. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4226. ** bytes (not characters) from the 2nd parameter as the error message.
  4227. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4228. ** routines make a private copy of the error message text before
  4229. ** they return. Hence, the calling function can deallocate or
  4230. ** modify the text after they return without harm.
  4231. ** ^The sqlite3_result_error_code() function changes the error code
  4232. ** returned by SQLite as a result of an error in a function. ^By default,
  4233. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4234. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4235. **
  4236. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4237. ** error indicating that a string or BLOB is too long to represent.
  4238. **
  4239. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4240. ** error indicating that a memory allocation failed.
  4241. **
  4242. ** ^The sqlite3_result_int() interface sets the return value
  4243. ** of the application-defined function to be the 32-bit signed integer
  4244. ** value given in the 2nd argument.
  4245. ** ^The sqlite3_result_int64() interface sets the return value
  4246. ** of the application-defined function to be the 64-bit signed integer
  4247. ** value given in the 2nd argument.
  4248. **
  4249. ** ^The sqlite3_result_null() interface sets the return value
  4250. ** of the application-defined function to be NULL.
  4251. **
  4252. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4253. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4254. ** set the return value of the application-defined function to be
  4255. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4256. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4257. ** ^SQLite takes the text result from the application from
  4258. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4259. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4260. ** is negative, then SQLite takes result text from the 2nd parameter
  4261. ** through the first zero character.
  4262. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4263. ** is non-negative, then as many bytes (not characters) of the text
  4264. ** pointed to by the 2nd parameter are taken as the application-defined
  4265. ** function result. If the 3rd parameter is non-negative, then it
  4266. ** must be the byte offset into the string where the NUL terminator would
  4267. ** appear if the string where NUL terminated. If any NUL characters occur
  4268. ** in the string at a byte offset that is less than the value of the 3rd
  4269. ** parameter, then the resulting string will contain embedded NULs and the
  4270. ** result of expressions operating on strings with embedded NULs is undefined.
  4271. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4272. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4273. ** function as the destructor on the text or BLOB result when it has
  4274. ** finished using that result.
  4275. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4276. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4277. ** assumes that the text or BLOB result is in constant space and does not
  4278. ** copy the content of the parameter nor call a destructor on the content
  4279. ** when it has finished using that result.
  4280. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4281. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4282. ** then SQLite makes a copy of the result into space obtained from
  4283. ** from [sqlite3_malloc()] before it returns.
  4284. **
  4285. ** ^The sqlite3_result_value() interface sets the result of
  4286. ** the application-defined function to be a copy the
  4287. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4288. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4289. ** so that the [sqlite3_value] specified in the parameter may change or
  4290. ** be deallocated after sqlite3_result_value() returns without harm.
  4291. ** ^A [protected sqlite3_value] object may always be used where an
  4292. ** [unprotected sqlite3_value] object is required, so either
  4293. ** kind of [sqlite3_value] object can be used with this interface.
  4294. **
  4295. ** If these routines are called from within the different thread
  4296. ** than the one containing the application-defined function that received
  4297. ** the [sqlite3_context] pointer, the results are undefined.
  4298. */
  4299. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4300. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4301. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4302. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4303. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4304. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4305. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4306. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4307. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4308. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4309. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4310. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4311. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4312. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4313. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4314. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4315. /*
  4316. ** CAPI3REF: Define New Collating Sequences
  4317. **
  4318. ** ^These functions add, remove, or modify a [collation] associated
  4319. ** with the [database connection] specified as the first argument.
  4320. **
  4321. ** ^The name of the collation is a UTF-8 string
  4322. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4323. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4324. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4325. ** considered to be the same name.
  4326. **
  4327. ** ^(The third argument (eTextRep) must be one of the constants:
  4328. ** <ul>
  4329. ** <li> [SQLITE_UTF8],
  4330. ** <li> [SQLITE_UTF16LE],
  4331. ** <li> [SQLITE_UTF16BE],
  4332. ** <li> [SQLITE_UTF16], or
  4333. ** <li> [SQLITE_UTF16_ALIGNED].
  4334. ** </ul>)^
  4335. ** ^The eTextRep argument determines the encoding of strings passed
  4336. ** to the collating function callback, xCallback.
  4337. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4338. ** force strings to be UTF16 with native byte order.
  4339. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4340. ** on an even byte address.
  4341. **
  4342. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4343. ** through as the first argument to the collating function callback.
  4344. **
  4345. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4346. ** ^Multiple collating functions can be registered using the same name but
  4347. ** with different eTextRep parameters and SQLite will use whichever
  4348. ** function requires the least amount of data transformation.
  4349. ** ^If the xCallback argument is NULL then the collating function is
  4350. ** deleted. ^When all collating functions having the same name are deleted,
  4351. ** that collation is no longer usable.
  4352. **
  4353. ** ^The collating function callback is invoked with a copy of the pArg
  4354. ** application data pointer and with two strings in the encoding specified
  4355. ** by the eTextRep argument. The collating function must return an
  4356. ** integer that is negative, zero, or positive
  4357. ** if the first string is less than, equal to, or greater than the second,
  4358. ** respectively. A collating function must always return the same answer
  4359. ** given the same inputs. If two or more collating functions are registered
  4360. ** to the same collation name (using different eTextRep values) then all
  4361. ** must give an equivalent answer when invoked with equivalent strings.
  4362. ** The collating function must obey the following properties for all
  4363. ** strings A, B, and C:
  4364. **
  4365. ** <ol>
  4366. ** <li> If A==B then B==A.
  4367. ** <li> If A==B and B==C then A==C.
  4368. ** <li> If A&lt;B THEN B&gt;A.
  4369. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4370. ** </ol>
  4371. **
  4372. ** If a collating function fails any of the above constraints and that
  4373. ** collating function is registered and used, then the behavior of SQLite
  4374. ** is undefined.
  4375. **
  4376. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4377. ** with the addition that the xDestroy callback is invoked on pArg when
  4378. ** the collating function is deleted.
  4379. ** ^Collating functions are deleted when they are overridden by later
  4380. ** calls to the collation creation functions or when the
  4381. ** [database connection] is closed using [sqlite3_close()].
  4382. **
  4383. ** ^The xDestroy callback is <u>not</u> called if the
  4384. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4385. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4386. ** check the return code and dispose of the application data pointer
  4387. ** themselves rather than expecting SQLite to deal with it for them.
  4388. ** This is different from every other SQLite interface. The inconsistency
  4389. ** is unfortunate but cannot be changed without breaking backwards
  4390. ** compatibility.
  4391. **
  4392. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4393. */
  4394. SQLITE_API int sqlite3_create_collation(
  4395. sqlite3*,
  4396. const char *zName,
  4397. int eTextRep,
  4398. void *pArg,
  4399. int(*xCompare)(void*,int,const void*,int,const void*)
  4400. );
  4401. SQLITE_API int sqlite3_create_collation_v2(
  4402. sqlite3*,
  4403. const char *zName,
  4404. int eTextRep,
  4405. void *pArg,
  4406. int(*xCompare)(void*,int,const void*,int,const void*),
  4407. void(*xDestroy)(void*)
  4408. );
  4409. SQLITE_API int sqlite3_create_collation16(
  4410. sqlite3*,
  4411. const void *zName,
  4412. int eTextRep,
  4413. void *pArg,
  4414. int(*xCompare)(void*,int,const void*,int,const void*)
  4415. );
  4416. /*
  4417. ** CAPI3REF: Collation Needed Callbacks
  4418. **
  4419. ** ^To avoid having to register all collation sequences before a database
  4420. ** can be used, a single callback function may be registered with the
  4421. ** [database connection] to be invoked whenever an undefined collation
  4422. ** sequence is required.
  4423. **
  4424. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4425. ** then it is passed the names of undefined collation sequences as strings
  4426. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4427. ** the names are passed as UTF-16 in machine native byte order.
  4428. ** ^A call to either function replaces the existing collation-needed callback.
  4429. **
  4430. ** ^(When the callback is invoked, the first argument passed is a copy
  4431. ** of the second argument to sqlite3_collation_needed() or
  4432. ** sqlite3_collation_needed16(). The second argument is the database
  4433. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4434. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4435. ** sequence function required. The fourth parameter is the name of the
  4436. ** required collation sequence.)^
  4437. **
  4438. ** The callback function should register the desired collation using
  4439. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4440. ** [sqlite3_create_collation_v2()].
  4441. */
  4442. SQLITE_API int sqlite3_collation_needed(
  4443. sqlite3*,
  4444. void*,
  4445. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4446. );
  4447. SQLITE_API int sqlite3_collation_needed16(
  4448. sqlite3*,
  4449. void*,
  4450. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4451. );
  4452. #ifdef SQLITE_HAS_CODEC
  4453. /*
  4454. ** Specify the key for an encrypted database. This routine should be
  4455. ** called right after sqlite3_open().
  4456. **
  4457. ** The code to implement this API is not available in the public release
  4458. ** of SQLite.
  4459. */
  4460. SQLITE_API int sqlite3_key(
  4461. sqlite3 *db, /* Database to be rekeyed */
  4462. const void *pKey, int nKey /* The key */
  4463. );
  4464. SQLITE_API int sqlite3_key_v2(
  4465. sqlite3 *db, /* Database to be rekeyed */
  4466. const char *zDbName, /* Name of the database */
  4467. const void *pKey, int nKey /* The key */
  4468. );
  4469. /*
  4470. ** Change the key on an open database. If the current database is not
  4471. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4472. ** database is decrypted.
  4473. **
  4474. ** The code to implement this API is not available in the public release
  4475. ** of SQLite.
  4476. */
  4477. SQLITE_API int sqlite3_rekey(
  4478. sqlite3 *db, /* Database to be rekeyed */
  4479. const void *pKey, int nKey /* The new key */
  4480. );
  4481. SQLITE_API int sqlite3_rekey_v2(
  4482. sqlite3 *db, /* Database to be rekeyed */
  4483. const char *zDbName, /* Name of the database */
  4484. const void *pKey, int nKey /* The new key */
  4485. );
  4486. /*
  4487. ** Specify the activation key for a SEE database. Unless
  4488. ** activated, none of the SEE routines will work.
  4489. */
  4490. SQLITE_API void sqlite3_activate_see(
  4491. const char *zPassPhrase /* Activation phrase */
  4492. );
  4493. #endif
  4494. #ifdef SQLITE_ENABLE_CEROD
  4495. /*
  4496. ** Specify the activation key for a CEROD database. Unless
  4497. ** activated, none of the CEROD routines will work.
  4498. */
  4499. SQLITE_API void sqlite3_activate_cerod(
  4500. const char *zPassPhrase /* Activation phrase */
  4501. );
  4502. #endif
  4503. /*
  4504. ** CAPI3REF: Suspend Execution For A Short Time
  4505. **
  4506. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4507. ** for at least a number of milliseconds specified in its parameter.
  4508. **
  4509. ** If the operating system does not support sleep requests with
  4510. ** millisecond time resolution, then the time will be rounded up to
  4511. ** the nearest second. The number of milliseconds of sleep actually
  4512. ** requested from the operating system is returned.
  4513. **
  4514. ** ^SQLite implements this interface by calling the xSleep()
  4515. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4516. ** of the default VFS is not implemented correctly, or not implemented at
  4517. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4518. ** in the previous paragraphs.
  4519. */
  4520. SQLITE_API int sqlite3_sleep(int);
  4521. /*
  4522. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4523. **
  4524. ** ^(If this global variable is made to point to a string which is
  4525. ** the name of a folder (a.k.a. directory), then all temporary files
  4526. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4527. ** will be placed in that directory.)^ ^If this variable
  4528. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4529. ** temporary file directory.
  4530. **
  4531. ** It is not safe to read or modify this variable in more than one
  4532. ** thread at a time. It is not safe to read or modify this variable
  4533. ** if a [database connection] is being used at the same time in a separate
  4534. ** thread.
  4535. ** It is intended that this variable be set once
  4536. ** as part of process initialization and before any SQLite interface
  4537. ** routines have been called and that this variable remain unchanged
  4538. ** thereafter.
  4539. **
  4540. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4541. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4542. ** the [temp_store_directory pragma] always assumes that any string
  4543. ** that this variable points to is held in memory obtained from
  4544. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4545. ** using [sqlite3_free].
  4546. ** Hence, if this variable is modified directly, either it should be
  4547. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4548. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4549. **
  4550. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4551. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4552. ** features that require the use of temporary files may fail. Here is an
  4553. ** example of how to do this using C++ with the Windows Runtime:
  4554. **
  4555. ** <blockquote><pre>
  4556. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4557. ** &nbsp; TemporaryFolder->Path->Data();
  4558. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4559. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4560. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4561. ** &nbsp; NULL, NULL);
  4562. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4563. ** </pre></blockquote>
  4564. */
  4565. SQLITE_API char *sqlite3_temp_directory;
  4566. /*
  4567. ** CAPI3REF: Name Of The Folder Holding Database Files
  4568. **
  4569. ** ^(If this global variable is made to point to a string which is
  4570. ** the name of a folder (a.k.a. directory), then all database files
  4571. ** specified with a relative pathname and created or accessed by
  4572. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4573. ** to be relative to that directory.)^ ^If this variable is a NULL
  4574. ** pointer, then SQLite assumes that all database files specified
  4575. ** with a relative pathname are relative to the current directory
  4576. ** for the process. Only the windows VFS makes use of this global
  4577. ** variable; it is ignored by the unix VFS.
  4578. **
  4579. ** Changing the value of this variable while a database connection is
  4580. ** open can result in a corrupt database.
  4581. **
  4582. ** It is not safe to read or modify this variable in more than one
  4583. ** thread at a time. It is not safe to read or modify this variable
  4584. ** if a [database connection] is being used at the same time in a separate
  4585. ** thread.
  4586. ** It is intended that this variable be set once
  4587. ** as part of process initialization and before any SQLite interface
  4588. ** routines have been called and that this variable remain unchanged
  4589. ** thereafter.
  4590. **
  4591. ** ^The [data_store_directory pragma] may modify this variable and cause
  4592. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4593. ** the [data_store_directory pragma] always assumes that any string
  4594. ** that this variable points to is held in memory obtained from
  4595. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4596. ** using [sqlite3_free].
  4597. ** Hence, if this variable is modified directly, either it should be
  4598. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4599. ** or else the use of the [data_store_directory pragma] should be avoided.
  4600. */
  4601. SQLITE_API char *sqlite3_data_directory;
  4602. /*
  4603. ** CAPI3REF: Test For Auto-Commit Mode
  4604. ** KEYWORDS: {autocommit mode}
  4605. **
  4606. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4607. ** zero if the given database connection is or is not in autocommit mode,
  4608. ** respectively. ^Autocommit mode is on by default.
  4609. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4610. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4611. **
  4612. ** If certain kinds of errors occur on a statement within a multi-statement
  4613. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4614. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4615. ** transaction might be rolled back automatically. The only way to
  4616. ** find out whether SQLite automatically rolled back the transaction after
  4617. ** an error is to use this function.
  4618. **
  4619. ** If another thread changes the autocommit status of the database
  4620. ** connection while this routine is running, then the return value
  4621. ** is undefined.
  4622. */
  4623. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4624. /*
  4625. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4626. **
  4627. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4628. ** to which a [prepared statement] belongs. ^The [database connection]
  4629. ** returned by sqlite3_db_handle is the same [database connection]
  4630. ** that was the first argument
  4631. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4632. ** create the statement in the first place.
  4633. */
  4634. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4635. /*
  4636. ** CAPI3REF: Return The Filename For A Database Connection
  4637. **
  4638. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4639. ** associated with database N of connection D. ^The main database file
  4640. ** has the name "main". If there is no attached database N on the database
  4641. ** connection D, or if database N is a temporary or in-memory database, then
  4642. ** a NULL pointer is returned.
  4643. **
  4644. ** ^The filename returned by this function is the output of the
  4645. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4646. ** will be an absolute pathname, even if the filename used
  4647. ** to open the database originally was a URI or relative pathname.
  4648. */
  4649. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4650. /*
  4651. ** CAPI3REF: Determine if a database is read-only
  4652. **
  4653. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4654. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4655. ** the name of a database on connection D.
  4656. */
  4657. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4658. /*
  4659. ** CAPI3REF: Find the next prepared statement
  4660. **
  4661. ** ^This interface returns a pointer to the next [prepared statement] after
  4662. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4663. ** then this interface returns a pointer to the first prepared statement
  4664. ** associated with the database connection pDb. ^If no prepared statement
  4665. ** satisfies the conditions of this routine, it returns NULL.
  4666. **
  4667. ** The [database connection] pointer D in a call to
  4668. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4669. ** connection and in particular must not be a NULL pointer.
  4670. */
  4671. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4672. /*
  4673. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4674. **
  4675. ** ^The sqlite3_commit_hook() interface registers a callback
  4676. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4677. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4678. ** for the same database connection is overridden.
  4679. ** ^The sqlite3_rollback_hook() interface registers a callback
  4680. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4681. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4682. ** for the same database connection is overridden.
  4683. ** ^The pArg argument is passed through to the callback.
  4684. ** ^If the callback on a commit hook function returns non-zero,
  4685. ** then the commit is converted into a rollback.
  4686. **
  4687. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4688. ** return the P argument from the previous call of the same function
  4689. ** on the same [database connection] D, or NULL for
  4690. ** the first call for each function on D.
  4691. **
  4692. ** The commit and rollback hook callbacks are not reentrant.
  4693. ** The callback implementation must not do anything that will modify
  4694. ** the database connection that invoked the callback. Any actions
  4695. ** to modify the database connection must be deferred until after the
  4696. ** completion of the [sqlite3_step()] call that triggered the commit
  4697. ** or rollback hook in the first place.
  4698. ** Note that running any other SQL statements, including SELECT statements,
  4699. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4700. ** the database connections for the meaning of "modify" in this paragraph.
  4701. **
  4702. ** ^Registering a NULL function disables the callback.
  4703. **
  4704. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4705. ** operation is allowed to continue normally. ^If the commit hook
  4706. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4707. ** ^The rollback hook is invoked on a rollback that results from a commit
  4708. ** hook returning non-zero, just as it would be with any other rollback.
  4709. **
  4710. ** ^For the purposes of this API, a transaction is said to have been
  4711. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4712. ** an error or constraint causes an implicit rollback to occur.
  4713. ** ^The rollback callback is not invoked if a transaction is
  4714. ** automatically rolled back because the database connection is closed.
  4715. **
  4716. ** See also the [sqlite3_update_hook()] interface.
  4717. */
  4718. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4719. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4720. /*
  4721. ** CAPI3REF: Data Change Notification Callbacks
  4722. **
  4723. ** ^The sqlite3_update_hook() interface registers a callback function
  4724. ** with the [database connection] identified by the first argument
  4725. ** to be invoked whenever a row is updated, inserted or deleted.
  4726. ** ^Any callback set by a previous call to this function
  4727. ** for the same database connection is overridden.
  4728. **
  4729. ** ^The second argument is a pointer to the function to invoke when a
  4730. ** row is updated, inserted or deleted.
  4731. ** ^The first argument to the callback is a copy of the third argument
  4732. ** to sqlite3_update_hook().
  4733. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4734. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4735. ** to be invoked.
  4736. ** ^The third and fourth arguments to the callback contain pointers to the
  4737. ** database and table name containing the affected row.
  4738. ** ^The final callback parameter is the [rowid] of the row.
  4739. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4740. **
  4741. ** ^(The update hook is not invoked when internal system tables are
  4742. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4743. **
  4744. ** ^In the current implementation, the update hook
  4745. ** is not invoked when duplication rows are deleted because of an
  4746. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4747. ** invoked when rows are deleted using the [truncate optimization].
  4748. ** The exceptions defined in this paragraph might change in a future
  4749. ** release of SQLite.
  4750. **
  4751. ** The update hook implementation must not do anything that will modify
  4752. ** the database connection that invoked the update hook. Any actions
  4753. ** to modify the database connection must be deferred until after the
  4754. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4755. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4756. ** database connections for the meaning of "modify" in this paragraph.
  4757. **
  4758. ** ^The sqlite3_update_hook(D,C,P) function
  4759. ** returns the P argument from the previous call
  4760. ** on the same [database connection] D, or NULL for
  4761. ** the first call on D.
  4762. **
  4763. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4764. ** interfaces.
  4765. */
  4766. SQLITE_API void *sqlite3_update_hook(
  4767. sqlite3*,
  4768. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4769. void*
  4770. );
  4771. /*
  4772. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4773. **
  4774. ** ^(This routine enables or disables the sharing of the database cache
  4775. ** and schema data structures between [database connection | connections]
  4776. ** to the same database. Sharing is enabled if the argument is true
  4777. ** and disabled if the argument is false.)^
  4778. **
  4779. ** ^Cache sharing is enabled and disabled for an entire process.
  4780. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4781. ** sharing was enabled or disabled for each thread separately.
  4782. **
  4783. ** ^(The cache sharing mode set by this interface effects all subsequent
  4784. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4785. ** Existing database connections continue use the sharing mode
  4786. ** that was in effect at the time they were opened.)^
  4787. **
  4788. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4789. ** successfully. An [error code] is returned otherwise.)^
  4790. **
  4791. ** ^Shared cache is disabled by default. But this might change in
  4792. ** future releases of SQLite. Applications that care about shared
  4793. ** cache setting should set it explicitly.
  4794. **
  4795. ** This interface is threadsafe on processors where writing a
  4796. ** 32-bit integer is atomic.
  4797. **
  4798. ** See Also: [SQLite Shared-Cache Mode]
  4799. */
  4800. SQLITE_API int sqlite3_enable_shared_cache(int);
  4801. /*
  4802. ** CAPI3REF: Attempt To Free Heap Memory
  4803. **
  4804. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  4805. ** of heap memory by deallocating non-essential memory allocations
  4806. ** held by the database library. Memory used to cache database
  4807. ** pages to improve performance is an example of non-essential memory.
  4808. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4809. ** which might be more or less than the amount requested.
  4810. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4811. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4812. **
  4813. ** See also: [sqlite3_db_release_memory()]
  4814. */
  4815. SQLITE_API int sqlite3_release_memory(int);
  4816. /*
  4817. ** CAPI3REF: Free Memory Used By A Database Connection
  4818. **
  4819. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  4820. ** memory as possible from database connection D. Unlike the
  4821. ** [sqlite3_release_memory()] interface, this interface is effect even
  4822. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  4823. ** omitted.
  4824. **
  4825. ** See also: [sqlite3_release_memory()]
  4826. */
  4827. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  4828. /*
  4829. ** CAPI3REF: Impose A Limit On Heap Size
  4830. **
  4831. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4832. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4833. ** ^SQLite strives to keep heap memory utilization below the soft heap
  4834. ** limit by reducing the number of pages held in the page cache
  4835. ** as heap memory usages approaches the limit.
  4836. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4837. ** below the limit, it will exceed the limit rather than generate
  4838. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  4839. ** is advisory only.
  4840. **
  4841. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4842. ** the soft heap limit prior to the call, or negative in the case of an
  4843. ** error. ^If the argument N is negative
  4844. ** then no change is made to the soft heap limit. Hence, the current
  4845. ** size of the soft heap limit can be determined by invoking
  4846. ** sqlite3_soft_heap_limit64() with a negative argument.
  4847. **
  4848. ** ^If the argument N is zero then the soft heap limit is disabled.
  4849. **
  4850. ** ^(The soft heap limit is not enforced in the current implementation
  4851. ** if one or more of following conditions are true:
  4852. **
  4853. ** <ul>
  4854. ** <li> The soft heap limit is set to zero.
  4855. ** <li> Memory accounting is disabled using a combination of the
  4856. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4857. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4858. ** <li> An alternative page cache implementation is specified using
  4859. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  4860. ** <li> The page cache allocates from its own memory pool supplied
  4861. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4862. ** from the heap.
  4863. ** </ul>)^
  4864. **
  4865. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4866. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  4867. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  4868. ** the soft heap limit is enforced on every memory allocation. Without
  4869. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  4870. ** when memory is allocated by the page cache. Testing suggests that because
  4871. ** the page cache is the predominate memory user in SQLite, most
  4872. ** applications will achieve adequate soft heap limit enforcement without
  4873. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4874. **
  4875. ** The circumstances under which SQLite will enforce the soft heap limit may
  4876. ** changes in future releases of SQLite.
  4877. */
  4878. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  4879. /*
  4880. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  4881. ** DEPRECATED
  4882. **
  4883. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  4884. ** interface. This routine is provided for historical compatibility
  4885. ** only. All new applications should use the
  4886. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  4887. */
  4888. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  4889. /*
  4890. ** CAPI3REF: Extract Metadata About A Column Of A Table
  4891. **
  4892. ** ^This routine returns metadata about a specific column of a specific
  4893. ** database table accessible using the [database connection] handle
  4894. ** passed as the first function argument.
  4895. **
  4896. ** ^The column is identified by the second, third and fourth parameters to
  4897. ** this function. ^The second parameter is either the name of the database
  4898. ** (i.e. "main", "temp", or an attached database) containing the specified
  4899. ** table or NULL. ^If it is NULL, then all attached databases are searched
  4900. ** for the table using the same algorithm used by the database engine to
  4901. ** resolve unqualified table references.
  4902. **
  4903. ** ^The third and fourth parameters to this function are the table and column
  4904. ** name of the desired column, respectively. Neither of these parameters
  4905. ** may be NULL.
  4906. **
  4907. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  4908. ** and subsequent parameters to this function. ^Any of these arguments may be
  4909. ** NULL, in which case the corresponding element of metadata is omitted.
  4910. **
  4911. ** ^(<blockquote>
  4912. ** <table border="1">
  4913. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4914. **
  4915. ** <tr><td> 5th <td> const char* <td> Data type
  4916. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4917. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4918. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4919. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4920. ** </table>
  4921. ** </blockquote>)^
  4922. **
  4923. ** ^The memory pointed to by the character pointers returned for the
  4924. ** declaration type and collation sequence is valid only until the next
  4925. ** call to any SQLite API function.
  4926. **
  4927. ** ^If the specified table is actually a view, an [error code] is returned.
  4928. **
  4929. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  4930. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4931. ** parameters are set for the explicitly declared column. ^(If there is no
  4932. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4933. ** parameters are set as follows:
  4934. **
  4935. ** <pre>
  4936. ** data type: "INTEGER"
  4937. ** collation sequence: "BINARY"
  4938. ** not null: 0
  4939. ** primary key: 1
  4940. ** auto increment: 0
  4941. ** </pre>)^
  4942. **
  4943. ** ^(This function may load one or more schemas from database files. If an
  4944. ** error occurs during this process, or if the requested table or column
  4945. ** cannot be found, an [error code] is returned and an error message left
  4946. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  4947. **
  4948. ** ^This API is only available if the library was compiled with the
  4949. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  4950. */
  4951. SQLITE_API int sqlite3_table_column_metadata(
  4952. sqlite3 *db, /* Connection handle */
  4953. const char *zDbName, /* Database name or NULL */
  4954. const char *zTableName, /* Table name */
  4955. const char *zColumnName, /* Column name */
  4956. char const **pzDataType, /* OUTPUT: Declared data type */
  4957. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  4958. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  4959. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  4960. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  4961. );
  4962. /*
  4963. ** CAPI3REF: Load An Extension
  4964. **
  4965. ** ^This interface loads an SQLite extension library from the named file.
  4966. **
  4967. ** ^The sqlite3_load_extension() interface attempts to load an
  4968. ** [SQLite extension] library contained in the file zFile. If
  4969. ** the file cannot be loaded directly, attempts are made to load
  4970. ** with various operating-system specific extensions added.
  4971. ** So for example, if "samplelib" cannot be loaded, then names like
  4972. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  4973. ** be tried also.
  4974. **
  4975. ** ^The entry point is zProc.
  4976. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  4977. ** entry point name on its own. It first tries "sqlite3_extension_init".
  4978. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  4979. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  4980. ** characters in the filename from the last "/" to the first following
  4981. ** "." and omitting any initial "lib".)^
  4982. ** ^The sqlite3_load_extension() interface returns
  4983. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  4984. ** ^If an error occurs and pzErrMsg is not 0, then the
  4985. ** [sqlite3_load_extension()] interface shall attempt to
  4986. ** fill *pzErrMsg with error message text stored in memory
  4987. ** obtained from [sqlite3_malloc()]. The calling function
  4988. ** should free this memory by calling [sqlite3_free()].
  4989. **
  4990. ** ^Extension loading must be enabled using
  4991. ** [sqlite3_enable_load_extension()] prior to calling this API,
  4992. ** otherwise an error will be returned.
  4993. **
  4994. ** See also the [load_extension() SQL function].
  4995. */
  4996. SQLITE_API int sqlite3_load_extension(
  4997. sqlite3 *db, /* Load the extension into this database connection */
  4998. const char *zFile, /* Name of the shared library containing extension */
  4999. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5000. char **pzErrMsg /* Put error message here if not 0 */
  5001. );
  5002. /*
  5003. ** CAPI3REF: Enable Or Disable Extension Loading
  5004. **
  5005. ** ^So as not to open security holes in older applications that are
  5006. ** unprepared to deal with [extension loading], and as a means of disabling
  5007. ** [extension loading] while evaluating user-entered SQL, the following API
  5008. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5009. **
  5010. ** ^Extension loading is off by default.
  5011. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5012. ** to turn extension loading on and call it with onoff==0 to turn
  5013. ** it back off again.
  5014. */
  5015. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5016. /*
  5017. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5018. **
  5019. ** ^This interface causes the xEntryPoint() function to be invoked for
  5020. ** each new [database connection] that is created. The idea here is that
  5021. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5022. ** that is to be automatically loaded into all new database connections.
  5023. **
  5024. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5025. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5026. ** arguments and expects and integer result as if the signature of the
  5027. ** entry point where as follows:
  5028. **
  5029. ** <blockquote><pre>
  5030. ** &nbsp; int xEntryPoint(
  5031. ** &nbsp; sqlite3 *db,
  5032. ** &nbsp; const char **pzErrMsg,
  5033. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5034. ** &nbsp; );
  5035. ** </pre></blockquote>)^
  5036. **
  5037. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5038. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5039. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5040. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5041. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5042. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5043. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5044. **
  5045. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5046. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5047. ** will be called more than once for each database connection that is opened.
  5048. **
  5049. ** See also: [sqlite3_reset_auto_extension()]
  5050. ** and [sqlite3_cancel_auto_extension()]
  5051. */
  5052. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5053. /*
  5054. ** CAPI3REF: Cancel Automatic Extension Loading
  5055. **
  5056. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5057. ** initialization routine X that was registered using a prior call to
  5058. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5059. ** routine returns 1 if initialization routine X was successfully
  5060. ** unregistered and it returns 0 if X was not on the list of initialization
  5061. ** routines.
  5062. */
  5063. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5064. /*
  5065. ** CAPI3REF: Reset Automatic Extension Loading
  5066. **
  5067. ** ^This interface disables all automatic extensions previously
  5068. ** registered using [sqlite3_auto_extension()].
  5069. */
  5070. SQLITE_API void sqlite3_reset_auto_extension(void);
  5071. /*
  5072. ** The interface to the virtual-table mechanism is currently considered
  5073. ** to be experimental. The interface might change in incompatible ways.
  5074. ** If this is a problem for you, do not use the interface at this time.
  5075. **
  5076. ** When the virtual-table mechanism stabilizes, we will declare the
  5077. ** interface fixed, support it indefinitely, and remove this comment.
  5078. */
  5079. /*
  5080. ** Structures used by the virtual table interface
  5081. */
  5082. typedef struct sqlite3_vtab sqlite3_vtab;
  5083. typedef struct sqlite3_index_info sqlite3_index_info;
  5084. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5085. typedef struct sqlite3_module sqlite3_module;
  5086. /*
  5087. ** CAPI3REF: Virtual Table Object
  5088. ** KEYWORDS: sqlite3_module {virtual table module}
  5089. **
  5090. ** This structure, sometimes called a "virtual table module",
  5091. ** defines the implementation of a [virtual tables].
  5092. ** This structure consists mostly of methods for the module.
  5093. **
  5094. ** ^A virtual table module is created by filling in a persistent
  5095. ** instance of this structure and passing a pointer to that instance
  5096. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5097. ** ^The registration remains valid until it is replaced by a different
  5098. ** module or until the [database connection] closes. The content
  5099. ** of this structure must not change while it is registered with
  5100. ** any database connection.
  5101. */
  5102. struct sqlite3_module {
  5103. int iVersion;
  5104. int (*xCreate)(sqlite3*, void *pAux,
  5105. int argc, const char *const*argv,
  5106. sqlite3_vtab **ppVTab, char**);
  5107. int (*xConnect)(sqlite3*, void *pAux,
  5108. int argc, const char *const*argv,
  5109. sqlite3_vtab **ppVTab, char**);
  5110. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5111. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5112. int (*xDestroy)(sqlite3_vtab *pVTab);
  5113. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5114. int (*xClose)(sqlite3_vtab_cursor*);
  5115. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5116. int argc, sqlite3_value **argv);
  5117. int (*xNext)(sqlite3_vtab_cursor*);
  5118. int (*xEof)(sqlite3_vtab_cursor*);
  5119. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5120. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5121. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5122. int (*xBegin)(sqlite3_vtab *pVTab);
  5123. int (*xSync)(sqlite3_vtab *pVTab);
  5124. int (*xCommit)(sqlite3_vtab *pVTab);
  5125. int (*xRollback)(sqlite3_vtab *pVTab);
  5126. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5127. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5128. void **ppArg);
  5129. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5130. /* The methods above are in version 1 of the sqlite_module object. Those
  5131. ** below are for version 2 and greater. */
  5132. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5133. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5134. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5135. };
  5136. /*
  5137. ** CAPI3REF: Virtual Table Indexing Information
  5138. ** KEYWORDS: sqlite3_index_info
  5139. **
  5140. ** The sqlite3_index_info structure and its substructures is used as part
  5141. ** of the [virtual table] interface to
  5142. ** pass information into and receive the reply from the [xBestIndex]
  5143. ** method of a [virtual table module]. The fields under **Inputs** are the
  5144. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5145. ** results into the **Outputs** fields.
  5146. **
  5147. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5148. **
  5149. ** <blockquote>column OP expr</blockquote>
  5150. **
  5151. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5152. ** stored in aConstraint[].op using one of the
  5153. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5154. ** ^(The index of the column is stored in
  5155. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5156. ** expr on the right-hand side can be evaluated (and thus the constraint
  5157. ** is usable) and false if it cannot.)^
  5158. **
  5159. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5160. ** and makes other simplifications to the WHERE clause in an attempt to
  5161. ** get as many WHERE clause terms into the form shown above as possible.
  5162. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5163. ** relevant to the particular virtual table being queried.
  5164. **
  5165. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5166. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5167. **
  5168. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5169. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5170. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5171. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5172. ** is true, then the constraint is assumed to be fully handled by the
  5173. ** virtual table and is not checked again by SQLite.)^
  5174. **
  5175. ** ^The idxNum and idxPtr values are recorded and passed into the
  5176. ** [xFilter] method.
  5177. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5178. ** needToFreeIdxPtr is true.
  5179. **
  5180. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5181. ** the correct order to satisfy the ORDER BY clause so that no separate
  5182. ** sorting step is required.
  5183. **
  5184. ** ^The estimatedCost value is an estimate of the cost of doing the
  5185. ** particular lookup. A full scan of a table with N entries should have
  5186. ** a cost of N. A binary search of a table of N entries should have a
  5187. ** cost of approximately log(N).
  5188. */
  5189. struct sqlite3_index_info {
  5190. /* Inputs */
  5191. int nConstraint; /* Number of entries in aConstraint */
  5192. struct sqlite3_index_constraint {
  5193. int iColumn; /* Column on left-hand side of constraint */
  5194. unsigned char op; /* Constraint operator */
  5195. unsigned char usable; /* True if this constraint is usable */
  5196. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5197. } *aConstraint; /* Table of WHERE clause constraints */
  5198. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5199. struct sqlite3_index_orderby {
  5200. int iColumn; /* Column number */
  5201. unsigned char desc; /* True for DESC. False for ASC. */
  5202. } *aOrderBy; /* The ORDER BY clause */
  5203. /* Outputs */
  5204. struct sqlite3_index_constraint_usage {
  5205. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5206. unsigned char omit; /* Do not code a test for this constraint */
  5207. } *aConstraintUsage;
  5208. int idxNum; /* Number used to identify the index */
  5209. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5210. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5211. int orderByConsumed; /* True if output is already ordered */
  5212. double estimatedCost; /* Estimated cost of using this index */
  5213. };
  5214. /*
  5215. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5216. **
  5217. ** These macros defined the allowed values for the
  5218. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5219. ** an operator that is part of a constraint term in the wHERE clause of
  5220. ** a query that uses a [virtual table].
  5221. */
  5222. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5223. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5224. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5225. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5226. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5227. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5228. /*
  5229. ** CAPI3REF: Register A Virtual Table Implementation
  5230. **
  5231. ** ^These routines are used to register a new [virtual table module] name.
  5232. ** ^Module names must be registered before
  5233. ** creating a new [virtual table] using the module and before using a
  5234. ** preexisting [virtual table] for the module.
  5235. **
  5236. ** ^The module name is registered on the [database connection] specified
  5237. ** by the first parameter. ^The name of the module is given by the
  5238. ** second parameter. ^The third parameter is a pointer to
  5239. ** the implementation of the [virtual table module]. ^The fourth
  5240. ** parameter is an arbitrary client data pointer that is passed through
  5241. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5242. ** when a new virtual table is be being created or reinitialized.
  5243. **
  5244. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5245. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5246. ** invoke the destructor function (if it is not NULL) when SQLite
  5247. ** no longer needs the pClientData pointer. ^The destructor will also
  5248. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5249. ** ^The sqlite3_create_module()
  5250. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5251. ** destructor.
  5252. */
  5253. SQLITE_API int sqlite3_create_module(
  5254. sqlite3 *db, /* SQLite connection to register module with */
  5255. const char *zName, /* Name of the module */
  5256. const sqlite3_module *p, /* Methods for the module */
  5257. void *pClientData /* Client data for xCreate/xConnect */
  5258. );
  5259. SQLITE_API int sqlite3_create_module_v2(
  5260. sqlite3 *db, /* SQLite connection to register module with */
  5261. const char *zName, /* Name of the module */
  5262. const sqlite3_module *p, /* Methods for the module */
  5263. void *pClientData, /* Client data for xCreate/xConnect */
  5264. void(*xDestroy)(void*) /* Module destructor function */
  5265. );
  5266. /*
  5267. ** CAPI3REF: Virtual Table Instance Object
  5268. ** KEYWORDS: sqlite3_vtab
  5269. **
  5270. ** Every [virtual table module] implementation uses a subclass
  5271. ** of this object to describe a particular instance
  5272. ** of the [virtual table]. Each subclass will
  5273. ** be tailored to the specific needs of the module implementation.
  5274. ** The purpose of this superclass is to define certain fields that are
  5275. ** common to all module implementations.
  5276. **
  5277. ** ^Virtual tables methods can set an error message by assigning a
  5278. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5279. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5280. ** prior to assigning a new string to zErrMsg. ^After the error message
  5281. ** is delivered up to the client application, the string will be automatically
  5282. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5283. */
  5284. struct sqlite3_vtab {
  5285. const sqlite3_module *pModule; /* The module for this virtual table */
  5286. int nRef; /* NO LONGER USED */
  5287. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5288. /* Virtual table implementations will typically add additional fields */
  5289. };
  5290. /*
  5291. ** CAPI3REF: Virtual Table Cursor Object
  5292. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5293. **
  5294. ** Every [virtual table module] implementation uses a subclass of the
  5295. ** following structure to describe cursors that point into the
  5296. ** [virtual table] and are used
  5297. ** to loop through the virtual table. Cursors are created using the
  5298. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5299. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5300. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5301. ** of the module. Each module implementation will define
  5302. ** the content of a cursor structure to suit its own needs.
  5303. **
  5304. ** This superclass exists in order to define fields of the cursor that
  5305. ** are common to all implementations.
  5306. */
  5307. struct sqlite3_vtab_cursor {
  5308. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5309. /* Virtual table implementations will typically add additional fields */
  5310. };
  5311. /*
  5312. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5313. **
  5314. ** ^The [xCreate] and [xConnect] methods of a
  5315. ** [virtual table module] call this interface
  5316. ** to declare the format (the names and datatypes of the columns) of
  5317. ** the virtual tables they implement.
  5318. */
  5319. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5320. /*
  5321. ** CAPI3REF: Overload A Function For A Virtual Table
  5322. **
  5323. ** ^(Virtual tables can provide alternative implementations of functions
  5324. ** using the [xFindFunction] method of the [virtual table module].
  5325. ** But global versions of those functions
  5326. ** must exist in order to be overloaded.)^
  5327. **
  5328. ** ^(This API makes sure a global version of a function with a particular
  5329. ** name and number of parameters exists. If no such function exists
  5330. ** before this API is called, a new function is created.)^ ^The implementation
  5331. ** of the new function always causes an exception to be thrown. So
  5332. ** the new function is not good for anything by itself. Its only
  5333. ** purpose is to be a placeholder function that can be overloaded
  5334. ** by a [virtual table].
  5335. */
  5336. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5337. /*
  5338. ** The interface to the virtual-table mechanism defined above (back up
  5339. ** to a comment remarkably similar to this one) is currently considered
  5340. ** to be experimental. The interface might change in incompatible ways.
  5341. ** If this is a problem for you, do not use the interface at this time.
  5342. **
  5343. ** When the virtual-table mechanism stabilizes, we will declare the
  5344. ** interface fixed, support it indefinitely, and remove this comment.
  5345. */
  5346. /*
  5347. ** CAPI3REF: A Handle To An Open BLOB
  5348. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5349. **
  5350. ** An instance of this object represents an open BLOB on which
  5351. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5352. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5353. ** and destroyed by [sqlite3_blob_close()].
  5354. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5355. ** can be used to read or write small subsections of the BLOB.
  5356. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5357. */
  5358. typedef struct sqlite3_blob sqlite3_blob;
  5359. /*
  5360. ** CAPI3REF: Open A BLOB For Incremental I/O
  5361. **
  5362. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5363. ** in row iRow, column zColumn, table zTable in database zDb;
  5364. ** in other words, the same BLOB that would be selected by:
  5365. **
  5366. ** <pre>
  5367. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5368. ** </pre>)^
  5369. **
  5370. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5371. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5372. ** ^It is not possible to open a column that is part of an index or primary
  5373. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5374. ** not possible to open a column that is part of a [child key] for writing.
  5375. **
  5376. ** ^Note that the database name is not the filename that contains
  5377. ** the database but rather the symbolic name of the database that
  5378. ** appears after the AS keyword when the database is connected using [ATTACH].
  5379. ** ^For the main database file, the database name is "main".
  5380. ** ^For TEMP tables, the database name is "temp".
  5381. **
  5382. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5383. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5384. ** to be a null pointer.)^
  5385. ** ^This function sets the [database connection] error code and message
  5386. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5387. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5388. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5389. ** regardless of the success or failure of this routine.
  5390. **
  5391. ** ^(If the row that a BLOB handle points to is modified by an
  5392. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5393. ** then the BLOB handle is marked as "expired".
  5394. ** This is true if any column of the row is changed, even a column
  5395. ** other than the one the BLOB handle is open on.)^
  5396. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5397. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5398. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5399. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5400. ** commit if the transaction continues to completion.)^
  5401. **
  5402. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5403. ** the opened blob. ^The size of a blob may not be changed by this
  5404. ** interface. Use the [UPDATE] SQL command to change the size of a
  5405. ** blob.
  5406. **
  5407. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5408. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5409. ** to create an empty, zero-filled blob in which to read or write using
  5410. ** this interface.
  5411. **
  5412. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5413. ** be released by a call to [sqlite3_blob_close()].
  5414. */
  5415. SQLITE_API int sqlite3_blob_open(
  5416. sqlite3*,
  5417. const char *zDb,
  5418. const char *zTable,
  5419. const char *zColumn,
  5420. sqlite3_int64 iRow,
  5421. int flags,
  5422. sqlite3_blob **ppBlob
  5423. );
  5424. /*
  5425. ** CAPI3REF: Move a BLOB Handle to a New Row
  5426. **
  5427. ** ^This function is used to move an existing blob handle so that it points
  5428. ** to a different row of the same database table. ^The new row is identified
  5429. ** by the rowid value passed as the second argument. Only the row can be
  5430. ** changed. ^The database, table and column on which the blob handle is open
  5431. ** remain the same. Moving an existing blob handle to a new row can be
  5432. ** faster than closing the existing handle and opening a new one.
  5433. **
  5434. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5435. ** it must exist and there must be either a blob or text value stored in
  5436. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5437. ** it does not contain a blob or text value, or if another error occurs, an
  5438. ** SQLite error code is returned and the blob handle is considered aborted.
  5439. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5440. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5441. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5442. ** always returns zero.
  5443. **
  5444. ** ^This function sets the database handle error code and message.
  5445. */
  5446. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5447. /*
  5448. ** CAPI3REF: Close A BLOB Handle
  5449. **
  5450. ** ^Closes an open [BLOB handle].
  5451. **
  5452. ** ^Closing a BLOB shall cause the current transaction to commit
  5453. ** if there are no other BLOBs, no pending prepared statements, and the
  5454. ** database connection is in [autocommit mode].
  5455. ** ^If any writes were made to the BLOB, they might be held in cache
  5456. ** until the close operation if they will fit.
  5457. **
  5458. ** ^(Closing the BLOB often forces the changes
  5459. ** out to disk and so if any I/O errors occur, they will likely occur
  5460. ** at the time when the BLOB is closed. Any errors that occur during
  5461. ** closing are reported as a non-zero return value.)^
  5462. **
  5463. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5464. ** an error code, the BLOB is still closed.)^
  5465. **
  5466. ** ^Calling this routine with a null pointer (such as would be returned
  5467. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5468. */
  5469. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5470. /*
  5471. ** CAPI3REF: Return The Size Of An Open BLOB
  5472. **
  5473. ** ^Returns the size in bytes of the BLOB accessible via the
  5474. ** successfully opened [BLOB handle] in its only argument. ^The
  5475. ** incremental blob I/O routines can only read or overwriting existing
  5476. ** blob content; they cannot change the size of a blob.
  5477. **
  5478. ** This routine only works on a [BLOB handle] which has been created
  5479. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5480. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5481. ** to this routine results in undefined and probably undesirable behavior.
  5482. */
  5483. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5484. /*
  5485. ** CAPI3REF: Read Data From A BLOB Incrementally
  5486. **
  5487. ** ^(This function is used to read data from an open [BLOB handle] into a
  5488. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5489. ** from the open BLOB, starting at offset iOffset.)^
  5490. **
  5491. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5492. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5493. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5494. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5495. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5496. **
  5497. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5498. ** error code of [SQLITE_ABORT].
  5499. **
  5500. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5501. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5502. **
  5503. ** This routine only works on a [BLOB handle] which has been created
  5504. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5505. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5506. ** to this routine results in undefined and probably undesirable behavior.
  5507. **
  5508. ** See also: [sqlite3_blob_write()].
  5509. */
  5510. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5511. /*
  5512. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5513. **
  5514. ** ^This function is used to write data into an open [BLOB handle] from a
  5515. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5516. ** into the open BLOB, starting at offset iOffset.
  5517. **
  5518. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5519. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5520. ** this function returns [SQLITE_READONLY].
  5521. **
  5522. ** ^This function may only modify the contents of the BLOB; it is
  5523. ** not possible to increase the size of a BLOB using this API.
  5524. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5525. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5526. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5527. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5528. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5529. **
  5530. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5531. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5532. ** before the [BLOB handle] expired are not rolled back by the
  5533. ** expiration of the handle, though of course those changes might
  5534. ** have been overwritten by the statement that expired the BLOB handle
  5535. ** or by other independent statements.
  5536. **
  5537. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5538. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5539. **
  5540. ** This routine only works on a [BLOB handle] which has been created
  5541. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5542. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5543. ** to this routine results in undefined and probably undesirable behavior.
  5544. **
  5545. ** See also: [sqlite3_blob_read()].
  5546. */
  5547. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5548. /*
  5549. ** CAPI3REF: Virtual File System Objects
  5550. **
  5551. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5552. ** that SQLite uses to interact
  5553. ** with the underlying operating system. Most SQLite builds come with a
  5554. ** single default VFS that is appropriate for the host computer.
  5555. ** New VFSes can be registered and existing VFSes can be unregistered.
  5556. ** The following interfaces are provided.
  5557. **
  5558. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5559. ** ^Names are case sensitive.
  5560. ** ^Names are zero-terminated UTF-8 strings.
  5561. ** ^If there is no match, a NULL pointer is returned.
  5562. ** ^If zVfsName is NULL then the default VFS is returned.
  5563. **
  5564. ** ^New VFSes are registered with sqlite3_vfs_register().
  5565. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5566. ** ^The same VFS can be registered multiple times without injury.
  5567. ** ^To make an existing VFS into the default VFS, register it again
  5568. ** with the makeDflt flag set. If two different VFSes with the
  5569. ** same name are registered, the behavior is undefined. If a
  5570. ** VFS is registered with a name that is NULL or an empty string,
  5571. ** then the behavior is undefined.
  5572. **
  5573. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5574. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5575. ** the default. The choice for the new VFS is arbitrary.)^
  5576. */
  5577. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5578. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5579. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5580. /*
  5581. ** CAPI3REF: Mutexes
  5582. **
  5583. ** The SQLite core uses these routines for thread
  5584. ** synchronization. Though they are intended for internal
  5585. ** use by SQLite, code that links against SQLite is
  5586. ** permitted to use any of these routines.
  5587. **
  5588. ** The SQLite source code contains multiple implementations
  5589. ** of these mutex routines. An appropriate implementation
  5590. ** is selected automatically at compile-time. ^(The following
  5591. ** implementations are available in the SQLite core:
  5592. **
  5593. ** <ul>
  5594. ** <li> SQLITE_MUTEX_PTHREADS
  5595. ** <li> SQLITE_MUTEX_W32
  5596. ** <li> SQLITE_MUTEX_NOOP
  5597. ** </ul>)^
  5598. **
  5599. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5600. ** that does no real locking and is appropriate for use in
  5601. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5602. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5603. ** and Windows.
  5604. **
  5605. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5606. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5607. ** implementation is included with the library. In this case the
  5608. ** application must supply a custom mutex implementation using the
  5609. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5610. ** before calling sqlite3_initialize() or any other public sqlite3_
  5611. ** function that calls sqlite3_initialize().)^
  5612. **
  5613. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5614. ** mutex and returns a pointer to it. ^If it returns NULL
  5615. ** that means that a mutex could not be allocated. ^SQLite
  5616. ** will unwind its stack and return an error. ^(The argument
  5617. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5618. **
  5619. ** <ul>
  5620. ** <li> SQLITE_MUTEX_FAST
  5621. ** <li> SQLITE_MUTEX_RECURSIVE
  5622. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5623. ** <li> SQLITE_MUTEX_STATIC_MEM
  5624. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5625. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5626. ** <li> SQLITE_MUTEX_STATIC_LRU
  5627. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5628. ** </ul>)^
  5629. **
  5630. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5631. ** cause sqlite3_mutex_alloc() to create
  5632. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5633. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5634. ** The mutex implementation does not need to make a distinction
  5635. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5636. ** not want to. ^SQLite will only request a recursive mutex in
  5637. ** cases where it really needs one. ^If a faster non-recursive mutex
  5638. ** implementation is available on the host platform, the mutex subsystem
  5639. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5640. **
  5641. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5642. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5643. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5644. ** used by the current version of SQLite. Future versions of SQLite
  5645. ** may add additional static mutexes. Static mutexes are for internal
  5646. ** use by SQLite only. Applications that use SQLite mutexes should
  5647. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5648. ** SQLITE_MUTEX_RECURSIVE.
  5649. **
  5650. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5651. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5652. ** returns a different mutex on every call. ^But for the static
  5653. ** mutex types, the same mutex is returned on every call that has
  5654. ** the same type number.
  5655. **
  5656. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5657. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5658. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5659. ** use when they are deallocated. Attempting to deallocate a static
  5660. ** mutex results in undefined behavior. ^SQLite never deallocates
  5661. ** a static mutex.
  5662. **
  5663. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5664. ** to enter a mutex. ^If another thread is already within the mutex,
  5665. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5666. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5667. ** upon successful entry. ^(Mutexes created using
  5668. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5669. ** In such cases the,
  5670. ** mutex must be exited an equal number of times before another thread
  5671. ** can enter.)^ ^(If the same thread tries to enter any other
  5672. ** kind of mutex more than once, the behavior is undefined.
  5673. ** SQLite will never exhibit
  5674. ** such behavior in its own use of mutexes.)^
  5675. **
  5676. ** ^(Some systems (for example, Windows 95) do not support the operation
  5677. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5678. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5679. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5680. **
  5681. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5682. ** previously entered by the same thread. ^(The behavior
  5683. ** is undefined if the mutex is not currently entered by the
  5684. ** calling thread or is not currently allocated. SQLite will
  5685. ** never do either.)^
  5686. **
  5687. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5688. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5689. ** behave as no-ops.
  5690. **
  5691. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5692. */
  5693. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5694. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5695. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5696. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5697. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5698. /*
  5699. ** CAPI3REF: Mutex Methods Object
  5700. **
  5701. ** An instance of this structure defines the low-level routines
  5702. ** used to allocate and use mutexes.
  5703. **
  5704. ** Usually, the default mutex implementations provided by SQLite are
  5705. ** sufficient, however the user has the option of substituting a custom
  5706. ** implementation for specialized deployments or systems for which SQLite
  5707. ** does not provide a suitable implementation. In this case, the user
  5708. ** creates and populates an instance of this structure to pass
  5709. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5710. ** Additionally, an instance of this structure can be used as an
  5711. ** output variable when querying the system for the current mutex
  5712. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5713. **
  5714. ** ^The xMutexInit method defined by this structure is invoked as
  5715. ** part of system initialization by the sqlite3_initialize() function.
  5716. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5717. ** effective call to [sqlite3_initialize()].
  5718. **
  5719. ** ^The xMutexEnd method defined by this structure is invoked as
  5720. ** part of system shutdown by the sqlite3_shutdown() function. The
  5721. ** implementation of this method is expected to release all outstanding
  5722. ** resources obtained by the mutex methods implementation, especially
  5723. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5724. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5725. **
  5726. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5727. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5728. ** xMutexNotheld) implement the following interfaces (respectively):
  5729. **
  5730. ** <ul>
  5731. ** <li> [sqlite3_mutex_alloc()] </li>
  5732. ** <li> [sqlite3_mutex_free()] </li>
  5733. ** <li> [sqlite3_mutex_enter()] </li>
  5734. ** <li> [sqlite3_mutex_try()] </li>
  5735. ** <li> [sqlite3_mutex_leave()] </li>
  5736. ** <li> [sqlite3_mutex_held()] </li>
  5737. ** <li> [sqlite3_mutex_notheld()] </li>
  5738. ** </ul>)^
  5739. **
  5740. ** The only difference is that the public sqlite3_XXX functions enumerated
  5741. ** above silently ignore any invocations that pass a NULL pointer instead
  5742. ** of a valid mutex handle. The implementations of the methods defined
  5743. ** by this structure are not required to handle this case, the results
  5744. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5745. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5746. ** it is passed a NULL pointer).
  5747. **
  5748. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5749. ** invoke xMutexInit() multiple times within the same process and without
  5750. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5751. ** xMutexInit() must be no-ops.
  5752. **
  5753. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5754. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5755. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5756. ** memory allocation for a fast or recursive mutex.
  5757. **
  5758. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5759. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5760. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5761. ** prior to returning.
  5762. */
  5763. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5764. struct sqlite3_mutex_methods {
  5765. int (*xMutexInit)(void);
  5766. int (*xMutexEnd)(void);
  5767. sqlite3_mutex *(*xMutexAlloc)(int);
  5768. void (*xMutexFree)(sqlite3_mutex *);
  5769. void (*xMutexEnter)(sqlite3_mutex *);
  5770. int (*xMutexTry)(sqlite3_mutex *);
  5771. void (*xMutexLeave)(sqlite3_mutex *);
  5772. int (*xMutexHeld)(sqlite3_mutex *);
  5773. int (*xMutexNotheld)(sqlite3_mutex *);
  5774. };
  5775. /*
  5776. ** CAPI3REF: Mutex Verification Routines
  5777. **
  5778. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5779. ** are intended for use inside assert() statements. ^The SQLite core
  5780. ** never uses these routines except inside an assert() and applications
  5781. ** are advised to follow the lead of the core. ^The SQLite core only
  5782. ** provides implementations for these routines when it is compiled
  5783. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5784. ** are only required to provide these routines if SQLITE_DEBUG is
  5785. ** defined and if NDEBUG is not defined.
  5786. **
  5787. ** ^These routines should return true if the mutex in their argument
  5788. ** is held or not held, respectively, by the calling thread.
  5789. **
  5790. ** ^The implementation is not required to provide versions of these
  5791. ** routines that actually work. If the implementation does not provide working
  5792. ** versions of these routines, it should at least provide stubs that always
  5793. ** return true so that one does not get spurious assertion failures.
  5794. **
  5795. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5796. ** the routine should return 1. This seems counter-intuitive since
  5797. ** clearly the mutex cannot be held if it does not exist. But
  5798. ** the reason the mutex does not exist is because the build is not
  5799. ** using mutexes. And we do not want the assert() containing the
  5800. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5801. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5802. ** interface should also return 1 when given a NULL pointer.
  5803. */
  5804. #ifndef NDEBUG
  5805. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5806. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5807. #endif
  5808. /*
  5809. ** CAPI3REF: Mutex Types
  5810. **
  5811. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5812. ** which is one of these integer constants.
  5813. **
  5814. ** The set of static mutexes may change from one SQLite release to the
  5815. ** next. Applications that override the built-in mutex logic must be
  5816. ** prepared to accommodate additional static mutexes.
  5817. */
  5818. #define SQLITE_MUTEX_FAST 0
  5819. #define SQLITE_MUTEX_RECURSIVE 1
  5820. #define SQLITE_MUTEX_STATIC_MASTER 2
  5821. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5822. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5823. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5824. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5825. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5826. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  5827. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  5828. /*
  5829. ** CAPI3REF: Retrieve the mutex for a database connection
  5830. **
  5831. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  5832. ** serializes access to the [database connection] given in the argument
  5833. ** when the [threading mode] is Serialized.
  5834. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  5835. ** routine returns a NULL pointer.
  5836. */
  5837. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5838. /*
  5839. ** CAPI3REF: Low-Level Control Of Database Files
  5840. **
  5841. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  5842. ** xFileControl method for the [sqlite3_io_methods] object associated
  5843. ** with a particular database identified by the second argument. ^The
  5844. ** name of the database is "main" for the main database or "temp" for the
  5845. ** TEMP database, or the name that appears after the AS keyword for
  5846. ** databases that are added using the [ATTACH] SQL command.
  5847. ** ^A NULL pointer can be used in place of "main" to refer to the
  5848. ** main database file.
  5849. ** ^The third and fourth parameters to this routine
  5850. ** are passed directly through to the second and third parameters of
  5851. ** the xFileControl method. ^The return value of the xFileControl
  5852. ** method becomes the return value of this routine.
  5853. **
  5854. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  5855. ** a pointer to the underlying [sqlite3_file] object to be written into
  5856. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  5857. ** case is a short-circuit path which does not actually invoke the
  5858. ** underlying sqlite3_io_methods.xFileControl method.
  5859. **
  5860. ** ^If the second parameter (zDbName) does not match the name of any
  5861. ** open database file, then SQLITE_ERROR is returned. ^This error
  5862. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5863. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  5864. ** also return SQLITE_ERROR. There is no way to distinguish between
  5865. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5866. ** xFileControl method.
  5867. **
  5868. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5869. */
  5870. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5871. /*
  5872. ** CAPI3REF: Testing Interface
  5873. **
  5874. ** ^The sqlite3_test_control() interface is used to read out internal
  5875. ** state of SQLite and to inject faults into SQLite for testing
  5876. ** purposes. ^The first parameter is an operation code that determines
  5877. ** the number, meaning, and operation of all subsequent parameters.
  5878. **
  5879. ** This interface is not for use by applications. It exists solely
  5880. ** for verifying the correct operation of the SQLite library. Depending
  5881. ** on how the SQLite library is compiled, this interface might not exist.
  5882. **
  5883. ** The details of the operation codes, their meanings, the parameters
  5884. ** they take, and what they do are all subject to change without notice.
  5885. ** Unlike most of the SQLite API, this function is not guaranteed to
  5886. ** operate consistently from one release to the next.
  5887. */
  5888. SQLITE_API int sqlite3_test_control(int op, ...);
  5889. /*
  5890. ** CAPI3REF: Testing Interface Operation Codes
  5891. **
  5892. ** These constants are the valid operation code parameters used
  5893. ** as the first argument to [sqlite3_test_control()].
  5894. **
  5895. ** These parameters and their meanings are subject to change
  5896. ** without notice. These values are for testing purposes only.
  5897. ** Applications should not use any of these parameters or the
  5898. ** [sqlite3_test_control()] interface.
  5899. */
  5900. #define SQLITE_TESTCTRL_FIRST 5
  5901. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5902. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5903. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5904. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5905. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5906. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5907. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5908. #define SQLITE_TESTCTRL_ASSERT 12
  5909. #define SQLITE_TESTCTRL_ALWAYS 13
  5910. #define SQLITE_TESTCTRL_RESERVE 14
  5911. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  5912. #define SQLITE_TESTCTRL_ISKEYWORD 16
  5913. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  5914. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  5915. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  5916. #define SQLITE_TESTCTRL_LAST 19
  5917. /*
  5918. ** CAPI3REF: SQLite Runtime Status
  5919. **
  5920. ** ^This interface is used to retrieve runtime status information
  5921. ** about the performance of SQLite, and optionally to reset various
  5922. ** highwater marks. ^The first argument is an integer code for
  5923. ** the specific parameter to measure. ^(Recognized integer codes
  5924. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  5925. ** ^The current value of the parameter is returned into *pCurrent.
  5926. ** ^The highest recorded value is returned in *pHighwater. ^If the
  5927. ** resetFlag is true, then the highest record value is reset after
  5928. ** *pHighwater is written. ^(Some parameters do not record the highest
  5929. ** value. For those parameters
  5930. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  5931. ** ^(Other parameters record only the highwater mark and not the current
  5932. ** value. For these latter parameters nothing is written into *pCurrent.)^
  5933. **
  5934. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  5935. ** non-zero [error code] on failure.
  5936. **
  5937. ** This routine is threadsafe but is not atomic. This routine can be
  5938. ** called while other threads are running the same or different SQLite
  5939. ** interfaces. However the values returned in *pCurrent and
  5940. ** *pHighwater reflect the status of SQLite at different points in time
  5941. ** and it is possible that another thread might change the parameter
  5942. ** in between the times when *pCurrent and *pHighwater are written.
  5943. **
  5944. ** See also: [sqlite3_db_status()]
  5945. */
  5946. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5947. /*
  5948. ** CAPI3REF: Status Parameters
  5949. ** KEYWORDS: {status parameters}
  5950. **
  5951. ** These integer constants designate various run-time status parameters
  5952. ** that can be returned by [sqlite3_status()].
  5953. **
  5954. ** <dl>
  5955. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  5956. ** <dd>This parameter is the current amount of memory checked out
  5957. ** using [sqlite3_malloc()], either directly or indirectly. The
  5958. ** figure includes calls made to [sqlite3_malloc()] by the application
  5959. ** and internal memory usage by the SQLite library. Scratch memory
  5960. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  5961. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  5962. ** this parameter. The amount returned is the sum of the allocation
  5963. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  5964. **
  5965. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  5966. ** <dd>This parameter records the largest memory allocation request
  5967. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  5968. ** internal equivalents). Only the value returned in the
  5969. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5970. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5971. **
  5972. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  5973. ** <dd>This parameter records the number of separate memory allocations
  5974. ** currently checked out.</dd>)^
  5975. **
  5976. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  5977. ** <dd>This parameter returns the number of pages used out of the
  5978. ** [pagecache memory allocator] that was configured using
  5979. ** [SQLITE_CONFIG_PAGECACHE]. The
  5980. ** value returned is in pages, not in bytes.</dd>)^
  5981. **
  5982. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  5983. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  5984. ** <dd>This parameter returns the number of bytes of page cache
  5985. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  5986. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  5987. ** returned value includes allocations that overflowed because they
  5988. ** where too large (they were larger than the "sz" parameter to
  5989. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  5990. ** no space was left in the page cache.</dd>)^
  5991. **
  5992. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  5993. ** <dd>This parameter records the largest memory allocation request
  5994. ** handed to [pagecache memory allocator]. Only the value returned in the
  5995. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5996. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5997. **
  5998. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  5999. ** <dd>This parameter returns the number of allocations used out of the
  6000. ** [scratch memory allocator] configured using
  6001. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6002. ** in bytes. Since a single thread may only have one scratch allocation
  6003. ** outstanding at time, this parameter also reports the number of threads
  6004. ** using scratch memory at the same time.</dd>)^
  6005. **
  6006. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6007. ** <dd>This parameter returns the number of bytes of scratch memory
  6008. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6009. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6010. ** returned include overflows because the requested allocation was too
  6011. ** larger (that is, because the requested allocation was larger than the
  6012. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6013. ** slots were available.
  6014. ** </dd>)^
  6015. **
  6016. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6017. ** <dd>This parameter records the largest memory allocation request
  6018. ** handed to [scratch memory allocator]. Only the value returned in the
  6019. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6020. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6021. **
  6022. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6023. ** <dd>This parameter records the deepest parser stack. It is only
  6024. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6025. ** </dl>
  6026. **
  6027. ** New status parameters may be added from time to time.
  6028. */
  6029. #define SQLITE_STATUS_MEMORY_USED 0
  6030. #define SQLITE_STATUS_PAGECACHE_USED 1
  6031. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6032. #define SQLITE_STATUS_SCRATCH_USED 3
  6033. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6034. #define SQLITE_STATUS_MALLOC_SIZE 5
  6035. #define SQLITE_STATUS_PARSER_STACK 6
  6036. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6037. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6038. #define SQLITE_STATUS_MALLOC_COUNT 9
  6039. /*
  6040. ** CAPI3REF: Database Connection Status
  6041. **
  6042. ** ^This interface is used to retrieve runtime status information
  6043. ** about a single [database connection]. ^The first argument is the
  6044. ** database connection object to be interrogated. ^The second argument
  6045. ** is an integer constant, taken from the set of
  6046. ** [SQLITE_DBSTATUS options], that
  6047. ** determines the parameter to interrogate. The set of
  6048. ** [SQLITE_DBSTATUS options] is likely
  6049. ** to grow in future releases of SQLite.
  6050. **
  6051. ** ^The current value of the requested parameter is written into *pCur
  6052. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6053. ** the resetFlg is true, then the highest instantaneous value is
  6054. ** reset back down to the current value.
  6055. **
  6056. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6057. ** non-zero [error code] on failure.
  6058. **
  6059. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6060. */
  6061. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6062. /*
  6063. ** CAPI3REF: Status Parameters for database connections
  6064. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6065. **
  6066. ** These constants are the available integer "verbs" that can be passed as
  6067. ** the second argument to the [sqlite3_db_status()] interface.
  6068. **
  6069. ** New verbs may be added in future releases of SQLite. Existing verbs
  6070. ** might be discontinued. Applications should check the return code from
  6071. ** [sqlite3_db_status()] to make sure that the call worked.
  6072. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6073. ** if a discontinued or unsupported verb is invoked.
  6074. **
  6075. ** <dl>
  6076. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6077. ** <dd>This parameter returns the number of lookaside memory slots currently
  6078. ** checked out.</dd>)^
  6079. **
  6080. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6081. ** <dd>This parameter returns the number malloc attempts that were
  6082. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6083. ** the current value is always zero.)^
  6084. **
  6085. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6086. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6087. ** <dd>This parameter returns the number malloc attempts that might have
  6088. ** been satisfied using lookaside memory but failed due to the amount of
  6089. ** memory requested being larger than the lookaside slot size.
  6090. ** Only the high-water value is meaningful;
  6091. ** the current value is always zero.)^
  6092. **
  6093. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6094. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6095. ** <dd>This parameter returns the number malloc attempts that might have
  6096. ** been satisfied using lookaside memory but failed due to all lookaside
  6097. ** memory already being in use.
  6098. ** Only the high-water value is meaningful;
  6099. ** the current value is always zero.)^
  6100. **
  6101. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6102. ** <dd>This parameter returns the approximate number of of bytes of heap
  6103. ** memory used by all pager caches associated with the database connection.)^
  6104. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6105. **
  6106. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6107. ** <dd>This parameter returns the approximate number of of bytes of heap
  6108. ** memory used to store the schema for all databases associated
  6109. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6110. ** ^The full amount of memory used by the schemas is reported, even if the
  6111. ** schema memory is shared with other database connections due to
  6112. ** [shared cache mode] being enabled.
  6113. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6114. **
  6115. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6116. ** <dd>This parameter returns the approximate number of of bytes of heap
  6117. ** and lookaside memory used by all prepared statements associated with
  6118. ** the database connection.)^
  6119. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6120. ** </dd>
  6121. **
  6122. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6123. ** <dd>This parameter returns the number of pager cache hits that have
  6124. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6125. ** is always 0.
  6126. ** </dd>
  6127. **
  6128. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6129. ** <dd>This parameter returns the number of pager cache misses that have
  6130. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6131. ** is always 0.
  6132. ** </dd>
  6133. **
  6134. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6135. ** <dd>This parameter returns the number of dirty cache entries that have
  6136. ** been written to disk. Specifically, the number of pages written to the
  6137. ** wal file in wal mode databases, or the number of pages written to the
  6138. ** database file in rollback mode databases. Any pages written as part of
  6139. ** transaction rollback or database recovery operations are not included.
  6140. ** If an IO or other error occurs while writing a page to disk, the effect
  6141. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6142. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6143. ** </dd>
  6144. **
  6145. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6146. ** <dd>This parameter returns zero for the current value if and only if
  6147. ** all foreign key constraints (deferred or immediate) have been
  6148. ** resolved.)^ ^The highwater mark is always 0.
  6149. ** </dd>
  6150. ** </dl>
  6151. */
  6152. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6153. #define SQLITE_DBSTATUS_CACHE_USED 1
  6154. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6155. #define SQLITE_DBSTATUS_STMT_USED 3
  6156. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6157. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6158. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6159. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6160. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6161. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6162. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6163. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6164. /*
  6165. ** CAPI3REF: Prepared Statement Status
  6166. **
  6167. ** ^(Each prepared statement maintains various
  6168. ** [SQLITE_STMTSTATUS counters] that measure the number
  6169. ** of times it has performed specific operations.)^ These counters can
  6170. ** be used to monitor the performance characteristics of the prepared
  6171. ** statements. For example, if the number of table steps greatly exceeds
  6172. ** the number of table searches or result rows, that would tend to indicate
  6173. ** that the prepared statement is using a full table scan rather than
  6174. ** an index.
  6175. **
  6176. ** ^(This interface is used to retrieve and reset counter values from
  6177. ** a [prepared statement]. The first argument is the prepared statement
  6178. ** object to be interrogated. The second argument
  6179. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6180. ** to be interrogated.)^
  6181. ** ^The current value of the requested counter is returned.
  6182. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6183. ** interface call returns.
  6184. **
  6185. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6186. */
  6187. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6188. /*
  6189. ** CAPI3REF: Status Parameters for prepared statements
  6190. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6191. **
  6192. ** These preprocessor macros define integer codes that name counter
  6193. ** values associated with the [sqlite3_stmt_status()] interface.
  6194. ** The meanings of the various counters are as follows:
  6195. **
  6196. ** <dl>
  6197. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6198. ** <dd>^This is the number of times that SQLite has stepped forward in
  6199. ** a table as part of a full table scan. Large numbers for this counter
  6200. ** may indicate opportunities for performance improvement through
  6201. ** careful use of indices.</dd>
  6202. **
  6203. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6204. ** <dd>^This is the number of sort operations that have occurred.
  6205. ** A non-zero value in this counter may indicate an opportunity to
  6206. ** improvement performance through careful use of indices.</dd>
  6207. **
  6208. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6209. ** <dd>^This is the number of rows inserted into transient indices that
  6210. ** were created automatically in order to help joins run faster.
  6211. ** A non-zero value in this counter may indicate an opportunity to
  6212. ** improvement performance by adding permanent indices that do not
  6213. ** need to be reinitialized each time the statement is run.</dd>
  6214. **
  6215. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6216. ** <dd>^This is the number of virtual machine operations executed
  6217. ** by the prepared statement if that number is less than or equal
  6218. ** to 2147483647. The number of virtual machine operations can be
  6219. ** used as a proxy for the total work done by the prepared statement.
  6220. ** If the number of virtual machine operations exceeds 2147483647
  6221. ** then the value returned by this statement status code is undefined.
  6222. ** </dd>
  6223. ** </dl>
  6224. */
  6225. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6226. #define SQLITE_STMTSTATUS_SORT 2
  6227. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6228. #define SQLITE_STMTSTATUS_VM_STEP 4
  6229. /*
  6230. ** CAPI3REF: Custom Page Cache Object
  6231. **
  6232. ** The sqlite3_pcache type is opaque. It is implemented by
  6233. ** the pluggable module. The SQLite core has no knowledge of
  6234. ** its size or internal structure and never deals with the
  6235. ** sqlite3_pcache object except by holding and passing pointers
  6236. ** to the object.
  6237. **
  6238. ** See [sqlite3_pcache_methods2] for additional information.
  6239. */
  6240. typedef struct sqlite3_pcache sqlite3_pcache;
  6241. /*
  6242. ** CAPI3REF: Custom Page Cache Object
  6243. **
  6244. ** The sqlite3_pcache_page object represents a single page in the
  6245. ** page cache. The page cache will allocate instances of this
  6246. ** object. Various methods of the page cache use pointers to instances
  6247. ** of this object as parameters or as their return value.
  6248. **
  6249. ** See [sqlite3_pcache_methods2] for additional information.
  6250. */
  6251. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6252. struct sqlite3_pcache_page {
  6253. void *pBuf; /* The content of the page */
  6254. void *pExtra; /* Extra information associated with the page */
  6255. };
  6256. /*
  6257. ** CAPI3REF: Application Defined Page Cache.
  6258. ** KEYWORDS: {page cache}
  6259. **
  6260. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6261. ** register an alternative page cache implementation by passing in an
  6262. ** instance of the sqlite3_pcache_methods2 structure.)^
  6263. ** In many applications, most of the heap memory allocated by
  6264. ** SQLite is used for the page cache.
  6265. ** By implementing a
  6266. ** custom page cache using this API, an application can better control
  6267. ** the amount of memory consumed by SQLite, the way in which
  6268. ** that memory is allocated and released, and the policies used to
  6269. ** determine exactly which parts of a database file are cached and for
  6270. ** how long.
  6271. **
  6272. ** The alternative page cache mechanism is an
  6273. ** extreme measure that is only needed by the most demanding applications.
  6274. ** The built-in page cache is recommended for most uses.
  6275. **
  6276. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6277. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6278. ** the application may discard the parameter after the call to
  6279. ** [sqlite3_config()] returns.)^
  6280. **
  6281. ** [[the xInit() page cache method]]
  6282. ** ^(The xInit() method is called once for each effective
  6283. ** call to [sqlite3_initialize()])^
  6284. ** (usually only once during the lifetime of the process). ^(The xInit()
  6285. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6286. ** The intent of the xInit() method is to set up global data structures
  6287. ** required by the custom page cache implementation.
  6288. ** ^(If the xInit() method is NULL, then the
  6289. ** built-in default page cache is used instead of the application defined
  6290. ** page cache.)^
  6291. **
  6292. ** [[the xShutdown() page cache method]]
  6293. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6294. ** It can be used to clean up
  6295. ** any outstanding resources before process shutdown, if required.
  6296. ** ^The xShutdown() method may be NULL.
  6297. **
  6298. ** ^SQLite automatically serializes calls to the xInit method,
  6299. ** so the xInit method need not be threadsafe. ^The
  6300. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6301. ** not need to be threadsafe either. All other methods must be threadsafe
  6302. ** in multithreaded applications.
  6303. **
  6304. ** ^SQLite will never invoke xInit() more than once without an intervening
  6305. ** call to xShutdown().
  6306. **
  6307. ** [[the xCreate() page cache methods]]
  6308. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6309. ** SQLite will typically create one cache instance for each open database file,
  6310. ** though this is not guaranteed. ^The
  6311. ** first parameter, szPage, is the size in bytes of the pages that must
  6312. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6313. ** second parameter szExtra is a number of bytes of extra storage
  6314. ** associated with each page cache entry. ^The szExtra parameter will
  6315. ** a number less than 250. SQLite will use the
  6316. ** extra szExtra bytes on each page to store metadata about the underlying
  6317. ** database page on disk. The value passed into szExtra depends
  6318. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6319. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6320. ** created will be used to cache database pages of a file stored on disk, or
  6321. ** false if it is used for an in-memory database. The cache implementation
  6322. ** does not have to do anything special based with the value of bPurgeable;
  6323. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6324. ** never invoke xUnpin() except to deliberately delete a page.
  6325. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6326. ** false will always have the "discard" flag set to true.
  6327. ** ^Hence, a cache created with bPurgeable false will
  6328. ** never contain any unpinned pages.
  6329. **
  6330. ** [[the xCachesize() page cache method]]
  6331. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6332. ** suggested maximum cache-size (number of pages stored by) the cache
  6333. ** instance passed as the first argument. This is the value configured using
  6334. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6335. ** parameter, the implementation is not required to do anything with this
  6336. ** value; it is advisory only.
  6337. **
  6338. ** [[the xPagecount() page cache methods]]
  6339. ** The xPagecount() method must return the number of pages currently
  6340. ** stored in the cache, both pinned and unpinned.
  6341. **
  6342. ** [[the xFetch() page cache methods]]
  6343. ** The xFetch() method locates a page in the cache and returns a pointer to
  6344. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6345. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6346. ** pointer to a buffer of szPage bytes used to store the content of a
  6347. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6348. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6349. ** for each entry in the page cache.
  6350. **
  6351. ** The page to be fetched is determined by the key. ^The minimum key value
  6352. ** is 1. After it has been retrieved using xFetch, the page is considered
  6353. ** to be "pinned".
  6354. **
  6355. ** If the requested page is already in the page cache, then the page cache
  6356. ** implementation must return a pointer to the page buffer with its content
  6357. ** intact. If the requested page is not already in the cache, then the
  6358. ** cache implementation should use the value of the createFlag
  6359. ** parameter to help it determined what action to take:
  6360. **
  6361. ** <table border=1 width=85% align=center>
  6362. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6363. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6364. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6365. ** Otherwise return NULL.
  6366. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6367. ** NULL if allocating a new page is effectively impossible.
  6368. ** </table>
  6369. **
  6370. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6371. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6372. ** failed.)^ In between the to xFetch() calls, SQLite may
  6373. ** attempt to unpin one or more cache pages by spilling the content of
  6374. ** pinned pages to disk and synching the operating system disk cache.
  6375. **
  6376. ** [[the xUnpin() page cache method]]
  6377. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6378. ** as its second argument. If the third parameter, discard, is non-zero,
  6379. ** then the page must be evicted from the cache.
  6380. ** ^If the discard parameter is
  6381. ** zero, then the page may be discarded or retained at the discretion of
  6382. ** page cache implementation. ^The page cache implementation
  6383. ** may choose to evict unpinned pages at any time.
  6384. **
  6385. ** The cache must not perform any reference counting. A single
  6386. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6387. ** to xFetch().
  6388. **
  6389. ** [[the xRekey() page cache methods]]
  6390. ** The xRekey() method is used to change the key value associated with the
  6391. ** page passed as the second argument. If the cache
  6392. ** previously contains an entry associated with newKey, it must be
  6393. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6394. ** to be pinned.
  6395. **
  6396. ** When SQLite calls the xTruncate() method, the cache must discard all
  6397. ** existing cache entries with page numbers (keys) greater than or equal
  6398. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6399. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6400. ** they can be safely discarded.
  6401. **
  6402. ** [[the xDestroy() page cache method]]
  6403. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6404. ** All resources associated with the specified cache should be freed. ^After
  6405. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6406. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6407. ** functions.
  6408. **
  6409. ** [[the xShrink() page cache method]]
  6410. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6411. ** free up as much of heap memory as possible. The page cache implementation
  6412. ** is not obligated to free any memory, but well-behaved implementations should
  6413. ** do their best.
  6414. */
  6415. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6416. struct sqlite3_pcache_methods2 {
  6417. int iVersion;
  6418. void *pArg;
  6419. int (*xInit)(void*);
  6420. void (*xShutdown)(void*);
  6421. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6422. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6423. int (*xPagecount)(sqlite3_pcache*);
  6424. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6425. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6426. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6427. unsigned oldKey, unsigned newKey);
  6428. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6429. void (*xDestroy)(sqlite3_pcache*);
  6430. void (*xShrink)(sqlite3_pcache*);
  6431. };
  6432. /*
  6433. ** This is the obsolete pcache_methods object that has now been replaced
  6434. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6435. ** retained in the header file for backwards compatibility only.
  6436. */
  6437. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6438. struct sqlite3_pcache_methods {
  6439. void *pArg;
  6440. int (*xInit)(void*);
  6441. void (*xShutdown)(void*);
  6442. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6443. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6444. int (*xPagecount)(sqlite3_pcache*);
  6445. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6446. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6447. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6448. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6449. void (*xDestroy)(sqlite3_pcache*);
  6450. };
  6451. /*
  6452. ** CAPI3REF: Online Backup Object
  6453. **
  6454. ** The sqlite3_backup object records state information about an ongoing
  6455. ** online backup operation. ^The sqlite3_backup object is created by
  6456. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6457. ** [sqlite3_backup_finish()].
  6458. **
  6459. ** See Also: [Using the SQLite Online Backup API]
  6460. */
  6461. typedef struct sqlite3_backup sqlite3_backup;
  6462. /*
  6463. ** CAPI3REF: Online Backup API.
  6464. **
  6465. ** The backup API copies the content of one database into another.
  6466. ** It is useful either for creating backups of databases or
  6467. ** for copying in-memory databases to or from persistent files.
  6468. **
  6469. ** See Also: [Using the SQLite Online Backup API]
  6470. **
  6471. ** ^SQLite holds a write transaction open on the destination database file
  6472. ** for the duration of the backup operation.
  6473. ** ^The source database is read-locked only while it is being read;
  6474. ** it is not locked continuously for the entire backup operation.
  6475. ** ^Thus, the backup may be performed on a live source database without
  6476. ** preventing other database connections from
  6477. ** reading or writing to the source database while the backup is underway.
  6478. **
  6479. ** ^(To perform a backup operation:
  6480. ** <ol>
  6481. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6482. ** backup,
  6483. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6484. ** the data between the two databases, and finally
  6485. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6486. ** associated with the backup operation.
  6487. ** </ol>)^
  6488. ** There should be exactly one call to sqlite3_backup_finish() for each
  6489. ** successful call to sqlite3_backup_init().
  6490. **
  6491. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6492. **
  6493. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6494. ** [database connection] associated with the destination database
  6495. ** and the database name, respectively.
  6496. ** ^The database name is "main" for the main database, "temp" for the
  6497. ** temporary database, or the name specified after the AS keyword in
  6498. ** an [ATTACH] statement for an attached database.
  6499. ** ^The S and M arguments passed to
  6500. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6501. ** and database name of the source database, respectively.
  6502. ** ^The source and destination [database connections] (parameters S and D)
  6503. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6504. ** an error.
  6505. **
  6506. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6507. ** returned and an error code and error message are stored in the
  6508. ** destination [database connection] D.
  6509. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6510. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6511. ** [sqlite3_errmsg16()] functions.
  6512. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6513. ** [sqlite3_backup] object.
  6514. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6515. ** sqlite3_backup_finish() functions to perform the specified backup
  6516. ** operation.
  6517. **
  6518. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6519. **
  6520. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6521. ** the source and destination databases specified by [sqlite3_backup] object B.
  6522. ** ^If N is negative, all remaining source pages are copied.
  6523. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6524. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6525. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6526. ** from source to destination, then it returns [SQLITE_DONE].
  6527. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6528. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6529. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6530. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6531. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6532. **
  6533. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6534. ** <ol>
  6535. ** <li> the destination database was opened read-only, or
  6536. ** <li> the destination database is using write-ahead-log journaling
  6537. ** and the destination and source page sizes differ, or
  6538. ** <li> the destination database is an in-memory database and the
  6539. ** destination and source page sizes differ.
  6540. ** </ol>)^
  6541. **
  6542. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6543. ** the [sqlite3_busy_handler | busy-handler function]
  6544. ** is invoked (if one is specified). ^If the
  6545. ** busy-handler returns non-zero before the lock is available, then
  6546. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6547. ** sqlite3_backup_step() can be retried later. ^If the source
  6548. ** [database connection]
  6549. ** is being used to write to the source database when sqlite3_backup_step()
  6550. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6551. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6552. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6553. ** [SQLITE_READONLY] is returned, then
  6554. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6555. ** errors are considered fatal.)^ The application must accept
  6556. ** that the backup operation has failed and pass the backup operation handle
  6557. ** to the sqlite3_backup_finish() to release associated resources.
  6558. **
  6559. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6560. ** on the destination file. ^The exclusive lock is not released until either
  6561. ** sqlite3_backup_finish() is called or the backup operation is complete
  6562. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6563. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6564. ** lasts for the duration of the sqlite3_backup_step() call.
  6565. ** ^Because the source database is not locked between calls to
  6566. ** sqlite3_backup_step(), the source database may be modified mid-way
  6567. ** through the backup process. ^If the source database is modified by an
  6568. ** external process or via a database connection other than the one being
  6569. ** used by the backup operation, then the backup will be automatically
  6570. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6571. ** database is modified by the using the same database connection as is used
  6572. ** by the backup operation, then the backup database is automatically
  6573. ** updated at the same time.
  6574. **
  6575. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6576. **
  6577. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6578. ** application wishes to abandon the backup operation, the application
  6579. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6580. ** ^The sqlite3_backup_finish() interfaces releases all
  6581. ** resources associated with the [sqlite3_backup] object.
  6582. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6583. ** active write-transaction on the destination database is rolled back.
  6584. ** The [sqlite3_backup] object is invalid
  6585. ** and may not be used following a call to sqlite3_backup_finish().
  6586. **
  6587. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6588. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6589. ** sqlite3_backup_step() completed.
  6590. ** ^If an out-of-memory condition or IO error occurred during any prior
  6591. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6592. ** sqlite3_backup_finish() returns the corresponding [error code].
  6593. **
  6594. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6595. ** is not a permanent error and does not affect the return value of
  6596. ** sqlite3_backup_finish().
  6597. **
  6598. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6599. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6600. **
  6601. ** ^Each call to sqlite3_backup_step() sets two values inside
  6602. ** the [sqlite3_backup] object: the number of pages still to be backed
  6603. ** up and the total number of pages in the source database file.
  6604. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6605. ** retrieve these two values, respectively.
  6606. **
  6607. ** ^The values returned by these functions are only updated by
  6608. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6609. ** operation, then the values are not updated to account for any extra
  6610. ** pages that need to be updated or the size of the source database file
  6611. ** changing.
  6612. **
  6613. ** <b>Concurrent Usage of Database Handles</b>
  6614. **
  6615. ** ^The source [database connection] may be used by the application for other
  6616. ** purposes while a backup operation is underway or being initialized.
  6617. ** ^If SQLite is compiled and configured to support threadsafe database
  6618. ** connections, then the source database connection may be used concurrently
  6619. ** from within other threads.
  6620. **
  6621. ** However, the application must guarantee that the destination
  6622. ** [database connection] is not passed to any other API (by any thread) after
  6623. ** sqlite3_backup_init() is called and before the corresponding call to
  6624. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6625. ** if the application incorrectly accesses the destination [database connection]
  6626. ** and so no error code is reported, but the operations may malfunction
  6627. ** nevertheless. Use of the destination database connection while a
  6628. ** backup is in progress might also also cause a mutex deadlock.
  6629. **
  6630. ** If running in [shared cache mode], the application must
  6631. ** guarantee that the shared cache used by the destination database
  6632. ** is not accessed while the backup is running. In practice this means
  6633. ** that the application must guarantee that the disk file being
  6634. ** backed up to is not accessed by any connection within the process,
  6635. ** not just the specific connection that was passed to sqlite3_backup_init().
  6636. **
  6637. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6638. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6639. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6640. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6641. ** same time as another thread is invoking sqlite3_backup_step() it is
  6642. ** possible that they return invalid values.
  6643. */
  6644. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6645. sqlite3 *pDest, /* Destination database handle */
  6646. const char *zDestName, /* Destination database name */
  6647. sqlite3 *pSource, /* Source database handle */
  6648. const char *zSourceName /* Source database name */
  6649. );
  6650. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6651. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6652. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6653. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6654. /*
  6655. ** CAPI3REF: Unlock Notification
  6656. **
  6657. ** ^When running in shared-cache mode, a database operation may fail with
  6658. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6659. ** individual tables within the shared-cache cannot be obtained. See
  6660. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6661. ** ^This API may be used to register a callback that SQLite will invoke
  6662. ** when the connection currently holding the required lock relinquishes it.
  6663. ** ^This API is only available if the library was compiled with the
  6664. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6665. **
  6666. ** See Also: [Using the SQLite Unlock Notification Feature].
  6667. **
  6668. ** ^Shared-cache locks are released when a database connection concludes
  6669. ** its current transaction, either by committing it or rolling it back.
  6670. **
  6671. ** ^When a connection (known as the blocked connection) fails to obtain a
  6672. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6673. ** identity of the database connection (the blocking connection) that
  6674. ** has locked the required resource is stored internally. ^After an
  6675. ** application receives an SQLITE_LOCKED error, it may call the
  6676. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6677. ** the first argument to register for a callback that will be invoked
  6678. ** when the blocking connections current transaction is concluded. ^The
  6679. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6680. ** call that concludes the blocking connections transaction.
  6681. **
  6682. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6683. ** there is a chance that the blocking connection will have already
  6684. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6685. ** If this happens, then the specified callback is invoked immediately,
  6686. ** from within the call to sqlite3_unlock_notify().)^
  6687. **
  6688. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6689. ** shared-cache table, and more than one other connection currently holds
  6690. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6691. ** the other connections to use as the blocking connection.
  6692. **
  6693. ** ^(There may be at most one unlock-notify callback registered by a
  6694. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6695. ** blocked connection already has a registered unlock-notify callback,
  6696. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6697. ** called with a NULL pointer as its second argument, then any existing
  6698. ** unlock-notify callback is canceled. ^The blocked connections
  6699. ** unlock-notify callback may also be canceled by closing the blocked
  6700. ** connection using [sqlite3_close()].
  6701. **
  6702. ** The unlock-notify callback is not reentrant. If an application invokes
  6703. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6704. ** crash or deadlock may be the result.
  6705. **
  6706. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6707. ** returns SQLITE_OK.
  6708. **
  6709. ** <b>Callback Invocation Details</b>
  6710. **
  6711. ** When an unlock-notify callback is registered, the application provides a
  6712. ** single void* pointer that is passed to the callback when it is invoked.
  6713. ** However, the signature of the callback function allows SQLite to pass
  6714. ** it an array of void* context pointers. The first argument passed to
  6715. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6716. ** and the second is the number of entries in the array.
  6717. **
  6718. ** When a blocking connections transaction is concluded, there may be
  6719. ** more than one blocked connection that has registered for an unlock-notify
  6720. ** callback. ^If two or more such blocked connections have specified the
  6721. ** same callback function, then instead of invoking the callback function
  6722. ** multiple times, it is invoked once with the set of void* context pointers
  6723. ** specified by the blocked connections bundled together into an array.
  6724. ** This gives the application an opportunity to prioritize any actions
  6725. ** related to the set of unblocked database connections.
  6726. **
  6727. ** <b>Deadlock Detection</b>
  6728. **
  6729. ** Assuming that after registering for an unlock-notify callback a
  6730. ** database waits for the callback to be issued before taking any further
  6731. ** action (a reasonable assumption), then using this API may cause the
  6732. ** application to deadlock. For example, if connection X is waiting for
  6733. ** connection Y's transaction to be concluded, and similarly connection
  6734. ** Y is waiting on connection X's transaction, then neither connection
  6735. ** will proceed and the system may remain deadlocked indefinitely.
  6736. **
  6737. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6738. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6739. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6740. ** unlock-notify callback is registered. The system is said to be in
  6741. ** a deadlocked state if connection A has registered for an unlock-notify
  6742. ** callback on the conclusion of connection B's transaction, and connection
  6743. ** B has itself registered for an unlock-notify callback when connection
  6744. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6745. ** the system is also considered to be deadlocked if connection B has
  6746. ** registered for an unlock-notify callback on the conclusion of connection
  6747. ** C's transaction, where connection C is waiting on connection A. ^Any
  6748. ** number of levels of indirection are allowed.
  6749. **
  6750. ** <b>The "DROP TABLE" Exception</b>
  6751. **
  6752. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6753. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6754. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6755. ** SQLite checks if there are any currently executing SELECT statements
  6756. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6757. ** returned. In this case there is no "blocking connection", so invoking
  6758. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6759. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6760. ** or "DROP INDEX" query, an infinite loop might be the result.
  6761. **
  6762. ** One way around this problem is to check the extended error code returned
  6763. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6764. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6765. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6766. ** SQLITE_LOCKED.)^
  6767. */
  6768. SQLITE_API int sqlite3_unlock_notify(
  6769. sqlite3 *pBlocked, /* Waiting connection */
  6770. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6771. void *pNotifyArg /* Argument to pass to xNotify */
  6772. );
  6773. /*
  6774. ** CAPI3REF: String Comparison
  6775. **
  6776. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  6777. ** and extensions to compare the contents of two buffers containing UTF-8
  6778. ** strings in a case-independent fashion, using the same definition of "case
  6779. ** independence" that SQLite uses internally when comparing identifiers.
  6780. */
  6781. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  6782. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6783. /*
  6784. ** CAPI3REF: String Globbing
  6785. *
  6786. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  6787. ** the glob pattern P, and it returns non-zero if string X does not match
  6788. ** the glob pattern P. ^The definition of glob pattern matching used in
  6789. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  6790. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  6791. ** sensitive.
  6792. **
  6793. ** Note that this routine returns zero on a match and non-zero if the strings
  6794. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  6795. */
  6796. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  6797. /*
  6798. ** CAPI3REF: Error Logging Interface
  6799. **
  6800. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  6801. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6802. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6803. ** used with [sqlite3_snprintf()] to generate the final output string.
  6804. **
  6805. ** The sqlite3_log() interface is intended for use by extensions such as
  6806. ** virtual tables, collating functions, and SQL functions. While there is
  6807. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6808. ** is considered bad form.
  6809. **
  6810. ** The zFormat string must not be NULL.
  6811. **
  6812. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6813. ** will not use dynamically allocated memory. The log message is stored in
  6814. ** a fixed-length buffer on the stack. If the log message is longer than
  6815. ** a few hundred characters, it will be truncated to the length of the
  6816. ** buffer.
  6817. */
  6818. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6819. /*
  6820. ** CAPI3REF: Write-Ahead Log Commit Hook
  6821. **
  6822. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6823. ** will be invoked each time a database connection commits data to a
  6824. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6825. ** [journal_mode | journal_mode=WAL mode]).
  6826. **
  6827. ** ^The callback is invoked by SQLite after the commit has taken place and
  6828. ** the associated write-lock on the database released, so the implementation
  6829. ** may read, write or [checkpoint] the database as required.
  6830. **
  6831. ** ^The first parameter passed to the callback function when it is invoked
  6832. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6833. ** registering the callback. ^The second is a copy of the database handle.
  6834. ** ^The third parameter is the name of the database that was written to -
  6835. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6836. ** is the number of pages currently in the write-ahead log file,
  6837. ** including those that were just committed.
  6838. **
  6839. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6840. ** code is returned, that error will propagate back up through the
  6841. ** SQLite code base to cause the statement that provoked the callback
  6842. ** to report an error, though the commit will have still occurred. If the
  6843. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6844. ** that does not correspond to any valid SQLite error code, the results
  6845. ** are undefined.
  6846. **
  6847. ** A single database handle may have at most a single write-ahead log callback
  6848. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6849. ** previously registered write-ahead log callback. ^Note that the
  6850. ** [sqlite3_wal_autocheckpoint()] interface and the
  6851. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6852. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6853. */
  6854. SQLITE_API void *sqlite3_wal_hook(
  6855. sqlite3*,
  6856. int(*)(void *,sqlite3*,const char*,int),
  6857. void*
  6858. );
  6859. /*
  6860. ** CAPI3REF: Configure an auto-checkpoint
  6861. **
  6862. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6863. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  6864. ** to automatically [checkpoint]
  6865. ** after committing a transaction if there are N or
  6866. ** more frames in the [write-ahead log] file. ^Passing zero or
  6867. ** a negative value as the nFrame parameter disables automatic
  6868. ** checkpoints entirely.
  6869. **
  6870. ** ^The callback registered by this function replaces any existing callback
  6871. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  6872. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  6873. ** configured by this function.
  6874. **
  6875. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  6876. ** from SQL.
  6877. **
  6878. ** ^Every new [database connection] defaults to having the auto-checkpoint
  6879. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  6880. ** pages. The use of this interface
  6881. ** is only necessary if the default setting is found to be suboptimal
  6882. ** for a particular application.
  6883. */
  6884. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  6885. /*
  6886. ** CAPI3REF: Checkpoint a database
  6887. **
  6888. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  6889. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  6890. ** empty string, then a checkpoint is run on all databases of
  6891. ** connection D. ^If the database connection D is not in
  6892. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  6893. **
  6894. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  6895. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  6896. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  6897. ** run whenever the WAL reaches a certain size threshold.
  6898. **
  6899. ** See also: [sqlite3_wal_checkpoint_v2()]
  6900. */
  6901. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  6902. /*
  6903. ** CAPI3REF: Checkpoint a database
  6904. **
  6905. ** Run a checkpoint operation on WAL database zDb attached to database
  6906. ** handle db. The specific operation is determined by the value of the
  6907. ** eMode parameter:
  6908. **
  6909. ** <dl>
  6910. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  6911. ** Checkpoint as many frames as possible without waiting for any database
  6912. ** readers or writers to finish. Sync the db file if all frames in the log
  6913. ** are checkpointed. This mode is the same as calling
  6914. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  6915. **
  6916. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  6917. ** This mode blocks (calls the busy-handler callback) until there is no
  6918. ** database writer and all readers are reading from the most recent database
  6919. ** snapshot. It then checkpoints all frames in the log file and syncs the
  6920. ** database file. This call blocks database writers while it is running,
  6921. ** but not database readers.
  6922. **
  6923. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  6924. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  6925. ** checkpointing the log file it blocks (calls the busy-handler callback)
  6926. ** until all readers are reading from the database file only. This ensures
  6927. ** that the next client to write to the database file restarts the log file
  6928. ** from the beginning. This call blocks database writers while it is running,
  6929. ** but not database readers.
  6930. ** </dl>
  6931. **
  6932. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  6933. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  6934. ** the total number of checkpointed frames (including any that were already
  6935. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  6936. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  6937. ** If no values are available because of an error, they are both set to -1
  6938. ** before returning to communicate this to the caller.
  6939. **
  6940. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  6941. ** any other process is running a checkpoint operation at the same time, the
  6942. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  6943. ** busy-handler configured, it will not be invoked in this case.
  6944. **
  6945. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  6946. ** "writer" lock on the database file. If the writer lock cannot be obtained
  6947. ** immediately, and a busy-handler is configured, it is invoked and the writer
  6948. ** lock retried until either the busy-handler returns 0 or the lock is
  6949. ** successfully obtained. The busy-handler is also invoked while waiting for
  6950. ** database readers as described above. If the busy-handler returns 0 before
  6951. ** the writer lock is obtained or while waiting for database readers, the
  6952. ** checkpoint operation proceeds from that point in the same way as
  6953. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  6954. ** without blocking any further. SQLITE_BUSY is returned in this case.
  6955. **
  6956. ** If parameter zDb is NULL or points to a zero length string, then the
  6957. ** specified operation is attempted on all WAL databases. In this case the
  6958. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  6959. ** an SQLITE_BUSY error is encountered when processing one or more of the
  6960. ** attached WAL databases, the operation is still attempted on any remaining
  6961. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  6962. ** error occurs while processing an attached database, processing is abandoned
  6963. ** and the error code returned to the caller immediately. If no error
  6964. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  6965. ** databases, SQLITE_OK is returned.
  6966. **
  6967. ** If database zDb is the name of an attached database that is not in WAL
  6968. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  6969. ** zDb is not NULL (or a zero length string) and is not the name of any
  6970. ** attached database, SQLITE_ERROR is returned to the caller.
  6971. */
  6972. SQLITE_API int sqlite3_wal_checkpoint_v2(
  6973. sqlite3 *db, /* Database handle */
  6974. const char *zDb, /* Name of attached database (or NULL) */
  6975. int eMode, /* SQLITE_CHECKPOINT_* value */
  6976. int *pnLog, /* OUT: Size of WAL log in frames */
  6977. int *pnCkpt /* OUT: Total number of frames checkpointed */
  6978. );
  6979. /*
  6980. ** CAPI3REF: Checkpoint operation parameters
  6981. **
  6982. ** These constants can be used as the 3rd parameter to
  6983. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  6984. ** documentation for additional information about the meaning and use of
  6985. ** each of these values.
  6986. */
  6987. #define SQLITE_CHECKPOINT_PASSIVE 0
  6988. #define SQLITE_CHECKPOINT_FULL 1
  6989. #define SQLITE_CHECKPOINT_RESTART 2
  6990. /*
  6991. ** CAPI3REF: Virtual Table Interface Configuration
  6992. **
  6993. ** This function may be called by either the [xConnect] or [xCreate] method
  6994. ** of a [virtual table] implementation to configure
  6995. ** various facets of the virtual table interface.
  6996. **
  6997. ** If this interface is invoked outside the context of an xConnect or
  6998. ** xCreate virtual table method then the behavior is undefined.
  6999. **
  7000. ** At present, there is only one option that may be configured using
  7001. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7002. ** may be added in the future.
  7003. */
  7004. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7005. /*
  7006. ** CAPI3REF: Virtual Table Configuration Options
  7007. **
  7008. ** These macros define the various options to the
  7009. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7010. ** can use to customize and optimize their behavior.
  7011. **
  7012. ** <dl>
  7013. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7014. ** <dd>Calls of the form
  7015. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7016. ** where X is an integer. If X is zero, then the [virtual table] whose
  7017. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7018. ** support constraints. In this configuration (which is the default) if
  7019. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7020. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7021. ** specified as part of the users SQL statement, regardless of the actual
  7022. ** ON CONFLICT mode specified.
  7023. **
  7024. ** If X is non-zero, then the virtual table implementation guarantees
  7025. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7026. ** any modifications to internal or persistent data structures have been made.
  7027. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7028. ** is able to roll back a statement or database transaction, and abandon
  7029. ** or continue processing the current SQL statement as appropriate.
  7030. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7031. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7032. ** had been ABORT.
  7033. **
  7034. ** Virtual table implementations that are required to handle OR REPLACE
  7035. ** must do so within the [xUpdate] method. If a call to the
  7036. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7037. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7038. ** silently replace the appropriate rows within the xUpdate callback and
  7039. ** return SQLITE_OK. Or, if this is not possible, it may return
  7040. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7041. ** constraint handling.
  7042. ** </dl>
  7043. */
  7044. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7045. /*
  7046. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7047. **
  7048. ** This function may only be called from within a call to the [xUpdate] method
  7049. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7050. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7051. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7052. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7053. ** [virtual table].
  7054. */
  7055. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7056. /*
  7057. ** CAPI3REF: Conflict resolution modes
  7058. **
  7059. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7060. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7061. ** is for the SQL statement being evaluated.
  7062. **
  7063. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7064. ** return value from the [sqlite3_set_authorizer()] callback and that
  7065. ** [SQLITE_ABORT] is also a [result code].
  7066. */
  7067. #define SQLITE_ROLLBACK 1
  7068. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7069. #define SQLITE_FAIL 3
  7070. /* #define SQLITE_ABORT 4 // Also an error code */
  7071. #define SQLITE_REPLACE 5
  7072. /*
  7073. ** Undo the hack that converts floating point types to integer for
  7074. ** builds on processors without floating point support.
  7075. */
  7076. #ifdef SQLITE_OMIT_FLOATING_POINT
  7077. # undef double
  7078. #endif
  7079. #if 0
  7080. } /* End of the 'extern "C"' block */
  7081. #endif
  7082. #endif /* _SQLITE3_H_ */
  7083. /*
  7084. ** 2010 August 30
  7085. **
  7086. ** The author disclaims copyright to this source code. In place of
  7087. ** a legal notice, here is a blessing:
  7088. **
  7089. ** May you do good and not evil.
  7090. ** May you find forgiveness for yourself and forgive others.
  7091. ** May you share freely, never taking more than you give.
  7092. **
  7093. *************************************************************************
  7094. */
  7095. #ifndef _SQLITE3RTREE_H_
  7096. #define _SQLITE3RTREE_H_
  7097. #if 0
  7098. extern "C" {
  7099. #endif
  7100. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7101. /*
  7102. ** Register a geometry callback named zGeom that can be used as part of an
  7103. ** R-Tree geometry query as follows:
  7104. **
  7105. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7106. */
  7107. SQLITE_API int sqlite3_rtree_geometry_callback(
  7108. sqlite3 *db,
  7109. const char *zGeom,
  7110. #ifdef SQLITE_RTREE_INT_ONLY
  7111. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7112. #else
  7113. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7114. #endif
  7115. void *pContext
  7116. );
  7117. /*
  7118. ** A pointer to a structure of the following type is passed as the first
  7119. ** argument to callbacks registered using rtree_geometry_callback().
  7120. */
  7121. struct sqlite3_rtree_geometry {
  7122. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7123. int nParam; /* Size of array aParam[] */
  7124. double *aParam; /* Parameters passed to SQL geom function */
  7125. void *pUser; /* Callback implementation user data */
  7126. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7127. };
  7128. #if 0
  7129. } /* end of the 'extern "C"' block */
  7130. #endif
  7131. #endif /* ifndef _SQLITE3RTREE_H_ */
  7132. /************** End of sqlite3.h *********************************************/
  7133. /************** Begin file sqliteInt.h ***************************************/
  7134. /*
  7135. ** 2001 September 15
  7136. **
  7137. ** The author disclaims copyright to this source code. In place of
  7138. ** a legal notice, here is a blessing:
  7139. **
  7140. ** May you do good and not evil.
  7141. ** May you find forgiveness for yourself and forgive others.
  7142. ** May you share freely, never taking more than you give.
  7143. **
  7144. *************************************************************************
  7145. ** Internal interface definitions for SQLite.
  7146. **
  7147. */
  7148. #ifndef _SQLITEINT_H_
  7149. #define _SQLITEINT_H_
  7150. /*
  7151. ** These #defines should enable >2GB file support on POSIX if the
  7152. ** underlying operating system supports it. If the OS lacks
  7153. ** large file support, or if the OS is windows, these should be no-ops.
  7154. **
  7155. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  7156. ** system #includes. Hence, this block of code must be the very first
  7157. ** code in all source files.
  7158. **
  7159. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  7160. ** on the compiler command line. This is necessary if you are compiling
  7161. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  7162. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  7163. ** without this option, LFS is enable. But LFS does not exist in the kernel
  7164. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  7165. ** portability you should omit LFS.
  7166. **
  7167. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  7168. */
  7169. #ifndef SQLITE_DISABLE_LFS
  7170. # define _LARGE_FILE 1
  7171. # ifndef _FILE_OFFSET_BITS
  7172. # define _FILE_OFFSET_BITS 64
  7173. # endif
  7174. # define _LARGEFILE_SOURCE 1
  7175. #endif
  7176. /*
  7177. ** Include the configuration header output by 'configure' if we're using the
  7178. ** autoconf-based build
  7179. */
  7180. #ifdef _HAVE_SQLITE_CONFIG_H
  7181. #include "config.h"
  7182. #endif
  7183. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7184. /************** Begin file sqliteLimit.h *************************************/
  7185. /*
  7186. ** 2007 May 7
  7187. **
  7188. ** The author disclaims copyright to this source code. In place of
  7189. ** a legal notice, here is a blessing:
  7190. **
  7191. ** May you do good and not evil.
  7192. ** May you find forgiveness for yourself and forgive others.
  7193. ** May you share freely, never taking more than you give.
  7194. **
  7195. *************************************************************************
  7196. **
  7197. ** This file defines various limits of what SQLite can process.
  7198. */
  7199. /*
  7200. ** The maximum length of a TEXT or BLOB in bytes. This also
  7201. ** limits the size of a row in a table or index.
  7202. **
  7203. ** The hard limit is the ability of a 32-bit signed integer
  7204. ** to count the size: 2^31-1 or 2147483647.
  7205. */
  7206. #ifndef SQLITE_MAX_LENGTH
  7207. # define SQLITE_MAX_LENGTH 1000000000
  7208. #endif
  7209. /*
  7210. ** This is the maximum number of
  7211. **
  7212. ** * Columns in a table
  7213. ** * Columns in an index
  7214. ** * Columns in a view
  7215. ** * Terms in the SET clause of an UPDATE statement
  7216. ** * Terms in the result set of a SELECT statement
  7217. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7218. ** * Terms in the VALUES clause of an INSERT statement
  7219. **
  7220. ** The hard upper limit here is 32676. Most database people will
  7221. ** tell you that in a well-normalized database, you usually should
  7222. ** not have more than a dozen or so columns in any table. And if
  7223. ** that is the case, there is no point in having more than a few
  7224. ** dozen values in any of the other situations described above.
  7225. */
  7226. #ifndef SQLITE_MAX_COLUMN
  7227. # define SQLITE_MAX_COLUMN 2000
  7228. #endif
  7229. /*
  7230. ** The maximum length of a single SQL statement in bytes.
  7231. **
  7232. ** It used to be the case that setting this value to zero would
  7233. ** turn the limit off. That is no longer true. It is not possible
  7234. ** to turn this limit off.
  7235. */
  7236. #ifndef SQLITE_MAX_SQL_LENGTH
  7237. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7238. #endif
  7239. /*
  7240. ** The maximum depth of an expression tree. This is limited to
  7241. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7242. ** want to place more severe limits on the complexity of an
  7243. ** expression.
  7244. **
  7245. ** A value of 0 used to mean that the limit was not enforced.
  7246. ** But that is no longer true. The limit is now strictly enforced
  7247. ** at all times.
  7248. */
  7249. #ifndef SQLITE_MAX_EXPR_DEPTH
  7250. # define SQLITE_MAX_EXPR_DEPTH 1000
  7251. #endif
  7252. /*
  7253. ** The maximum number of terms in a compound SELECT statement.
  7254. ** The code generator for compound SELECT statements does one
  7255. ** level of recursion for each term. A stack overflow can result
  7256. ** if the number of terms is too large. In practice, most SQL
  7257. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7258. ** any limit on the number of terms in a compount SELECT.
  7259. */
  7260. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7261. # define SQLITE_MAX_COMPOUND_SELECT 500
  7262. #endif
  7263. /*
  7264. ** The maximum number of opcodes in a VDBE program.
  7265. ** Not currently enforced.
  7266. */
  7267. #ifndef SQLITE_MAX_VDBE_OP
  7268. # define SQLITE_MAX_VDBE_OP 25000
  7269. #endif
  7270. /*
  7271. ** The maximum number of arguments to an SQL function.
  7272. */
  7273. #ifndef SQLITE_MAX_FUNCTION_ARG
  7274. # define SQLITE_MAX_FUNCTION_ARG 127
  7275. #endif
  7276. /*
  7277. ** The maximum number of in-memory pages to use for the main database
  7278. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7279. */
  7280. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7281. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7282. #endif
  7283. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7284. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7285. #endif
  7286. /*
  7287. ** The default number of frames to accumulate in the log file before
  7288. ** checkpointing the database in WAL mode.
  7289. */
  7290. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7291. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7292. #endif
  7293. /*
  7294. ** The maximum number of attached databases. This must be between 0
  7295. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7296. ** is used internally to track attached databases.
  7297. */
  7298. #ifndef SQLITE_MAX_ATTACHED
  7299. # define SQLITE_MAX_ATTACHED 10
  7300. #endif
  7301. /*
  7302. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7303. */
  7304. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7305. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7306. #endif
  7307. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7308. ** imposed by the use of 16-bit offsets within each page.
  7309. **
  7310. ** Earlier versions of SQLite allowed the user to change this value at
  7311. ** compile time. This is no longer permitted, on the grounds that it creates
  7312. ** a library that is technically incompatible with an SQLite library
  7313. ** compiled with a different limit. If a process operating on a database
  7314. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7315. ** compiled with the default page-size limit will not be able to rollback
  7316. ** the aborted transaction. This could lead to database corruption.
  7317. */
  7318. #ifdef SQLITE_MAX_PAGE_SIZE
  7319. # undef SQLITE_MAX_PAGE_SIZE
  7320. #endif
  7321. #define SQLITE_MAX_PAGE_SIZE 65536
  7322. /*
  7323. ** The default size of a database page.
  7324. */
  7325. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7326. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7327. #endif
  7328. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7329. # undef SQLITE_DEFAULT_PAGE_SIZE
  7330. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7331. #endif
  7332. /*
  7333. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7334. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7335. ** device characteristics (sector-size and atomic write() support),
  7336. ** SQLite may choose a larger value. This constant is the maximum value
  7337. ** SQLite will choose on its own.
  7338. */
  7339. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7340. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7341. #endif
  7342. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7343. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7344. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7345. #endif
  7346. /*
  7347. ** Maximum number of pages in one database file.
  7348. **
  7349. ** This is really just the default value for the max_page_count pragma.
  7350. ** This value can be lowered (or raised) at run-time using that the
  7351. ** max_page_count macro.
  7352. */
  7353. #ifndef SQLITE_MAX_PAGE_COUNT
  7354. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7355. #endif
  7356. /*
  7357. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7358. ** operator.
  7359. */
  7360. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7361. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7362. #endif
  7363. /*
  7364. ** Maximum depth of recursion for triggers.
  7365. **
  7366. ** A value of 1 means that a trigger program will not be able to itself
  7367. ** fire any triggers. A value of 0 means that no trigger programs at all
  7368. ** may be executed.
  7369. */
  7370. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7371. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7372. #endif
  7373. /************** End of sqliteLimit.h *****************************************/
  7374. /************** Continuing where we left off in sqliteInt.h ******************/
  7375. /* Disable nuisance warnings on Borland compilers */
  7376. #if defined(__BORLANDC__)
  7377. #pragma warn -rch /* unreachable code */
  7378. #pragma warn -ccc /* Condition is always true or false */
  7379. #pragma warn -aus /* Assigned value is never used */
  7380. #pragma warn -csu /* Comparing signed and unsigned */
  7381. #pragma warn -spa /* Suspicious pointer arithmetic */
  7382. #endif
  7383. /* Needed for various definitions... */
  7384. #ifndef _GNU_SOURCE
  7385. # define _GNU_SOURCE
  7386. #endif
  7387. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  7388. # define _BSD_SOURCE
  7389. #endif
  7390. /*
  7391. ** Include standard header files as necessary
  7392. */
  7393. #ifdef HAVE_STDINT_H
  7394. #include <stdint.h>
  7395. #endif
  7396. #ifdef HAVE_INTTYPES_H
  7397. #include <inttypes.h>
  7398. #endif
  7399. /*
  7400. ** The following macros are used to cast pointers to integers and
  7401. ** integers to pointers. The way you do this varies from one compiler
  7402. ** to the next, so we have developed the following set of #if statements
  7403. ** to generate appropriate macros for a wide range of compilers.
  7404. **
  7405. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7406. ** Unfortunately, that typedef is not available on all compilers, or
  7407. ** if it is available, it requires an #include of specific headers
  7408. ** that vary from one machine to the next.
  7409. **
  7410. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7411. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7412. ** So we have to define the macros in different ways depending on the
  7413. ** compiler.
  7414. */
  7415. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7416. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7417. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7418. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7419. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7420. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7421. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7422. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7423. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7424. #else /* Generates a warning - but it always works */
  7425. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7426. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7427. #endif
  7428. /*
  7429. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7430. ** 0 means mutexes are permanently disable and the library is never
  7431. ** threadsafe. 1 means the library is serialized which is the highest
  7432. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7433. ** threads can use SQLite as long as no two threads try to use the same
  7434. ** database connection at the same time.
  7435. **
  7436. ** Older versions of SQLite used an optional THREADSAFE macro.
  7437. ** We support that for legacy.
  7438. */
  7439. #if !defined(SQLITE_THREADSAFE)
  7440. # if defined(THREADSAFE)
  7441. # define SQLITE_THREADSAFE THREADSAFE
  7442. # else
  7443. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7444. # endif
  7445. #endif
  7446. /*
  7447. ** Powersafe overwrite is on by default. But can be turned off using
  7448. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7449. */
  7450. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7451. # define SQLITE_POWERSAFE_OVERWRITE 1
  7452. #endif
  7453. /*
  7454. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7455. ** It determines whether or not the features related to
  7456. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7457. ** be overridden at runtime using the sqlite3_config() API.
  7458. */
  7459. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7460. # define SQLITE_DEFAULT_MEMSTATUS 1
  7461. #endif
  7462. /*
  7463. ** Exactly one of the following macros must be defined in order to
  7464. ** specify which memory allocation subsystem to use.
  7465. **
  7466. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7467. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7468. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7469. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7470. **
  7471. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7472. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7473. ** will cause HeapValidate to be called. If heap validation should fail, an
  7474. ** assertion will be triggered.
  7475. **
  7476. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7477. ** the default.
  7478. */
  7479. #if defined(SQLITE_SYSTEM_MALLOC) \
  7480. + defined(SQLITE_WIN32_MALLOC) \
  7481. + defined(SQLITE_ZERO_MALLOC) \
  7482. + defined(SQLITE_MEMDEBUG)>1
  7483. # error "Two or more of the following compile-time configuration options\
  7484. are defined but at most one is allowed:\
  7485. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7486. SQLITE_ZERO_MALLOC"
  7487. #endif
  7488. #if defined(SQLITE_SYSTEM_MALLOC) \
  7489. + defined(SQLITE_WIN32_MALLOC) \
  7490. + defined(SQLITE_ZERO_MALLOC) \
  7491. + defined(SQLITE_MEMDEBUG)==0
  7492. # define SQLITE_SYSTEM_MALLOC 1
  7493. #endif
  7494. /*
  7495. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7496. ** sizes of memory allocations below this value where possible.
  7497. */
  7498. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7499. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7500. #endif
  7501. /*
  7502. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7503. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7504. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7505. ** it.
  7506. */
  7507. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7508. # define _XOPEN_SOURCE 600
  7509. #endif
  7510. /*
  7511. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7512. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7513. ** make it true by defining or undefining NDEBUG.
  7514. **
  7515. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7516. ** assert() statements in the code. So we want the default action
  7517. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7518. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7519. ** feature.
  7520. */
  7521. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7522. # define NDEBUG 1
  7523. #endif
  7524. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7525. # undef NDEBUG
  7526. #endif
  7527. /*
  7528. ** The testcase() macro is used to aid in coverage testing. When
  7529. ** doing coverage testing, the condition inside the argument to
  7530. ** testcase() must be evaluated both true and false in order to
  7531. ** get full branch coverage. The testcase() macro is inserted
  7532. ** to help ensure adequate test coverage in places where simple
  7533. ** condition/decision coverage is inadequate. For example, testcase()
  7534. ** can be used to make sure boundary values are tested. For
  7535. ** bitmask tests, testcase() can be used to make sure each bit
  7536. ** is significant and used at least once. On switch statements
  7537. ** where multiple cases go to the same block of code, testcase()
  7538. ** can insure that all cases are evaluated.
  7539. **
  7540. */
  7541. #ifdef SQLITE_COVERAGE_TEST
  7542. SQLITE_PRIVATE void sqlite3Coverage(int);
  7543. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7544. #else
  7545. # define testcase(X)
  7546. #endif
  7547. /*
  7548. ** The TESTONLY macro is used to enclose variable declarations or
  7549. ** other bits of code that are needed to support the arguments
  7550. ** within testcase() and assert() macros.
  7551. */
  7552. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7553. # define TESTONLY(X) X
  7554. #else
  7555. # define TESTONLY(X)
  7556. #endif
  7557. /*
  7558. ** Sometimes we need a small amount of code such as a variable initialization
  7559. ** to setup for a later assert() statement. We do not want this code to
  7560. ** appear when assert() is disabled. The following macro is therefore
  7561. ** used to contain that setup code. The "VVA" acronym stands for
  7562. ** "Verification, Validation, and Accreditation". In other words, the
  7563. ** code within VVA_ONLY() will only run during verification processes.
  7564. */
  7565. #ifndef NDEBUG
  7566. # define VVA_ONLY(X) X
  7567. #else
  7568. # define VVA_ONLY(X)
  7569. #endif
  7570. /*
  7571. ** The ALWAYS and NEVER macros surround boolean expressions which
  7572. ** are intended to always be true or false, respectively. Such
  7573. ** expressions could be omitted from the code completely. But they
  7574. ** are included in a few cases in order to enhance the resilience
  7575. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7576. ** or "ductile" rather than being "brittle" and crashing at the first
  7577. ** hint of unplanned behavior.
  7578. **
  7579. ** In other words, ALWAYS and NEVER are added for defensive code.
  7580. **
  7581. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7582. ** be true and false so that the unreachable code they specify will
  7583. ** not be counted as untested code.
  7584. */
  7585. #if defined(SQLITE_COVERAGE_TEST)
  7586. # define ALWAYS(X) (1)
  7587. # define NEVER(X) (0)
  7588. #elif !defined(NDEBUG)
  7589. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7590. # define NEVER(X) ((X)?(assert(0),1):0)
  7591. #else
  7592. # define ALWAYS(X) (X)
  7593. # define NEVER(X) (X)
  7594. #endif
  7595. /*
  7596. ** Return true (non-zero) if the input is a integer that is too large
  7597. ** to fit in 32-bits. This macro is used inside of various testcase()
  7598. ** macros to verify that we have tested SQLite for large-file support.
  7599. */
  7600. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7601. /*
  7602. ** The macro unlikely() is a hint that surrounds a boolean
  7603. ** expression that is usually false. Macro likely() surrounds
  7604. ** a boolean expression that is usually true. These hints could,
  7605. ** in theory, be used by the compiler to generate better code, but
  7606. ** currently they are just comments for human readers.
  7607. */
  7608. #define likely(X) (X)
  7609. #define unlikely(X) (X)
  7610. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7611. /************** Begin file hash.h ********************************************/
  7612. /*
  7613. ** 2001 September 22
  7614. **
  7615. ** The author disclaims copyright to this source code. In place of
  7616. ** a legal notice, here is a blessing:
  7617. **
  7618. ** May you do good and not evil.
  7619. ** May you find forgiveness for yourself and forgive others.
  7620. ** May you share freely, never taking more than you give.
  7621. **
  7622. *************************************************************************
  7623. ** This is the header file for the generic hash-table implementation
  7624. ** used in SQLite.
  7625. */
  7626. #ifndef _SQLITE_HASH_H_
  7627. #define _SQLITE_HASH_H_
  7628. /* Forward declarations of structures. */
  7629. typedef struct Hash Hash;
  7630. typedef struct HashElem HashElem;
  7631. /* A complete hash table is an instance of the following structure.
  7632. ** The internals of this structure are intended to be opaque -- client
  7633. ** code should not attempt to access or modify the fields of this structure
  7634. ** directly. Change this structure only by using the routines below.
  7635. ** However, some of the "procedures" and "functions" for modifying and
  7636. ** accessing this structure are really macros, so we can't really make
  7637. ** this structure opaque.
  7638. **
  7639. ** All elements of the hash table are on a single doubly-linked list.
  7640. ** Hash.first points to the head of this list.
  7641. **
  7642. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7643. ** the global doubly-linked list. The contents of the bucket are the
  7644. ** element pointed to plus the next _ht.count-1 elements in the list.
  7645. **
  7646. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7647. ** by a linear search of the global list. For small tables, the
  7648. ** Hash.ht table is never allocated because if there are few elements
  7649. ** in the table, it is faster to do a linear search than to manage
  7650. ** the hash table.
  7651. */
  7652. struct Hash {
  7653. unsigned int htsize; /* Number of buckets in the hash table */
  7654. unsigned int count; /* Number of entries in this table */
  7655. HashElem *first; /* The first element of the array */
  7656. struct _ht { /* the hash table */
  7657. int count; /* Number of entries with this hash */
  7658. HashElem *chain; /* Pointer to first entry with this hash */
  7659. } *ht;
  7660. };
  7661. /* Each element in the hash table is an instance of the following
  7662. ** structure. All elements are stored on a single doubly-linked list.
  7663. **
  7664. ** Again, this structure is intended to be opaque, but it can't really
  7665. ** be opaque because it is used by macros.
  7666. */
  7667. struct HashElem {
  7668. HashElem *next, *prev; /* Next and previous elements in the table */
  7669. void *data; /* Data associated with this element */
  7670. const char *pKey; int nKey; /* Key associated with this element */
  7671. };
  7672. /*
  7673. ** Access routines. To delete, insert a NULL pointer.
  7674. */
  7675. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7676. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7677. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7678. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7679. /*
  7680. ** Macros for looping over all elements of a hash table. The idiom is
  7681. ** like this:
  7682. **
  7683. ** Hash h;
  7684. ** HashElem *p;
  7685. ** ...
  7686. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7687. ** SomeStructure *pData = sqliteHashData(p);
  7688. ** // do something with pData
  7689. ** }
  7690. */
  7691. #define sqliteHashFirst(H) ((H)->first)
  7692. #define sqliteHashNext(E) ((E)->next)
  7693. #define sqliteHashData(E) ((E)->data)
  7694. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7695. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7696. /*
  7697. ** Number of entries in a hash table
  7698. */
  7699. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7700. #endif /* _SQLITE_HASH_H_ */
  7701. /************** End of hash.h ************************************************/
  7702. /************** Continuing where we left off in sqliteInt.h ******************/
  7703. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7704. /************** Begin file parse.h *******************************************/
  7705. #define TK_SEMI 1
  7706. #define TK_EXPLAIN 2
  7707. #define TK_QUERY 3
  7708. #define TK_PLAN 4
  7709. #define TK_BEGIN 5
  7710. #define TK_TRANSACTION 6
  7711. #define TK_DEFERRED 7
  7712. #define TK_IMMEDIATE 8
  7713. #define TK_EXCLUSIVE 9
  7714. #define TK_COMMIT 10
  7715. #define TK_END 11
  7716. #define TK_ROLLBACK 12
  7717. #define TK_SAVEPOINT 13
  7718. #define TK_RELEASE 14
  7719. #define TK_TO 15
  7720. #define TK_TABLE 16
  7721. #define TK_CREATE 17
  7722. #define TK_IF 18
  7723. #define TK_NOT 19
  7724. #define TK_EXISTS 20
  7725. #define TK_TEMP 21
  7726. #define TK_LP 22
  7727. #define TK_RP 23
  7728. #define TK_AS 24
  7729. #define TK_COMMA 25
  7730. #define TK_ID 26
  7731. #define TK_INDEXED 27
  7732. #define TK_ABORT 28
  7733. #define TK_ACTION 29
  7734. #define TK_AFTER 30
  7735. #define TK_ANALYZE 31
  7736. #define TK_ASC 32
  7737. #define TK_ATTACH 33
  7738. #define TK_BEFORE 34
  7739. #define TK_BY 35
  7740. #define TK_CASCADE 36
  7741. #define TK_CAST 37
  7742. #define TK_COLUMNKW 38
  7743. #define TK_CONFLICT 39
  7744. #define TK_DATABASE 40
  7745. #define TK_DESC 41
  7746. #define TK_DETACH 42
  7747. #define TK_EACH 43
  7748. #define TK_FAIL 44
  7749. #define TK_FOR 45
  7750. #define TK_IGNORE 46
  7751. #define TK_INITIALLY 47
  7752. #define TK_INSTEAD 48
  7753. #define TK_LIKE_KW 49
  7754. #define TK_MATCH 50
  7755. #define TK_NO 51
  7756. #define TK_KEY 52
  7757. #define TK_OF 53
  7758. #define TK_OFFSET 54
  7759. #define TK_PRAGMA 55
  7760. #define TK_RAISE 56
  7761. #define TK_REPLACE 57
  7762. #define TK_RESTRICT 58
  7763. #define TK_ROW 59
  7764. #define TK_TRIGGER 60
  7765. #define TK_VACUUM 61
  7766. #define TK_VIEW 62
  7767. #define TK_VIRTUAL 63
  7768. #define TK_REINDEX 64
  7769. #define TK_RENAME 65
  7770. #define TK_CTIME_KW 66
  7771. #define TK_ANY 67
  7772. #define TK_OR 68
  7773. #define TK_AND 69
  7774. #define TK_IS 70
  7775. #define TK_BETWEEN 71
  7776. #define TK_IN 72
  7777. #define TK_ISNULL 73
  7778. #define TK_NOTNULL 74
  7779. #define TK_NE 75
  7780. #define TK_EQ 76
  7781. #define TK_GT 77
  7782. #define TK_LE 78
  7783. #define TK_LT 79
  7784. #define TK_GE 80
  7785. #define TK_ESCAPE 81
  7786. #define TK_BITAND 82
  7787. #define TK_BITOR 83
  7788. #define TK_LSHIFT 84
  7789. #define TK_RSHIFT 85
  7790. #define TK_PLUS 86
  7791. #define TK_MINUS 87
  7792. #define TK_STAR 88
  7793. #define TK_SLASH 89
  7794. #define TK_REM 90
  7795. #define TK_CONCAT 91
  7796. #define TK_COLLATE 92
  7797. #define TK_BITNOT 93
  7798. #define TK_STRING 94
  7799. #define TK_JOIN_KW 95
  7800. #define TK_CONSTRAINT 96
  7801. #define TK_DEFAULT 97
  7802. #define TK_NULL 98
  7803. #define TK_PRIMARY 99
  7804. #define TK_UNIQUE 100
  7805. #define TK_CHECK 101
  7806. #define TK_REFERENCES 102
  7807. #define TK_AUTOINCR 103
  7808. #define TK_ON 104
  7809. #define TK_INSERT 105
  7810. #define TK_DELETE 106
  7811. #define TK_UPDATE 107
  7812. #define TK_SET 108
  7813. #define TK_DEFERRABLE 109
  7814. #define TK_FOREIGN 110
  7815. #define TK_DROP 111
  7816. #define TK_UNION 112
  7817. #define TK_ALL 113
  7818. #define TK_EXCEPT 114
  7819. #define TK_INTERSECT 115
  7820. #define TK_SELECT 116
  7821. #define TK_DISTINCT 117
  7822. #define TK_DOT 118
  7823. #define TK_FROM 119
  7824. #define TK_JOIN 120
  7825. #define TK_USING 121
  7826. #define TK_ORDER 122
  7827. #define TK_GROUP 123
  7828. #define TK_HAVING 124
  7829. #define TK_LIMIT 125
  7830. #define TK_WHERE 126
  7831. #define TK_INTO 127
  7832. #define TK_VALUES 128
  7833. #define TK_INTEGER 129
  7834. #define TK_FLOAT 130
  7835. #define TK_BLOB 131
  7836. #define TK_REGISTER 132
  7837. #define TK_VARIABLE 133
  7838. #define TK_CASE 134
  7839. #define TK_WHEN 135
  7840. #define TK_THEN 136
  7841. #define TK_ELSE 137
  7842. #define TK_INDEX 138
  7843. #define TK_ALTER 139
  7844. #define TK_ADD 140
  7845. #define TK_TO_TEXT 141
  7846. #define TK_TO_BLOB 142
  7847. #define TK_TO_NUMERIC 143
  7848. #define TK_TO_INT 144
  7849. #define TK_TO_REAL 145
  7850. #define TK_ISNOT 146
  7851. #define TK_END_OF_FILE 147
  7852. #define TK_ILLEGAL 148
  7853. #define TK_SPACE 149
  7854. #define TK_UNCLOSED_STRING 150
  7855. #define TK_FUNCTION 151
  7856. #define TK_COLUMN 152
  7857. #define TK_AGG_FUNCTION 153
  7858. #define TK_AGG_COLUMN 154
  7859. #define TK_CONST_FUNC 155
  7860. #define TK_UMINUS 156
  7861. #define TK_UPLUS 157
  7862. /************** End of parse.h ***********************************************/
  7863. /************** Continuing where we left off in sqliteInt.h ******************/
  7864. #include <stdio.h>
  7865. #include <stdlib.h>
  7866. #include <string.h>
  7867. #include <assert.h>
  7868. #include <stddef.h>
  7869. /*
  7870. ** If compiling for a processor that lacks floating point support,
  7871. ** substitute integer for floating-point
  7872. */
  7873. #ifdef SQLITE_OMIT_FLOATING_POINT
  7874. # define double sqlite_int64
  7875. # define float sqlite_int64
  7876. # define LONGDOUBLE_TYPE sqlite_int64
  7877. # ifndef SQLITE_BIG_DBL
  7878. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7879. # endif
  7880. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7881. # define SQLITE_OMIT_TRACE 1
  7882. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7883. # undef SQLITE_HAVE_ISNAN
  7884. #endif
  7885. #ifndef SQLITE_BIG_DBL
  7886. # define SQLITE_BIG_DBL (1e99)
  7887. #endif
  7888. /*
  7889. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7890. ** afterward. Having this macro allows us to cause the C compiler
  7891. ** to omit code used by TEMP tables without messy #ifndef statements.
  7892. */
  7893. #ifdef SQLITE_OMIT_TEMPDB
  7894. #define OMIT_TEMPDB 1
  7895. #else
  7896. #define OMIT_TEMPDB 0
  7897. #endif
  7898. /*
  7899. ** The "file format" number is an integer that is incremented whenever
  7900. ** the VDBE-level file format changes. The following macros define the
  7901. ** the default file format for new databases and the maximum file format
  7902. ** that the library can read.
  7903. */
  7904. #define SQLITE_MAX_FILE_FORMAT 4
  7905. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7906. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7907. #endif
  7908. /*
  7909. ** Determine whether triggers are recursive by default. This can be
  7910. ** changed at run-time using a pragma.
  7911. */
  7912. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7913. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7914. #endif
  7915. /*
  7916. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7917. ** on the command-line
  7918. */
  7919. #ifndef SQLITE_TEMP_STORE
  7920. # define SQLITE_TEMP_STORE 1
  7921. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  7922. #endif
  7923. /*
  7924. ** GCC does not define the offsetof() macro so we'll have to do it
  7925. ** ourselves.
  7926. */
  7927. #ifndef offsetof
  7928. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7929. #endif
  7930. /*
  7931. ** Macros to compute minimum and maximum of two numbers.
  7932. */
  7933. #define MIN(A,B) ((A)<(B)?(A):(B))
  7934. #define MAX(A,B) ((A)>(B)?(A):(B))
  7935. /*
  7936. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7937. ** not, there are still machines out there that use EBCDIC.)
  7938. */
  7939. #if 'A' == '\301'
  7940. # define SQLITE_EBCDIC 1
  7941. #else
  7942. # define SQLITE_ASCII 1
  7943. #endif
  7944. /*
  7945. ** Integers of known sizes. These typedefs might change for architectures
  7946. ** where the sizes very. Preprocessor macros are available so that the
  7947. ** types can be conveniently redefined at compile-type. Like this:
  7948. **
  7949. ** cc '-DUINTPTR_TYPE=long long int' ...
  7950. */
  7951. #ifndef UINT32_TYPE
  7952. # ifdef HAVE_UINT32_T
  7953. # define UINT32_TYPE uint32_t
  7954. # else
  7955. # define UINT32_TYPE unsigned int
  7956. # endif
  7957. #endif
  7958. #ifndef UINT16_TYPE
  7959. # ifdef HAVE_UINT16_T
  7960. # define UINT16_TYPE uint16_t
  7961. # else
  7962. # define UINT16_TYPE unsigned short int
  7963. # endif
  7964. #endif
  7965. #ifndef INT16_TYPE
  7966. # ifdef HAVE_INT16_T
  7967. # define INT16_TYPE int16_t
  7968. # else
  7969. # define INT16_TYPE short int
  7970. # endif
  7971. #endif
  7972. #ifndef UINT8_TYPE
  7973. # ifdef HAVE_UINT8_T
  7974. # define UINT8_TYPE uint8_t
  7975. # else
  7976. # define UINT8_TYPE unsigned char
  7977. # endif
  7978. #endif
  7979. #ifndef INT8_TYPE
  7980. # ifdef HAVE_INT8_T
  7981. # define INT8_TYPE int8_t
  7982. # else
  7983. # define INT8_TYPE signed char
  7984. # endif
  7985. #endif
  7986. #ifndef LONGDOUBLE_TYPE
  7987. # define LONGDOUBLE_TYPE long double
  7988. #endif
  7989. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7990. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7991. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7992. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7993. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7994. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7995. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7996. /*
  7997. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7998. ** that can be stored in a u32 without loss of data. The value
  7999. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8000. ** have to specify the value in the less intuitive manner shown:
  8001. */
  8002. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8003. /*
  8004. ** The datatype used to store estimates of the number of rows in a
  8005. ** table or index. This is an unsigned integer type. For 99.9% of
  8006. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8007. ** can be used at compile-time if desired.
  8008. */
  8009. #ifdef SQLITE_64BIT_STATS
  8010. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8011. #else
  8012. typedef u32 tRowcnt; /* 32-bit is the default */
  8013. #endif
  8014. /*
  8015. ** Estimated quantities used for query planning are stored as 16-bit
  8016. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8017. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8018. ** But the allowed values are "grainy". Not every value is representable.
  8019. ** For example, quantities 16 and 17 are both represented by a LogEst
  8020. ** of 40. However, since LogEst quantatites are suppose to be estimates,
  8021. ** not exact values, this imprecision is not a problem.
  8022. **
  8023. ** "LogEst" is short for "Logarithimic Estimate".
  8024. **
  8025. ** Examples:
  8026. ** 1 -> 0 20 -> 43 10000 -> 132
  8027. ** 2 -> 10 25 -> 46 25000 -> 146
  8028. ** 3 -> 16 100 -> 66 1000000 -> 199
  8029. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8030. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8031. **
  8032. ** The LogEst can be negative to indicate fractional values.
  8033. ** Examples:
  8034. **
  8035. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8036. */
  8037. typedef INT16_TYPE LogEst;
  8038. /*
  8039. ** Macros to determine whether the machine is big or little endian,
  8040. ** evaluated at runtime.
  8041. */
  8042. #ifdef SQLITE_AMALGAMATION
  8043. SQLITE_PRIVATE const int sqlite3one = 1;
  8044. #else
  8045. SQLITE_PRIVATE const int sqlite3one;
  8046. #endif
  8047. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  8048. || defined(__x86_64) || defined(__x86_64__)
  8049. # define SQLITE_BIGENDIAN 0
  8050. # define SQLITE_LITTLEENDIAN 1
  8051. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8052. #else
  8053. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8054. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8055. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8056. #endif
  8057. /*
  8058. ** Constants for the largest and smallest possible 64-bit signed integers.
  8059. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8060. ** compilers.
  8061. */
  8062. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8063. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8064. /*
  8065. ** Round up a number to the next larger multiple of 8. This is used
  8066. ** to force 8-byte alignment on 64-bit architectures.
  8067. */
  8068. #define ROUND8(x) (((x)+7)&~7)
  8069. /*
  8070. ** Round down to the nearest multiple of 8
  8071. */
  8072. #define ROUNDDOWN8(x) ((x)&~7)
  8073. /*
  8074. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8075. ** macro is used only within assert() to verify that the code gets
  8076. ** all alignment restrictions correct.
  8077. **
  8078. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8079. ** underlying malloc() implemention might return us 4-byte aligned
  8080. ** pointers. In that case, only verify 4-byte alignment.
  8081. */
  8082. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8083. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8084. #else
  8085. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8086. #endif
  8087. /*
  8088. ** Disable MMAP on platforms where it is known to not work
  8089. */
  8090. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8091. # undef SQLITE_MAX_MMAP_SIZE
  8092. # define SQLITE_MAX_MMAP_SIZE 0
  8093. #endif
  8094. /*
  8095. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8096. */
  8097. #ifdef __APPLE__
  8098. # include <TargetConditionals.h>
  8099. # if TARGET_OS_IPHONE
  8100. # undef SQLITE_MAX_MMAP_SIZE
  8101. # define SQLITE_MAX_MMAP_SIZE 0
  8102. # endif
  8103. #endif
  8104. #ifndef SQLITE_MAX_MMAP_SIZE
  8105. # if defined(SQLITE_OS_RTT)
  8106. # define SQLITE_MAX_MMAP_SIZE 0
  8107. # elif defined(__linux__) \
  8108. || defined(_WIN32) \
  8109. || (defined(__APPLE__) && defined(__MACH__)) \
  8110. || defined(__sun)
  8111. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8112. # else
  8113. # define SQLITE_MAX_MMAP_SIZE 0
  8114. # endif
  8115. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8116. #endif
  8117. /*
  8118. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8119. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8120. ** not exceed the maximum mmap size.
  8121. */
  8122. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8123. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8124. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8125. #endif
  8126. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8127. # undef SQLITE_DEFAULT_MMAP_SIZE
  8128. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8129. #endif
  8130. /*
  8131. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8132. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8133. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8134. */
  8135. #ifdef SQLITE_ENABLE_STAT4
  8136. # undef SQLITE_ENABLE_STAT3
  8137. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8138. #elif SQLITE_ENABLE_STAT3
  8139. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8140. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8141. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8142. #endif
  8143. /*
  8144. ** An instance of the following structure is used to store the busy-handler
  8145. ** callback for a given sqlite handle.
  8146. **
  8147. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8148. ** callback for the database handle. Each pager opened via the sqlite
  8149. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8150. ** callback is currently invoked only from within pager.c.
  8151. */
  8152. typedef struct BusyHandler BusyHandler;
  8153. struct BusyHandler {
  8154. int (*xFunc)(void *,int); /* The busy callback */
  8155. void *pArg; /* First arg to busy callback */
  8156. int nBusy; /* Incremented with each busy call */
  8157. };
  8158. /*
  8159. ** Name of the master database table. The master database table
  8160. ** is a special table that holds the names and attributes of all
  8161. ** user tables and indices.
  8162. */
  8163. #define MASTER_NAME "sqlite_master"
  8164. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8165. /*
  8166. ** The root-page of the master database table.
  8167. */
  8168. #define MASTER_ROOT 1
  8169. /*
  8170. ** The name of the schema table.
  8171. */
  8172. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8173. /*
  8174. ** A convenience macro that returns the number of elements in
  8175. ** an array.
  8176. */
  8177. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8178. /*
  8179. ** Determine if the argument is a power of two
  8180. */
  8181. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8182. /*
  8183. ** The following value as a destructor means to use sqlite3DbFree().
  8184. ** The sqlite3DbFree() routine requires two parameters instead of the
  8185. ** one parameter that destructors normally want. So we have to introduce
  8186. ** this magic value that the code knows to handle differently. Any
  8187. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8188. ** and SQLITE_TRANSIENT.
  8189. */
  8190. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8191. /*
  8192. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8193. ** not support Writable Static Data (WSD) such as global and static variables.
  8194. ** All variables must either be on the stack or dynamically allocated from
  8195. ** the heap. When WSD is unsupported, the variable declarations scattered
  8196. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8197. ** macro is used for this purpose. And instead of referencing the variable
  8198. ** directly, we use its constant as a key to lookup the run-time allocated
  8199. ** buffer that holds real variable. The constant is also the initializer
  8200. ** for the run-time allocated buffer.
  8201. **
  8202. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8203. ** macros become no-ops and have zero performance impact.
  8204. */
  8205. #ifdef SQLITE_OMIT_WSD
  8206. #define SQLITE_WSD const
  8207. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8208. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8209. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8210. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8211. #else
  8212. #define SQLITE_WSD
  8213. #define GLOBAL(t,v) v
  8214. #define sqlite3GlobalConfig sqlite3Config
  8215. #endif
  8216. /*
  8217. ** The following macros are used to suppress compiler warnings and to
  8218. ** make it clear to human readers when a function parameter is deliberately
  8219. ** left unused within the body of a function. This usually happens when
  8220. ** a function is called via a function pointer. For example the
  8221. ** implementation of an SQL aggregate step callback may not use the
  8222. ** parameter indicating the number of arguments passed to the aggregate,
  8223. ** if it knows that this is enforced elsewhere.
  8224. **
  8225. ** When a function parameter is not used at all within the body of a function,
  8226. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8227. ** However, these macros may also be used to suppress warnings related to
  8228. ** parameters that may or may not be used depending on compilation options.
  8229. ** For example those parameters only used in assert() statements. In these
  8230. ** cases the parameters are named as per the usual conventions.
  8231. */
  8232. #define UNUSED_PARAMETER(x) (void)(x)
  8233. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8234. /*
  8235. ** Forward references to structures
  8236. */
  8237. typedef struct AggInfo AggInfo;
  8238. typedef struct AuthContext AuthContext;
  8239. typedef struct AutoincInfo AutoincInfo;
  8240. typedef struct Bitvec Bitvec;
  8241. typedef struct CollSeq CollSeq;
  8242. typedef struct Column Column;
  8243. typedef struct Db Db;
  8244. typedef struct Schema Schema;
  8245. typedef struct Expr Expr;
  8246. typedef struct ExprList ExprList;
  8247. typedef struct ExprSpan ExprSpan;
  8248. typedef struct FKey FKey;
  8249. typedef struct FuncDestructor FuncDestructor;
  8250. typedef struct FuncDef FuncDef;
  8251. typedef struct FuncDefHash FuncDefHash;
  8252. typedef struct IdList IdList;
  8253. typedef struct Index Index;
  8254. typedef struct IndexSample IndexSample;
  8255. typedef struct KeyClass KeyClass;
  8256. typedef struct KeyInfo KeyInfo;
  8257. typedef struct Lookaside Lookaside;
  8258. typedef struct LookasideSlot LookasideSlot;
  8259. typedef struct Module Module;
  8260. typedef struct NameContext NameContext;
  8261. typedef struct Parse Parse;
  8262. typedef struct RowSet RowSet;
  8263. typedef struct Savepoint Savepoint;
  8264. typedef struct Select Select;
  8265. typedef struct SelectDest SelectDest;
  8266. typedef struct SrcList SrcList;
  8267. typedef struct StrAccum StrAccum;
  8268. typedef struct Table Table;
  8269. typedef struct TableLock TableLock;
  8270. typedef struct Token Token;
  8271. typedef struct Trigger Trigger;
  8272. typedef struct TriggerPrg TriggerPrg;
  8273. typedef struct TriggerStep TriggerStep;
  8274. typedef struct UnpackedRecord UnpackedRecord;
  8275. typedef struct VTable VTable;
  8276. typedef struct VtabCtx VtabCtx;
  8277. typedef struct Walker Walker;
  8278. typedef struct WhereInfo WhereInfo;
  8279. /*
  8280. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8281. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8282. ** pointer types (i.e. FuncDef) defined above.
  8283. */
  8284. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8285. /************** Begin file btree.h *******************************************/
  8286. /*
  8287. ** 2001 September 15
  8288. **
  8289. ** The author disclaims copyright to this source code. In place of
  8290. ** a legal notice, here is a blessing:
  8291. **
  8292. ** May you do good and not evil.
  8293. ** May you find forgiveness for yourself and forgive others.
  8294. ** May you share freely, never taking more than you give.
  8295. **
  8296. *************************************************************************
  8297. ** This header file defines the interface that the sqlite B-Tree file
  8298. ** subsystem. See comments in the source code for a detailed description
  8299. ** of what each interface routine does.
  8300. */
  8301. #ifndef _BTREE_H_
  8302. #define _BTREE_H_
  8303. /* TODO: This definition is just included so other modules compile. It
  8304. ** needs to be revisited.
  8305. */
  8306. #define SQLITE_N_BTREE_META 10
  8307. /*
  8308. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8309. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8310. */
  8311. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8312. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8313. #endif
  8314. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8315. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8316. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8317. /*
  8318. ** Forward declarations of structure
  8319. */
  8320. typedef struct Btree Btree;
  8321. typedef struct BtCursor BtCursor;
  8322. typedef struct BtShared BtShared;
  8323. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8324. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8325. const char *zFilename, /* Name of database file to open */
  8326. sqlite3 *db, /* Associated database connection */
  8327. Btree **ppBtree, /* Return open Btree* here */
  8328. int flags, /* Flags */
  8329. int vfsFlags /* Flags passed through to VFS open */
  8330. );
  8331. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8332. ** following values.
  8333. **
  8334. ** NOTE: These values must match the corresponding PAGER_ values in
  8335. ** pager.h.
  8336. */
  8337. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8338. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8339. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8340. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8341. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8342. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8343. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8344. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8345. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8346. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8347. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8348. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8349. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8350. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8351. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8352. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8353. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8354. #endif
  8355. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8356. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8357. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8358. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8359. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8360. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8361. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8362. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8363. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8364. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8365. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8366. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8367. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8368. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8369. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8370. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8371. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8372. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8373. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8374. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8375. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8376. ** of the flags shown below.
  8377. **
  8378. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8379. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8380. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8381. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8382. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8383. ** indices.)
  8384. */
  8385. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8386. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8387. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8388. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8389. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8390. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8391. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8392. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8393. /*
  8394. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8395. ** should be one of the following values. The integer values are assigned
  8396. ** to constants so that the offset of the corresponding field in an
  8397. ** SQLite database header may be found using the following formula:
  8398. **
  8399. ** offset = 36 + (idx * 4)
  8400. **
  8401. ** For example, the free-page-count field is located at byte offset 36 of
  8402. ** the database file header. The incr-vacuum-flag field is located at
  8403. ** byte offset 64 (== 36+4*7).
  8404. */
  8405. #define BTREE_FREE_PAGE_COUNT 0
  8406. #define BTREE_SCHEMA_VERSION 1
  8407. #define BTREE_FILE_FORMAT 2
  8408. #define BTREE_DEFAULT_CACHE_SIZE 3
  8409. #define BTREE_LARGEST_ROOT_PAGE 4
  8410. #define BTREE_TEXT_ENCODING 5
  8411. #define BTREE_USER_VERSION 6
  8412. #define BTREE_INCR_VACUUM 7
  8413. #define BTREE_APPLICATION_ID 8
  8414. /*
  8415. ** Values that may be OR'd together to form the second argument of an
  8416. ** sqlite3BtreeCursorHints() call.
  8417. */
  8418. #define BTREE_BULKLOAD 0x00000001
  8419. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8420. Btree*, /* BTree containing table to open */
  8421. int iTable, /* Index of root page */
  8422. int wrFlag, /* 1 for writing. 0 for read-only */
  8423. struct KeyInfo*, /* First argument to compare function */
  8424. BtCursor *pCursor /* Space to write cursor structure */
  8425. );
  8426. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8427. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8428. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8429. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8430. BtCursor*,
  8431. UnpackedRecord *pUnKey,
  8432. i64 intKey,
  8433. int bias,
  8434. int *pRes
  8435. );
  8436. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8437. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8438. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8439. const void *pData, int nData,
  8440. int nZero, int bias, int seekResult);
  8441. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8442. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8443. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8444. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8445. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8446. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8447. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8448. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8449. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8450. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8451. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8452. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8453. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8454. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8455. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8456. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8457. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8458. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8459. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8460. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8461. #ifndef NDEBUG
  8462. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8463. #endif
  8464. #ifndef SQLITE_OMIT_BTREECOUNT
  8465. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8466. #endif
  8467. #ifdef SQLITE_TEST
  8468. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8469. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8470. #endif
  8471. #ifndef SQLITE_OMIT_WAL
  8472. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8473. #endif
  8474. /*
  8475. ** If we are not using shared cache, then there is no need to
  8476. ** use mutexes to access the BtShared structures. So make the
  8477. ** Enter and Leave procedures no-ops.
  8478. */
  8479. #ifndef SQLITE_OMIT_SHARED_CACHE
  8480. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8481. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8482. #else
  8483. # define sqlite3BtreeEnter(X)
  8484. # define sqlite3BtreeEnterAll(X)
  8485. #endif
  8486. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8487. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8488. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8489. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8490. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8491. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8492. #ifndef NDEBUG
  8493. /* These routines are used inside assert() statements only. */
  8494. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8495. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8496. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8497. #endif
  8498. #else
  8499. # define sqlite3BtreeSharable(X) 0
  8500. # define sqlite3BtreeLeave(X)
  8501. # define sqlite3BtreeEnterCursor(X)
  8502. # define sqlite3BtreeLeaveCursor(X)
  8503. # define sqlite3BtreeLeaveAll(X)
  8504. # define sqlite3BtreeHoldsMutex(X) 1
  8505. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8506. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8507. #endif
  8508. #endif /* _BTREE_H_ */
  8509. /************** End of btree.h ***********************************************/
  8510. /************** Continuing where we left off in sqliteInt.h ******************/
  8511. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8512. /************** Begin file vdbe.h ********************************************/
  8513. /*
  8514. ** 2001 September 15
  8515. **
  8516. ** The author disclaims copyright to this source code. In place of
  8517. ** a legal notice, here is a blessing:
  8518. **
  8519. ** May you do good and not evil.
  8520. ** May you find forgiveness for yourself and forgive others.
  8521. ** May you share freely, never taking more than you give.
  8522. **
  8523. *************************************************************************
  8524. ** Header file for the Virtual DataBase Engine (VDBE)
  8525. **
  8526. ** This header defines the interface to the virtual database engine
  8527. ** or VDBE. The VDBE implements an abstract machine that runs a
  8528. ** simple program to access and modify the underlying database.
  8529. */
  8530. #ifndef _SQLITE_VDBE_H_
  8531. #define _SQLITE_VDBE_H_
  8532. /* #include <stdio.h> */
  8533. /*
  8534. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8535. ** in the source file sqliteVdbe.c are allowed to see the insides
  8536. ** of this structure.
  8537. */
  8538. typedef struct Vdbe Vdbe;
  8539. /*
  8540. ** The names of the following types declared in vdbeInt.h are required
  8541. ** for the VdbeOp definition.
  8542. */
  8543. typedef struct Mem Mem;
  8544. typedef struct SubProgram SubProgram;
  8545. /*
  8546. ** A single instruction of the virtual machine has an opcode
  8547. ** and as many as three operands. The instruction is recorded
  8548. ** as an instance of the following structure:
  8549. */
  8550. struct VdbeOp {
  8551. u8 opcode; /* What operation to perform */
  8552. signed char p4type; /* One of the P4_xxx constants for p4 */
  8553. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8554. u8 p5; /* Fifth parameter is an unsigned character */
  8555. int p1; /* First operand */
  8556. int p2; /* Second parameter (often the jump destination) */
  8557. int p3; /* The third parameter */
  8558. union { /* fourth parameter */
  8559. int i; /* Integer value if p4type==P4_INT32 */
  8560. void *p; /* Generic pointer */
  8561. char *z; /* Pointer to data for string (char array) types */
  8562. i64 *pI64; /* Used when p4type is P4_INT64 */
  8563. double *pReal; /* Used when p4type is P4_REAL */
  8564. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8565. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8566. Mem *pMem; /* Used when p4type is P4_MEM */
  8567. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8568. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8569. int *ai; /* Used when p4type is P4_INTARRAY */
  8570. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8571. int (*xAdvance)(BtCursor *, int *);
  8572. } p4;
  8573. #ifdef SQLITE_DEBUG
  8574. char *zComment; /* Comment to improve readability */
  8575. #endif
  8576. #ifdef VDBE_PROFILE
  8577. int cnt; /* Number of times this instruction was executed */
  8578. u64 cycles; /* Total time spent executing this instruction */
  8579. #endif
  8580. };
  8581. typedef struct VdbeOp VdbeOp;
  8582. /*
  8583. ** A sub-routine used to implement a trigger program.
  8584. */
  8585. struct SubProgram {
  8586. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8587. int nOp; /* Elements in aOp[] */
  8588. int nMem; /* Number of memory cells required */
  8589. int nCsr; /* Number of cursors required */
  8590. int nOnce; /* Number of OP_Once instructions */
  8591. void *token; /* id that may be used to recursive triggers */
  8592. SubProgram *pNext; /* Next sub-program already visited */
  8593. };
  8594. /*
  8595. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8596. ** it takes up less space.
  8597. */
  8598. struct VdbeOpList {
  8599. u8 opcode; /* What operation to perform */
  8600. signed char p1; /* First operand */
  8601. signed char p2; /* Second parameter (often the jump destination) */
  8602. signed char p3; /* Third parameter */
  8603. };
  8604. typedef struct VdbeOpList VdbeOpList;
  8605. /*
  8606. ** Allowed values of VdbeOp.p4type
  8607. */
  8608. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8609. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8610. #define P4_STATIC (-2) /* Pointer to a static string */
  8611. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8612. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8613. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8614. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8615. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8616. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8617. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8618. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8619. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8620. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8621. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8622. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8623. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8624. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8625. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8626. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8627. ** gets freed when the Vdbe is finalized so it still should be obtained
  8628. ** from a single sqliteMalloc(). But no copy is made and the calling
  8629. ** function should *not* try to free the KeyInfo.
  8630. */
  8631. #define P4_KEYINFO_HANDOFF (-16)
  8632. #define P4_KEYINFO_STATIC (-17)
  8633. /*
  8634. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8635. ** number of columns of data returned by the statement.
  8636. */
  8637. #define COLNAME_NAME 0
  8638. #define COLNAME_DECLTYPE 1
  8639. #define COLNAME_DATABASE 2
  8640. #define COLNAME_TABLE 3
  8641. #define COLNAME_COLUMN 4
  8642. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8643. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8644. #else
  8645. # ifdef SQLITE_OMIT_DECLTYPE
  8646. # define COLNAME_N 1 /* Store only the name */
  8647. # else
  8648. # define COLNAME_N 2 /* Store the name and decltype */
  8649. # endif
  8650. #endif
  8651. /*
  8652. ** The following macro converts a relative address in the p2 field
  8653. ** of a VdbeOp structure into a negative number so that
  8654. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8655. ** the macro again restores the address.
  8656. */
  8657. #define ADDR(X) (-1-(X))
  8658. /*
  8659. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8660. ** header file that defines a number for each opcode used by the VDBE.
  8661. */
  8662. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8663. /************** Begin file opcodes.h *****************************************/
  8664. /* Automatically generated. Do not edit */
  8665. /* See the mkopcodeh.awk script for details */
  8666. #define OP_Function 1
  8667. #define OP_Savepoint 2
  8668. #define OP_AutoCommit 3
  8669. #define OP_Transaction 4
  8670. #define OP_SorterNext 5
  8671. #define OP_Prev 6
  8672. #define OP_Next 7
  8673. #define OP_AggStep 8
  8674. #define OP_Checkpoint 9
  8675. #define OP_JournalMode 10
  8676. #define OP_Vacuum 11
  8677. #define OP_VFilter 12
  8678. #define OP_VUpdate 13
  8679. #define OP_Goto 14
  8680. #define OP_Gosub 15
  8681. #define OP_Return 16
  8682. #define OP_Yield 17
  8683. #define OP_HaltIfNull 18
  8684. #define OP_Not 19 /* same as TK_NOT */
  8685. #define OP_Halt 20
  8686. #define OP_Integer 21
  8687. #define OP_Int64 22
  8688. #define OP_String 23
  8689. #define OP_Null 24
  8690. #define OP_Blob 25
  8691. #define OP_Variable 26
  8692. #define OP_Move 27
  8693. #define OP_Copy 28
  8694. #define OP_SCopy 29
  8695. #define OP_ResultRow 30
  8696. #define OP_CollSeq 31
  8697. #define OP_AddImm 32
  8698. #define OP_MustBeInt 33
  8699. #define OP_RealAffinity 34
  8700. #define OP_Permutation 35
  8701. #define OP_Compare 36
  8702. #define OP_Jump 37
  8703. #define OP_Once 38
  8704. #define OP_If 39
  8705. #define OP_IfNot 40
  8706. #define OP_Column 41
  8707. #define OP_Affinity 42
  8708. #define OP_MakeRecord 43
  8709. #define OP_Count 44
  8710. #define OP_ReadCookie 45
  8711. #define OP_SetCookie 46
  8712. #define OP_VerifyCookie 47
  8713. #define OP_OpenRead 48
  8714. #define OP_OpenWrite 49
  8715. #define OP_OpenAutoindex 50
  8716. #define OP_OpenEphemeral 51
  8717. #define OP_SorterOpen 52
  8718. #define OP_OpenPseudo 53
  8719. #define OP_Close 54
  8720. #define OP_SeekLt 55
  8721. #define OP_SeekLe 56
  8722. #define OP_SeekGe 57
  8723. #define OP_SeekGt 58
  8724. #define OP_Seek 59
  8725. #define OP_NotFound 60
  8726. #define OP_Found 61
  8727. #define OP_IsUnique 62
  8728. #define OP_NotExists 63
  8729. #define OP_Sequence 64
  8730. #define OP_NewRowid 65
  8731. #define OP_Insert 66
  8732. #define OP_InsertInt 67
  8733. #define OP_Or 68 /* same as TK_OR */
  8734. #define OP_And 69 /* same as TK_AND */
  8735. #define OP_Delete 70
  8736. #define OP_ResetCount 71
  8737. #define OP_SorterCompare 72
  8738. #define OP_IsNull 73 /* same as TK_ISNULL */
  8739. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8740. #define OP_Ne 75 /* same as TK_NE */
  8741. #define OP_Eq 76 /* same as TK_EQ */
  8742. #define OP_Gt 77 /* same as TK_GT */
  8743. #define OP_Le 78 /* same as TK_LE */
  8744. #define OP_Lt 79 /* same as TK_LT */
  8745. #define OP_Ge 80 /* same as TK_GE */
  8746. #define OP_SorterData 81
  8747. #define OP_BitAnd 82 /* same as TK_BITAND */
  8748. #define OP_BitOr 83 /* same as TK_BITOR */
  8749. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8750. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8751. #define OP_Add 86 /* same as TK_PLUS */
  8752. #define OP_Subtract 87 /* same as TK_MINUS */
  8753. #define OP_Multiply 88 /* same as TK_STAR */
  8754. #define OP_Divide 89 /* same as TK_SLASH */
  8755. #define OP_Remainder 90 /* same as TK_REM */
  8756. #define OP_Concat 91 /* same as TK_CONCAT */
  8757. #define OP_RowKey 92
  8758. #define OP_BitNot 93 /* same as TK_BITNOT */
  8759. #define OP_String8 94 /* same as TK_STRING */
  8760. #define OP_RowData 95
  8761. #define OP_Rowid 96
  8762. #define OP_NullRow 97
  8763. #define OP_Last 98
  8764. #define OP_SorterSort 99
  8765. #define OP_Sort 100
  8766. #define OP_Rewind 101
  8767. #define OP_SorterInsert 102
  8768. #define OP_IdxInsert 103
  8769. #define OP_IdxDelete 104
  8770. #define OP_IdxRowid 105
  8771. #define OP_IdxLT 106
  8772. #define OP_IdxGE 107
  8773. #define OP_Destroy 108
  8774. #define OP_Clear 109
  8775. #define OP_CreateIndex 110
  8776. #define OP_CreateTable 111
  8777. #define OP_ParseSchema 112
  8778. #define OP_LoadAnalysis 113
  8779. #define OP_DropTable 114
  8780. #define OP_DropIndex 115
  8781. #define OP_DropTrigger 116
  8782. #define OP_IntegrityCk 117
  8783. #define OP_RowSetAdd 118
  8784. #define OP_RowSetRead 119
  8785. #define OP_RowSetTest 120
  8786. #define OP_Program 121
  8787. #define OP_Param 122
  8788. #define OP_FkCounter 123
  8789. #define OP_FkIfZero 124
  8790. #define OP_MemMax 125
  8791. #define OP_IfPos 126
  8792. #define OP_IfNeg 127
  8793. #define OP_IfZero 128
  8794. #define OP_AggFinal 129
  8795. #define OP_Real 130 /* same as TK_FLOAT */
  8796. #define OP_IncrVacuum 131
  8797. #define OP_Expire 132
  8798. #define OP_TableLock 133
  8799. #define OP_VBegin 134
  8800. #define OP_VCreate 135
  8801. #define OP_VDestroy 136
  8802. #define OP_VOpen 137
  8803. #define OP_VColumn 138
  8804. #define OP_VNext 139
  8805. #define OP_VRename 140
  8806. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8807. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8808. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8809. #define OP_ToInt 144 /* same as TK_TO_INT */
  8810. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8811. #define OP_Pagecount 146
  8812. #define OP_MaxPgcnt 147
  8813. #define OP_Trace 148
  8814. #define OP_Noop 149
  8815. #define OP_Explain 150
  8816. /* Properties such as "out2" or "jump" that are specified in
  8817. ** comments following the "case" for each opcode in the vdbe.c
  8818. ** are encoded into bitvectors as follows:
  8819. */
  8820. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8821. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8822. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8823. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8824. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8825. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8826. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8827. #define OPFLG_INITIALIZER {\
  8828. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  8829. /* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\
  8830. /* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\
  8831. /* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\
  8832. /* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\
  8833. /* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\
  8834. /* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\
  8835. /* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\
  8836. /* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\
  8837. /* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8838. /* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8839. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\
  8840. /* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\
  8841. /* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\
  8842. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
  8843. /* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\
  8844. /* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\
  8845. /* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\
  8846. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8847. /************** End of opcodes.h *********************************************/
  8848. /************** Continuing where we left off in vdbe.h ***********************/
  8849. /*
  8850. ** Prototypes for the VDBE interface. See comments on the implementation
  8851. ** for a description of what each of these routines does.
  8852. */
  8853. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8854. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8855. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8856. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8857. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8858. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8859. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8860. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8861. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8862. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8863. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8864. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8865. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8866. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8867. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8868. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8869. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8870. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8871. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8872. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8873. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8874. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8875. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8876. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8877. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8878. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8879. #ifdef SQLITE_DEBUG
  8880. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8881. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8882. #endif
  8883. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8884. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8885. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8886. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8887. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8888. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8889. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8890. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8891. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8892. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8893. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  8894. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8895. #ifndef SQLITE_OMIT_TRACE
  8896. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8897. #endif
  8898. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8899. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8900. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8901. #ifndef SQLITE_OMIT_TRIGGER
  8902. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8903. #endif
  8904. #ifndef NDEBUG
  8905. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8906. # define VdbeComment(X) sqlite3VdbeComment X
  8907. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8908. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8909. #else
  8910. # define VdbeComment(X)
  8911. # define VdbeNoopComment(X)
  8912. #endif
  8913. #endif
  8914. /************** End of vdbe.h ************************************************/
  8915. /************** Continuing where we left off in sqliteInt.h ******************/
  8916. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8917. /************** Begin file pager.h *******************************************/
  8918. /*
  8919. ** 2001 September 15
  8920. **
  8921. ** The author disclaims copyright to this source code. In place of
  8922. ** a legal notice, here is a blessing:
  8923. **
  8924. ** May you do good and not evil.
  8925. ** May you find forgiveness for yourself and forgive others.
  8926. ** May you share freely, never taking more than you give.
  8927. **
  8928. *************************************************************************
  8929. ** This header file defines the interface that the sqlite page cache
  8930. ** subsystem. The page cache subsystem reads and writes a file a page
  8931. ** at a time and provides a journal for rollback.
  8932. */
  8933. #ifndef _PAGER_H_
  8934. #define _PAGER_H_
  8935. /*
  8936. ** Default maximum size for persistent journal files. A negative
  8937. ** value means no limit. This value may be overridden using the
  8938. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8939. */
  8940. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8941. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8942. #endif
  8943. /*
  8944. ** The type used to represent a page number. The first page in a file
  8945. ** is called page 1. 0 is used to represent "not a page".
  8946. */
  8947. typedef u32 Pgno;
  8948. /*
  8949. ** Each open file is managed by a separate instance of the "Pager" structure.
  8950. */
  8951. typedef struct Pager Pager;
  8952. /*
  8953. ** Handle type for pages.
  8954. */
  8955. typedef struct PgHdr DbPage;
  8956. /*
  8957. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8958. ** reserved for working around a windows/posix incompatibility). It is
  8959. ** used in the journal to signify that the remainder of the journal file
  8960. ** is devoted to storing a master journal name - there are no more pages to
  8961. ** roll back. See comments for function writeMasterJournal() in pager.c
  8962. ** for details.
  8963. */
  8964. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8965. /*
  8966. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8967. **
  8968. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8969. */
  8970. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8971. #define PAGER_MEMORY 0x0002 /* In-memory database */
  8972. /*
  8973. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8974. */
  8975. #define PAGER_LOCKINGMODE_QUERY -1
  8976. #define PAGER_LOCKINGMODE_NORMAL 0
  8977. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8978. /*
  8979. ** Numeric constants that encode the journalmode.
  8980. */
  8981. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8982. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8983. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8984. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8985. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8986. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8987. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8988. /*
  8989. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  8990. */
  8991. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  8992. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  8993. /*
  8994. ** Flags for sqlite3PagerSetFlags()
  8995. */
  8996. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  8997. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  8998. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  8999. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9000. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9001. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9002. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9003. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9004. /*
  9005. ** The remainder of this file contains the declarations of the functions
  9006. ** that make up the Pager sub-system API. See source code comments for
  9007. ** a detailed description of each routine.
  9008. */
  9009. /* Open and close a Pager connection. */
  9010. SQLITE_PRIVATE int sqlite3PagerOpen(
  9011. sqlite3_vfs*,
  9012. Pager **ppPager,
  9013. const char*,
  9014. int,
  9015. int,
  9016. int,
  9017. void(*)(DbPage*)
  9018. );
  9019. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9020. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9021. /* Functions used to configure a Pager object. */
  9022. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9023. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9024. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9025. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9026. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9027. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9028. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9029. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9030. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9031. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9032. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9033. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9034. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9035. /* Functions used to obtain and release page references. */
  9036. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9037. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9038. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9039. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9040. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9041. /* Operations on page references. */
  9042. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9043. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9044. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9045. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9046. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9047. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9048. /* Functions used to manage pager transactions and savepoints. */
  9049. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9050. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9051. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9052. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9053. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  9054. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9055. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9056. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9057. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9058. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9059. #ifndef SQLITE_OMIT_WAL
  9060. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9061. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9062. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9063. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9064. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9065. #endif
  9066. #ifdef SQLITE_ENABLE_ZIPVFS
  9067. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9068. #endif
  9069. /* Functions used to query pager state and configuration. */
  9070. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9071. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9072. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9073. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9074. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9075. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9076. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9077. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9078. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9079. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9080. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9081. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9082. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9083. /* Functions used to truncate the database file. */
  9084. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9085. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9086. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9087. #endif
  9088. /* Functions to support testing and debugging. */
  9089. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9090. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9091. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9092. #endif
  9093. #ifdef SQLITE_TEST
  9094. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9095. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9096. void disable_simulated_io_errors(void);
  9097. void enable_simulated_io_errors(void);
  9098. #else
  9099. # define disable_simulated_io_errors()
  9100. # define enable_simulated_io_errors()
  9101. #endif
  9102. #endif /* _PAGER_H_ */
  9103. /************** End of pager.h ***********************************************/
  9104. /************** Continuing where we left off in sqliteInt.h ******************/
  9105. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9106. /************** Begin file pcache.h ******************************************/
  9107. /*
  9108. ** 2008 August 05
  9109. **
  9110. ** The author disclaims copyright to this source code. In place of
  9111. ** a legal notice, here is a blessing:
  9112. **
  9113. ** May you do good and not evil.
  9114. ** May you find forgiveness for yourself and forgive others.
  9115. ** May you share freely, never taking more than you give.
  9116. **
  9117. *************************************************************************
  9118. ** This header file defines the interface that the sqlite page cache
  9119. ** subsystem.
  9120. */
  9121. #ifndef _PCACHE_H_
  9122. typedef struct PgHdr PgHdr;
  9123. typedef struct PCache PCache;
  9124. /*
  9125. ** Every page in the cache is controlled by an instance of the following
  9126. ** structure.
  9127. */
  9128. struct PgHdr {
  9129. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9130. void *pData; /* Page data */
  9131. void *pExtra; /* Extra content */
  9132. PgHdr *pDirty; /* Transient list of dirty pages */
  9133. Pager *pPager; /* The pager this page is part of */
  9134. Pgno pgno; /* Page number for this page */
  9135. #ifdef SQLITE_CHECK_PAGES
  9136. u32 pageHash; /* Hash of page content */
  9137. #endif
  9138. u16 flags; /* PGHDR flags defined below */
  9139. /**********************************************************************
  9140. ** Elements above are public. All that follows is private to pcache.c
  9141. ** and should not be accessed by other modules.
  9142. */
  9143. i16 nRef; /* Number of users of this page */
  9144. PCache *pCache; /* Cache that owns this page */
  9145. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9146. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9147. };
  9148. /* Bit values for PgHdr.flags */
  9149. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9150. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9151. ** writing this page to the database */
  9152. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9153. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9154. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9155. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9156. /* Initialize and shutdown the page cache subsystem */
  9157. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9158. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9159. /* Page cache buffer management:
  9160. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9161. */
  9162. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9163. /* Create a new pager cache.
  9164. ** Under memory stress, invoke xStress to try to make pages clean.
  9165. ** Only clean and unpinned pages can be reclaimed.
  9166. */
  9167. SQLITE_PRIVATE void sqlite3PcacheOpen(
  9168. int szPage, /* Size of every page */
  9169. int szExtra, /* Extra space associated with each page */
  9170. int bPurgeable, /* True if pages are on backing store */
  9171. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9172. void *pStress, /* Argument to xStress */
  9173. PCache *pToInit /* Preallocated space for the PCache */
  9174. );
  9175. /* Modify the page-size after the cache has been created. */
  9176. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  9177. /* Return the size in bytes of a PCache object. Used to preallocate
  9178. ** storage space.
  9179. */
  9180. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9181. /* One release per successful fetch. Page is pinned until released.
  9182. ** Reference counted.
  9183. */
  9184. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  9185. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9186. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9187. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9188. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9189. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9190. /* Change a page number. Used by incr-vacuum. */
  9191. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9192. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9193. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9194. /* Get a list of all dirty pages in the cache, sorted by page number */
  9195. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9196. /* Reset and close the cache object */
  9197. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9198. /* Clear flags from pages of the page cache */
  9199. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9200. /* Discard the contents of the cache */
  9201. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9202. /* Return the total number of outstanding page references */
  9203. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9204. /* Increment the reference count of an existing page */
  9205. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9206. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9207. /* Return the total number of pages stored in the cache */
  9208. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9209. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9210. /* Iterate through all dirty pages currently stored in the cache. This
  9211. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9212. ** library is built.
  9213. */
  9214. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9215. #endif
  9216. /* Set and get the suggested cache-size for the specified pager-cache.
  9217. **
  9218. ** If no global maximum is configured, then the system attempts to limit
  9219. ** the total number of pages cached by purgeable pager-caches to the sum
  9220. ** of the suggested cache-sizes.
  9221. */
  9222. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9223. #ifdef SQLITE_TEST
  9224. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9225. #endif
  9226. /* Free up as much memory as possible from the page cache */
  9227. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9228. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9229. /* Try to return memory used by the pcache module to the main memory heap */
  9230. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9231. #endif
  9232. #ifdef SQLITE_TEST
  9233. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9234. #endif
  9235. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9236. #endif /* _PCACHE_H_ */
  9237. /************** End of pcache.h **********************************************/
  9238. /************** Continuing where we left off in sqliteInt.h ******************/
  9239. /************** Include os.h in the middle of sqliteInt.h ********************/
  9240. /************** Begin file os.h **********************************************/
  9241. /*
  9242. ** 2001 September 16
  9243. **
  9244. ** The author disclaims copyright to this source code. In place of
  9245. ** a legal notice, here is a blessing:
  9246. **
  9247. ** May you do good and not evil.
  9248. ** May you find forgiveness for yourself and forgive others.
  9249. ** May you share freely, never taking more than you give.
  9250. **
  9251. ******************************************************************************
  9252. **
  9253. ** This header file (together with is companion C source-code file
  9254. ** "os.c") attempt to abstract the underlying operating system so that
  9255. ** the SQLite library will work on both POSIX and windows systems.
  9256. **
  9257. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9258. ** being included by every source file.
  9259. */
  9260. #ifndef _SQLITE_OS_H_
  9261. #define _SQLITE_OS_H_
  9262. /*
  9263. ** Figure out if we are dealing with Unix, Windows, or some other
  9264. ** operating system. After the following block of preprocess macros,
  9265. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9266. ** will defined to either 1 or 0. One of the four will be 1. The other
  9267. ** three will be 0.
  9268. */
  9269. #if defined(SQLITE_OS_OTHER)
  9270. # if SQLITE_OS_OTHER==1
  9271. # undef SQLITE_OS_UNIX
  9272. # define SQLITE_OS_UNIX 0
  9273. # undef SQLITE_OS_WIN
  9274. # define SQLITE_OS_WIN 0
  9275. # undef SQLITE_OS_RTT
  9276. # define SQLITE_OS_RTT 1
  9277. # else
  9278. # undef SQLITE_OS_OTHER
  9279. # endif
  9280. #endif
  9281. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9282. # define SQLITE_OS_OTHER 0
  9283. # ifndef SQLITE_OS_WIN
  9284. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9285. # define SQLITE_OS_WIN 1
  9286. # define SQLITE_OS_UNIX 0
  9287. # else
  9288. # define SQLITE_OS_WIN 0
  9289. # define SQLITE_OS_UNIX 1
  9290. # endif
  9291. # else
  9292. # define SQLITE_OS_UNIX 0
  9293. # endif
  9294. #else
  9295. # ifndef SQLITE_OS_WIN
  9296. # define SQLITE_OS_WIN 0
  9297. # endif
  9298. #endif
  9299. #if SQLITE_OS_WIN
  9300. # include <windows.h>
  9301. #endif
  9302. /*
  9303. ** Determine if we are dealing with Windows NT.
  9304. **
  9305. ** We ought to be able to determine if we are compiling for win98 or winNT
  9306. ** using the _WIN32_WINNT macro as follows:
  9307. **
  9308. ** #if defined(_WIN32_WINNT)
  9309. ** # define SQLITE_OS_WINNT 1
  9310. ** #else
  9311. ** # define SQLITE_OS_WINNT 0
  9312. ** #endif
  9313. **
  9314. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9315. ** so the above test does not work. We'll just assume that everything is
  9316. ** winNT unless the programmer explicitly says otherwise by setting
  9317. ** SQLITE_OS_WINNT to 0.
  9318. */
  9319. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9320. # define SQLITE_OS_WINNT 1
  9321. #endif
  9322. /*
  9323. ** Determine if we are dealing with WindowsCE - which has a much
  9324. ** reduced API.
  9325. */
  9326. #if defined(_WIN32_WCE)
  9327. # define SQLITE_OS_WINCE 1
  9328. #else
  9329. # define SQLITE_OS_WINCE 0
  9330. #endif
  9331. /*
  9332. ** Determine if we are dealing with WinRT, which provides only a subset of
  9333. ** the full Win32 API.
  9334. */
  9335. #if !defined(SQLITE_OS_WINRT)
  9336. # define SQLITE_OS_WINRT 0
  9337. #endif
  9338. /* If the SET_FULLSYNC macro is not defined above, then make it
  9339. ** a no-op
  9340. */
  9341. #ifndef SET_FULLSYNC
  9342. # define SET_FULLSYNC(x,y)
  9343. #endif
  9344. /*
  9345. ** The default size of a disk sector
  9346. */
  9347. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9348. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9349. #endif
  9350. /*
  9351. ** Temporary files are named starting with this prefix followed by 16 random
  9352. ** alphanumeric characters, and no file extension. They are stored in the
  9353. ** OS's standard temporary file directory, and are deleted prior to exit.
  9354. ** If sqlite is being embedded in another program, you may wish to change the
  9355. ** prefix to reflect your program's name, so that if your program exits
  9356. ** prematurely, old temporary files can be easily identified. This can be done
  9357. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9358. **
  9359. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9360. ** Mcafee started using SQLite in their anti-virus product and it
  9361. ** started putting files with the "sqlite" name in the c:/temp folder.
  9362. ** This annoyed many windows users. Those users would then do a
  9363. ** Google search for "sqlite", find the telephone numbers of the
  9364. ** developers and call to wake them up at night and complain.
  9365. ** For this reason, the default name prefix is changed to be "sqlite"
  9366. ** spelled backwards. So the temp files are still identified, but
  9367. ** anybody smart enough to figure out the code is also likely smart
  9368. ** enough to know that calling the developer will not help get rid
  9369. ** of the file.
  9370. */
  9371. #ifndef SQLITE_TEMP_FILE_PREFIX
  9372. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9373. #endif
  9374. /*
  9375. ** The following values may be passed as the second argument to
  9376. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9377. **
  9378. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9379. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9380. ** any time. Other processes may hold and obtain new SHARED locks.
  9381. ** PENDING: A single process may hold a PENDING lock on a file at
  9382. ** any one time. Existing SHARED locks may persist, but no new
  9383. ** SHARED locks may be obtained by other processes.
  9384. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9385. **
  9386. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9387. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9388. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9389. ** sqlite3OsLock().
  9390. */
  9391. #define NO_LOCK 0
  9392. #define SHARED_LOCK 1
  9393. #define RESERVED_LOCK 2
  9394. #define PENDING_LOCK 3
  9395. #define EXCLUSIVE_LOCK 4
  9396. /*
  9397. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9398. **
  9399. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9400. ** those functions are not available. So we use only LockFile() and
  9401. ** UnlockFile().
  9402. **
  9403. ** LockFile() prevents not just writing but also reading by other processes.
  9404. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9405. ** byte out of a specific range of bytes. The lock byte is obtained at
  9406. ** random so two separate readers can probably access the file at the
  9407. ** same time, unless they are unlucky and choose the same lock byte.
  9408. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9409. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9410. ** a single byte of the file that is designated as the reserved lock byte.
  9411. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9412. ** the RESERVED_LOCK byte.
  9413. **
  9414. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9415. ** which means we can use reader/writer locks. When reader/writer locks
  9416. ** are used, the lock is placed on the same range of bytes that is used
  9417. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9418. ** will support two or more Win95 readers or two or more WinNT readers.
  9419. ** But a single Win95 reader will lock out all WinNT readers and a single
  9420. ** WinNT reader will lock out all other Win95 readers.
  9421. **
  9422. ** The following #defines specify the range of bytes used for locking.
  9423. ** SHARED_SIZE is the number of bytes available in the pool from which
  9424. ** a random byte is selected for a shared lock. The pool of bytes for
  9425. ** shared locks begins at SHARED_FIRST.
  9426. **
  9427. ** The same locking strategy and
  9428. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9429. ** clients on win95, winNT, and unix all talking to the same shared file
  9430. ** and all locking correctly. To do so would require that samba (or whatever
  9431. ** tool is being used for file sharing) implements locks correctly between
  9432. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9433. ** using the same locking range we are at least open to the possibility.
  9434. **
  9435. ** Locking in windows is manditory. For this reason, we cannot store
  9436. ** actual data in the bytes used for locking. The pager never allocates
  9437. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9438. ** that all locks will fit on a single page even at the minimum page size.
  9439. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9440. ** is set high so that we don't have to allocate an unused page except
  9441. ** for very large databases. But one should test the page skipping logic
  9442. ** by setting PENDING_BYTE low and running the entire regression suite.
  9443. **
  9444. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9445. ** file format. Depending on how it is changed, you might not notice
  9446. ** the incompatibility right away, even running a full regression test.
  9447. ** The default location of PENDING_BYTE is the first byte past the
  9448. ** 1GB boundary.
  9449. **
  9450. */
  9451. #ifdef SQLITE_OMIT_WSD
  9452. # define PENDING_BYTE (0x40000000)
  9453. #else
  9454. # define PENDING_BYTE sqlite3PendingByte
  9455. #endif
  9456. #define RESERVED_BYTE (PENDING_BYTE+1)
  9457. #define SHARED_FIRST (PENDING_BYTE+2)
  9458. #define SHARED_SIZE 510
  9459. /*
  9460. ** Wrapper around OS specific sqlite3_os_init() function.
  9461. */
  9462. SQLITE_PRIVATE int sqlite3OsInit(void);
  9463. /*
  9464. ** Functions for accessing sqlite3_file methods
  9465. */
  9466. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9467. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9468. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9469. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9470. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9471. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9472. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9473. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9474. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9475. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9476. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9477. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9478. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9479. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9480. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9481. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9482. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9483. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9484. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9485. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9486. /*
  9487. ** Functions for accessing sqlite3_vfs methods
  9488. */
  9489. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9490. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9491. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9492. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9493. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9494. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9495. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9496. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9497. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9498. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9499. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9500. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9501. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9502. /*
  9503. ** Convenience functions for opening and closing files using
  9504. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9505. */
  9506. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9507. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9508. #endif /* _SQLITE_OS_H_ */
  9509. /************** End of os.h **************************************************/
  9510. /************** Continuing where we left off in sqliteInt.h ******************/
  9511. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9512. /************** Begin file mutex.h *******************************************/
  9513. /*
  9514. ** 2007 August 28
  9515. **
  9516. ** The author disclaims copyright to this source code. In place of
  9517. ** a legal notice, here is a blessing:
  9518. **
  9519. ** May you do good and not evil.
  9520. ** May you find forgiveness for yourself and forgive others.
  9521. ** May you share freely, never taking more than you give.
  9522. **
  9523. *************************************************************************
  9524. **
  9525. ** This file contains the common header for all mutex implementations.
  9526. ** The sqliteInt.h header #includes this file so that it is available
  9527. ** to all source files. We break it out in an effort to keep the code
  9528. ** better organized.
  9529. **
  9530. ** NOTE: source files should *not* #include this header file directly.
  9531. ** Source files should #include the sqliteInt.h file and let that file
  9532. ** include this one indirectly.
  9533. */
  9534. /*
  9535. ** Figure out what version of the code to use. The choices are
  9536. **
  9537. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9538. ** mutexes implemention cannot be overridden
  9539. ** at start-time.
  9540. **
  9541. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9542. ** mutual exclusion is provided. But this
  9543. ** implementation can be overridden at
  9544. ** start-time.
  9545. **
  9546. ** SQLITE_MUTEX_RTT For multi_threaded applications on rt-thread.
  9547. **
  9548. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9549. **
  9550. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9551. */
  9552. #if !SQLITE_THREADSAFE
  9553. # define SQLITE_MUTEX_OMIT
  9554. #endif
  9555. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9556. # if SQLITE_OS_UNIX
  9557. # define SQLITE_MUTEX_PTHREADS
  9558. # elif SQLITE_OS_WIN
  9559. # define SQLITE_MUTEX_W32
  9560. # elif SQLITE_OS_RTT
  9561. # define SQLITE_MUTEX_RTT
  9562. # else
  9563. # define SQLITE_MUTEX_NOOP
  9564. # endif
  9565. #endif
  9566. #ifdef SQLITE_MUTEX_OMIT
  9567. /*
  9568. ** If this is a no-op implementation, implement everything as macros.
  9569. */
  9570. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9571. #define sqlite3_mutex_free(X)
  9572. #define sqlite3_mutex_enter(X)
  9573. #define sqlite3_mutex_try(X) SQLITE_OK
  9574. #define sqlite3_mutex_leave(X)
  9575. #define sqlite3_mutex_held(X) ((void)(X),1)
  9576. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9577. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9578. #define sqlite3MutexInit() SQLITE_OK
  9579. #define sqlite3MutexEnd()
  9580. #define MUTEX_LOGIC(X)
  9581. #else
  9582. #define MUTEX_LOGIC(X) X
  9583. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9584. /************** End of mutex.h ***********************************************/
  9585. /************** Continuing where we left off in sqliteInt.h ******************/
  9586. /*
  9587. ** Each database file to be accessed by the system is an instance
  9588. ** of the following structure. There are normally two of these structures
  9589. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9590. ** aDb[1] is the database file used to hold temporary tables. Additional
  9591. ** databases may be attached.
  9592. */
  9593. struct Db {
  9594. char *zName; /* Name of this database */
  9595. Btree *pBt; /* The B*Tree structure for this database file */
  9596. u8 safety_level; /* How aggressive at syncing data to disk */
  9597. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9598. };
  9599. /*
  9600. ** An instance of the following structure stores a database schema.
  9601. **
  9602. ** Most Schema objects are associated with a Btree. The exception is
  9603. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9604. ** In shared cache mode, a single Schema object can be shared by multiple
  9605. ** Btrees that refer to the same underlying BtShared object.
  9606. **
  9607. ** Schema objects are automatically deallocated when the last Btree that
  9608. ** references them is destroyed. The TEMP Schema is manually freed by
  9609. ** sqlite3_close().
  9610. *
  9611. ** A thread must be holding a mutex on the corresponding Btree in order
  9612. ** to access Schema content. This implies that the thread must also be
  9613. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9614. ** For a TEMP Schema, only the connection mutex is required.
  9615. */
  9616. struct Schema {
  9617. int schema_cookie; /* Database schema version number for this file */
  9618. int iGeneration; /* Generation counter. Incremented with each change */
  9619. Hash tblHash; /* All tables indexed by name */
  9620. Hash idxHash; /* All (named) indices indexed by name */
  9621. Hash trigHash; /* All triggers indexed by name */
  9622. Hash fkeyHash; /* All foreign keys by referenced table name */
  9623. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9624. u8 file_format; /* Schema format version for this file */
  9625. u8 enc; /* Text encoding used by this database */
  9626. u16 flags; /* Flags associated with this schema */
  9627. int cache_size; /* Number of pages to use in the cache */
  9628. };
  9629. /*
  9630. ** These macros can be used to test, set, or clear bits in the
  9631. ** Db.pSchema->flags field.
  9632. */
  9633. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9634. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9635. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9636. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9637. /*
  9638. ** Allowed values for the DB.pSchema->flags field.
  9639. **
  9640. ** The DB_SchemaLoaded flag is set after the database schema has been
  9641. ** read into internal hash tables.
  9642. **
  9643. ** DB_UnresetViews means that one or more views have column names that
  9644. ** have been filled out. If the schema changes, these column names might
  9645. ** changes and so the view will need to be reset.
  9646. */
  9647. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9648. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9649. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9650. /*
  9651. ** The number of different kinds of things that can be limited
  9652. ** using the sqlite3_limit() interface.
  9653. */
  9654. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9655. /*
  9656. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9657. ** to satisfy small transient memory allocation requests for objects
  9658. ** associated with a particular database connection. The use of
  9659. ** lookaside malloc provides a significant performance enhancement
  9660. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9661. ** SQL statements.
  9662. **
  9663. ** The Lookaside structure holds configuration information about the
  9664. ** lookaside malloc subsystem. Each available memory allocation in
  9665. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9666. ** objects.
  9667. **
  9668. ** Lookaside allocations are only allowed for objects that are associated
  9669. ** with a particular database connection. Hence, schema information cannot
  9670. ** be stored in lookaside because in shared cache mode the schema information
  9671. ** is shared by multiple database connections. Therefore, while parsing
  9672. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9673. ** lookaside allocations are not used to construct the schema objects.
  9674. */
  9675. struct Lookaside {
  9676. u16 sz; /* Size of each buffer in bytes */
  9677. u8 bEnabled; /* False to disable new lookaside allocations */
  9678. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9679. int nOut; /* Number of buffers currently checked out */
  9680. int mxOut; /* Highwater mark for nOut */
  9681. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9682. LookasideSlot *pFree; /* List of available buffers */
  9683. void *pStart; /* First byte of available memory space */
  9684. void *pEnd; /* First byte past end of available space */
  9685. };
  9686. struct LookasideSlot {
  9687. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9688. };
  9689. /*
  9690. ** A hash table for function definitions.
  9691. **
  9692. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9693. ** Collisions are on the FuncDef.pHash chain.
  9694. */
  9695. struct FuncDefHash {
  9696. FuncDef *a[23]; /* Hash table for functions */
  9697. };
  9698. /*
  9699. ** Each database connection is an instance of the following structure.
  9700. */
  9701. struct sqlite3 {
  9702. sqlite3_vfs *pVfs; /* OS Interface */
  9703. struct Vdbe *pVdbe; /* List of active virtual machines */
  9704. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9705. sqlite3_mutex *mutex; /* Connection mutex */
  9706. Db *aDb; /* All backends */
  9707. int nDb; /* Number of backends currently in use */
  9708. int flags; /* Miscellaneous flags. See below */
  9709. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9710. i64 szMmap; /* Default mmap_size setting */
  9711. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9712. int errCode; /* Most recent error code (SQLITE_*) */
  9713. int errMask; /* & result codes with this before returning */
  9714. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9715. u8 autoCommit; /* The auto-commit flag. */
  9716. u8 temp_store; /* 1: file 2: memory 0: default */
  9717. u8 mallocFailed; /* True if we have seen a malloc failure */
  9718. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9719. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9720. u8 suppressErr; /* Do not issue error messages if true */
  9721. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9722. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9723. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9724. u32 magic; /* Magic number for detect library misuse */
  9725. int nChange; /* Value returned by sqlite3_changes() */
  9726. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9727. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9728. struct sqlite3InitInfo { /* Information used during initialization */
  9729. int newTnum; /* Rootpage of table being initialized */
  9730. u8 iDb; /* Which db file is being initialized */
  9731. u8 busy; /* TRUE if currently initializing */
  9732. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9733. } init;
  9734. int nVdbeActive; /* Number of VDBEs currently running */
  9735. int nVdbeRead; /* Number of active VDBEs that read or write */
  9736. int nVdbeWrite; /* Number of active VDBEs that read and write */
  9737. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  9738. int nExtension; /* Number of loaded extensions */
  9739. void **aExtension; /* Array of shared library handles */
  9740. void (*xTrace)(void*,const char*); /* Trace function */
  9741. void *pTraceArg; /* Argument to the trace function */
  9742. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9743. void *pProfileArg; /* Argument to profile function */
  9744. void *pCommitArg; /* Argument to xCommitCallback() */
  9745. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9746. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9747. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9748. void *pUpdateArg;
  9749. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9750. #ifndef SQLITE_OMIT_WAL
  9751. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9752. void *pWalArg;
  9753. #endif
  9754. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9755. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9756. void *pCollNeededArg;
  9757. sqlite3_value *pErr; /* Most recent error message */
  9758. union {
  9759. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9760. double notUsed1; /* Spacer */
  9761. } u1;
  9762. Lookaside lookaside; /* Lookaside malloc configuration */
  9763. #ifndef SQLITE_OMIT_AUTHORIZATION
  9764. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9765. /* Access authorization function */
  9766. void *pAuthArg; /* 1st argument to the access auth function */
  9767. #endif
  9768. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9769. int (*xProgress)(void *); /* The progress callback */
  9770. void *pProgressArg; /* Argument to the progress callback */
  9771. unsigned nProgressOps; /* Number of opcodes for progress callback */
  9772. #endif
  9773. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9774. int nVTrans; /* Allocated size of aVTrans */
  9775. Hash aModule; /* populated by sqlite3_create_module() */
  9776. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9777. VTable **aVTrans; /* Virtual tables with open transactions */
  9778. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9779. #endif
  9780. FuncDefHash aFunc; /* Hash table of connection functions */
  9781. Hash aCollSeq; /* All collating sequences */
  9782. BusyHandler busyHandler; /* Busy callback */
  9783. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9784. Savepoint *pSavepoint; /* List of active savepoints */
  9785. int busyTimeout; /* Busy handler timeout, in msec */
  9786. int nSavepoint; /* Number of non-transaction savepoints */
  9787. int nStatement; /* Number of nested statement-transactions */
  9788. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9789. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  9790. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9791. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9792. /* The following variables are all protected by the STATIC_MASTER
  9793. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9794. **
  9795. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9796. ** unlock so that it can proceed.
  9797. **
  9798. ** When X.pBlockingConnection==Y, that means that something that X tried
  9799. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9800. ** held by Y.
  9801. */
  9802. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9803. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9804. void *pUnlockArg; /* Argument to xUnlockNotify */
  9805. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9806. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9807. #endif
  9808. };
  9809. /*
  9810. ** A macro to discover the encoding of a database.
  9811. */
  9812. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9813. /*
  9814. ** Possible values for the sqlite3.flags.
  9815. */
  9816. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9817. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9818. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  9819. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  9820. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  9821. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  9822. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  9823. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  9824. /* DELETE, or UPDATE and return */
  9825. /* the count using a callback. */
  9826. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  9827. /* result set is empty */
  9828. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  9829. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  9830. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  9831. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  9832. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  9833. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  9834. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  9835. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  9836. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  9837. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  9838. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  9839. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  9840. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  9841. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  9842. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  9843. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  9844. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  9845. /*
  9846. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9847. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9848. ** selectively disable various optimizations.
  9849. */
  9850. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9851. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9852. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9853. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9854. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9855. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9856. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9857. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9858. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9859. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  9860. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  9861. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  9862. #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
  9863. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9864. /*
  9865. ** Macros for testing whether or not optimizations are enabled or disabled.
  9866. */
  9867. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9868. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9869. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9870. #else
  9871. #define OptimizationDisabled(db, mask) 0
  9872. #define OptimizationEnabled(db, mask) 1
  9873. #endif
  9874. /*
  9875. ** Possible values for the sqlite.magic field.
  9876. ** The numbers are obtained at random and have no special meaning, other
  9877. ** than being distinct from one another.
  9878. */
  9879. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9880. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9881. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9882. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9883. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9884. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9885. /*
  9886. ** Each SQL function is defined by an instance of the following
  9887. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9888. ** hash table. When multiple functions have the same name, the hash table
  9889. ** points to a linked list of these structures.
  9890. */
  9891. struct FuncDef {
  9892. i16 nArg; /* Number of arguments. -1 means unlimited */
  9893. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  9894. void *pUserData; /* User data parameter */
  9895. FuncDef *pNext; /* Next function with same name */
  9896. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9897. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9898. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9899. char *zName; /* SQL name of the function. */
  9900. FuncDef *pHash; /* Next with a different name but the same hash */
  9901. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9902. };
  9903. /*
  9904. ** This structure encapsulates a user-function destructor callback (as
  9905. ** configured using create_function_v2()) and a reference counter. When
  9906. ** create_function_v2() is called to create a function with a destructor,
  9907. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9908. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9909. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9910. ** member of each of the new FuncDef objects is set to point to the allocated
  9911. ** FuncDestructor.
  9912. **
  9913. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9914. ** count on this object is decremented. When it reaches 0, the destructor
  9915. ** is invoked and the FuncDestructor structure freed.
  9916. */
  9917. struct FuncDestructor {
  9918. int nRef;
  9919. void (*xDestroy)(void *);
  9920. void *pUserData;
  9921. };
  9922. /*
  9923. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9924. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9925. ** are assert() statements in the code to verify this.
  9926. */
  9927. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  9928. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  9929. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  9930. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  9931. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  9932. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  9933. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  9934. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  9935. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  9936. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  9937. /*
  9938. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9939. ** used to create the initializers for the FuncDef structures.
  9940. **
  9941. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9942. ** Used to create a scalar function definition of a function zName
  9943. ** implemented by C function xFunc that accepts nArg arguments. The
  9944. ** value passed as iArg is cast to a (void*) and made available
  9945. ** as the user-data (sqlite3_user_data()) for the function. If
  9946. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9947. **
  9948. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9949. ** Used to create an aggregate function definition implemented by
  9950. ** the C functions xStep and xFinal. The first four parameters
  9951. ** are interpreted in the same way as the first 4 parameters to
  9952. ** FUNCTION().
  9953. **
  9954. ** LIKEFUNC(zName, nArg, pArg, flags)
  9955. ** Used to create a scalar function definition of a function zName
  9956. ** that accepts nArg arguments and is implemented by a call to C
  9957. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9958. ** available as the function user-data (sqlite3_user_data()). The
  9959. ** FuncDef.flags variable is set to the value passed as the flags
  9960. ** parameter.
  9961. */
  9962. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9963. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9964. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9965. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  9966. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  9967. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9968. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9969. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9970. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9971. #define LIKEFUNC(zName, nArg, arg, flags) \
  9972. {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9973. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9974. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  9975. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9976. /*
  9977. ** All current savepoints are stored in a linked list starting at
  9978. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9979. ** opened savepoint. Savepoints are added to the list by the vdbe
  9980. ** OP_Savepoint instruction.
  9981. */
  9982. struct Savepoint {
  9983. char *zName; /* Savepoint name (nul-terminated) */
  9984. i64 nDeferredCons; /* Number of deferred fk violations */
  9985. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  9986. Savepoint *pNext; /* Parent savepoint (if any) */
  9987. };
  9988. /*
  9989. ** The following are used as the second parameter to sqlite3Savepoint(),
  9990. ** and as the P1 argument to the OP_Savepoint instruction.
  9991. */
  9992. #define SAVEPOINT_BEGIN 0
  9993. #define SAVEPOINT_RELEASE 1
  9994. #define SAVEPOINT_ROLLBACK 2
  9995. /*
  9996. ** Each SQLite module (virtual table definition) is defined by an
  9997. ** instance of the following structure, stored in the sqlite3.aModule
  9998. ** hash table.
  9999. */
  10000. struct Module {
  10001. const sqlite3_module *pModule; /* Callback pointers */
  10002. const char *zName; /* Name passed to create_module() */
  10003. void *pAux; /* pAux passed to create_module() */
  10004. void (*xDestroy)(void *); /* Module destructor function */
  10005. };
  10006. /*
  10007. ** information about each column of an SQL table is held in an instance
  10008. ** of this structure.
  10009. */
  10010. struct Column {
  10011. char *zName; /* Name of this column */
  10012. Expr *pDflt; /* Default value of this column */
  10013. char *zDflt; /* Original text of the default value */
  10014. char *zType; /* Data type for this column */
  10015. char *zColl; /* Collating sequence. If NULL, use the default */
  10016. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10017. char affinity; /* One of the SQLITE_AFF_... values */
  10018. u8 szEst; /* Estimated size of this column. INT==1 */
  10019. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10020. };
  10021. /* Allowed values for Column.colFlags:
  10022. */
  10023. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10024. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10025. /*
  10026. ** A "Collating Sequence" is defined by an instance of the following
  10027. ** structure. Conceptually, a collating sequence consists of a name and
  10028. ** a comparison routine that defines the order of that sequence.
  10029. **
  10030. ** If CollSeq.xCmp is NULL, it means that the
  10031. ** collating sequence is undefined. Indices built on an undefined
  10032. ** collating sequence may not be read or written.
  10033. */
  10034. struct CollSeq {
  10035. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10036. u8 enc; /* Text encoding handled by xCmp() */
  10037. void *pUser; /* First argument to xCmp() */
  10038. int (*xCmp)(void*,int, const void*, int, const void*);
  10039. void (*xDel)(void*); /* Destructor for pUser */
  10040. };
  10041. /*
  10042. ** A sort order can be either ASC or DESC.
  10043. */
  10044. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10045. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10046. /*
  10047. ** Column affinity types.
  10048. **
  10049. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10050. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10051. ** the speed a little by numbering the values consecutively.
  10052. **
  10053. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  10054. ** when multiple affinity types are concatenated into a string and
  10055. ** used as the P4 operand, they will be more readable.
  10056. **
  10057. ** Note also that the numeric types are grouped together so that testing
  10058. ** for a numeric type is a single comparison.
  10059. */
  10060. #define SQLITE_AFF_TEXT 'a'
  10061. #define SQLITE_AFF_NONE 'b'
  10062. #define SQLITE_AFF_NUMERIC 'c'
  10063. #define SQLITE_AFF_INTEGER 'd'
  10064. #define SQLITE_AFF_REAL 'e'
  10065. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10066. /*
  10067. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10068. ** affinity value.
  10069. */
  10070. #define SQLITE_AFF_MASK 0x67
  10071. /*
  10072. ** Additional bit values that can be ORed with an affinity without
  10073. ** changing the affinity.
  10074. */
  10075. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  10076. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  10077. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10078. /*
  10079. ** An object of this type is created for each virtual table present in
  10080. ** the database schema.
  10081. **
  10082. ** If the database schema is shared, then there is one instance of this
  10083. ** structure for each database connection (sqlite3*) that uses the shared
  10084. ** schema. This is because each database connection requires its own unique
  10085. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10086. ** implementation. sqlite3_vtab* handles can not be shared between
  10087. ** database connections, even when the rest of the in-memory database
  10088. ** schema is shared, as the implementation often stores the database
  10089. ** connection handle passed to it via the xConnect() or xCreate() method
  10090. ** during initialization internally. This database connection handle may
  10091. ** then be used by the virtual table implementation to access real tables
  10092. ** within the database. So that they appear as part of the callers
  10093. ** transaction, these accesses need to be made via the same database
  10094. ** connection as that used to execute SQL operations on the virtual table.
  10095. **
  10096. ** All VTable objects that correspond to a single table in a shared
  10097. ** database schema are initially stored in a linked-list pointed to by
  10098. ** the Table.pVTable member variable of the corresponding Table object.
  10099. ** When an sqlite3_prepare() operation is required to access the virtual
  10100. ** table, it searches the list for the VTable that corresponds to the
  10101. ** database connection doing the preparing so as to use the correct
  10102. ** sqlite3_vtab* handle in the compiled query.
  10103. **
  10104. ** When an in-memory Table object is deleted (for example when the
  10105. ** schema is being reloaded for some reason), the VTable objects are not
  10106. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10107. ** immediately. Instead, they are moved from the Table.pVTable list to
  10108. ** another linked list headed by the sqlite3.pDisconnect member of the
  10109. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10110. ** next time a statement is prepared using said sqlite3*. This is done
  10111. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10112. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10113. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10114. ** list without holding the corresponding sqlite3.mutex mutex.
  10115. **
  10116. ** The memory for objects of this type is always allocated by
  10117. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10118. ** the first argument.
  10119. */
  10120. struct VTable {
  10121. sqlite3 *db; /* Database connection associated with this table */
  10122. Module *pMod; /* Pointer to module implementation */
  10123. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10124. int nRef; /* Number of pointers to this structure */
  10125. u8 bConstraint; /* True if constraints are supported */
  10126. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10127. VTable *pNext; /* Next in linked list (see above) */
  10128. };
  10129. /*
  10130. ** Each SQL table is represented in memory by an instance of the
  10131. ** following structure.
  10132. **
  10133. ** Table.zName is the name of the table. The case of the original
  10134. ** CREATE TABLE statement is stored, but case is not significant for
  10135. ** comparisons.
  10136. **
  10137. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10138. ** pointer to an array of Column structures, one for each column.
  10139. **
  10140. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10141. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10142. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10143. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10144. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10145. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10146. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10147. **
  10148. ** Table.tnum is the page number for the root BTree page of the table in the
  10149. ** database file. If Table.iDb is the index of the database table backend
  10150. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10151. ** holds temporary tables and indices. If TF_Ephemeral is set
  10152. ** then the table is stored in a file that is automatically deleted
  10153. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10154. ** refers VDBE cursor number that holds the table open, not to the root
  10155. ** page number. Transient tables are used to hold the results of a
  10156. ** sub-query that appears instead of a real table name in the FROM clause
  10157. ** of a SELECT statement.
  10158. */
  10159. struct Table {
  10160. char *zName; /* Name of the table or view */
  10161. Column *aCol; /* Information about each column */
  10162. Index *pIndex; /* List of SQL indexes on this table. */
  10163. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10164. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10165. char *zColAff; /* String defining the affinity of each column */
  10166. #ifndef SQLITE_OMIT_CHECK
  10167. ExprList *pCheck; /* All CHECK constraints */
  10168. #endif
  10169. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  10170. int tnum; /* Root BTree node for this table (see note above) */
  10171. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10172. i16 nCol; /* Number of columns in this table */
  10173. u16 nRef; /* Number of pointers to this Table */
  10174. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10175. u8 tabFlags; /* Mask of TF_* values */
  10176. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10177. #ifndef SQLITE_OMIT_ALTERTABLE
  10178. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10179. #endif
  10180. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10181. int nModuleArg; /* Number of arguments to the module */
  10182. char **azModuleArg; /* Text of all module args. [0] is module name */
  10183. VTable *pVTable; /* List of VTable objects. */
  10184. #endif
  10185. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10186. Schema *pSchema; /* Schema that contains this table */
  10187. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10188. };
  10189. /*
  10190. ** Allowed values for Tabe.tabFlags.
  10191. */
  10192. #define TF_Readonly 0x01 /* Read-only system table */
  10193. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10194. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10195. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10196. #define TF_Virtual 0x10 /* Is a virtual table */
  10197. /*
  10198. ** Test to see whether or not a table is a virtual table. This is
  10199. ** done as a macro so that it will be optimized out when virtual
  10200. ** table support is omitted from the build.
  10201. */
  10202. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10203. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10204. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10205. #else
  10206. # define IsVirtual(X) 0
  10207. # define IsHiddenColumn(X) 0
  10208. #endif
  10209. /*
  10210. ** Each foreign key constraint is an instance of the following structure.
  10211. **
  10212. ** A foreign key is associated with two tables. The "from" table is
  10213. ** the table that contains the REFERENCES clause that creates the foreign
  10214. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10215. ** Consider this example:
  10216. **
  10217. ** CREATE TABLE ex1(
  10218. ** a INTEGER PRIMARY KEY,
  10219. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10220. ** );
  10221. **
  10222. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10223. **
  10224. ** Each REFERENCES clause generates an instance of the following structure
  10225. ** which is attached to the from-table. The to-table need not exist when
  10226. ** the from-table is created. The existence of the to-table is not checked.
  10227. */
  10228. struct FKey {
  10229. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10230. FKey *pNextFrom; /* Next foreign key in pFrom */
  10231. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10232. FKey *pNextTo; /* Next foreign key on table named zTo */
  10233. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  10234. int nCol; /* Number of columns in this key */
  10235. /* EV: R-30323-21917 */
  10236. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10237. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10238. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10239. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10240. int iFrom; /* Index of column in pFrom */
  10241. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10242. } aCol[1]; /* One entry for each of nCol column s */
  10243. };
  10244. /*
  10245. ** SQLite supports many different ways to resolve a constraint
  10246. ** error. ROLLBACK processing means that a constraint violation
  10247. ** causes the operation in process to fail and for the current transaction
  10248. ** to be rolled back. ABORT processing means the operation in process
  10249. ** fails and any prior changes from that one operation are backed out,
  10250. ** but the transaction is not rolled back. FAIL processing means that
  10251. ** the operation in progress stops and returns an error code. But prior
  10252. ** changes due to the same operation are not backed out and no rollback
  10253. ** occurs. IGNORE means that the particular row that caused the constraint
  10254. ** error is not inserted or updated. Processing continues and no error
  10255. ** is returned. REPLACE means that preexisting database rows that caused
  10256. ** a UNIQUE constraint violation are removed so that the new insert or
  10257. ** update can proceed. Processing continues and no error is reported.
  10258. **
  10259. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10260. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10261. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10262. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10263. ** referenced table row is propagated into the row that holds the
  10264. ** foreign key.
  10265. **
  10266. ** The following symbolic values are used to record which type
  10267. ** of action to take.
  10268. */
  10269. #define OE_None 0 /* There is no constraint to check */
  10270. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10271. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10272. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10273. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10274. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10275. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10276. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10277. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10278. #define OE_Cascade 9 /* Cascade the changes */
  10279. #define OE_Default 10 /* Do whatever the default action is */
  10280. /*
  10281. ** An instance of the following structure is passed as the first
  10282. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10283. ** comparison of the two index keys.
  10284. **
  10285. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10286. ** are nField slots for the columns of an index then one extra slot
  10287. ** for the rowid at the end.
  10288. */
  10289. struct KeyInfo {
  10290. sqlite3 *db; /* The database connection */
  10291. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10292. u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
  10293. u8 *aSortOrder; /* Sort order for each column. */
  10294. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10295. };
  10296. /*
  10297. ** An instance of the following structure holds information about a
  10298. ** single index record that has already been parsed out into individual
  10299. ** values.
  10300. **
  10301. ** A record is an object that contains one or more fields of data.
  10302. ** Records are used to store the content of a table row and to store
  10303. ** the key of an index. A blob encoding of a record is created by
  10304. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10305. ** OP_Column opcode.
  10306. **
  10307. ** This structure holds a record that has already been disassembled
  10308. ** into its constituent fields.
  10309. */
  10310. struct UnpackedRecord {
  10311. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10312. u16 nField; /* Number of entries in apMem[] */
  10313. u8 flags; /* Boolean settings. UNPACKED_... below */
  10314. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10315. Mem *aMem; /* Values */
  10316. };
  10317. /*
  10318. ** Allowed values of UnpackedRecord.flags
  10319. */
  10320. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10321. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10322. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10323. /*
  10324. ** Each SQL index is represented in memory by an
  10325. ** instance of the following structure.
  10326. **
  10327. ** The columns of the table that are to be indexed are described
  10328. ** by the aiColumn[] field of this structure. For example, suppose
  10329. ** we have the following table and index:
  10330. **
  10331. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10332. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10333. **
  10334. ** In the Table structure describing Ex1, nCol==3 because there are
  10335. ** three columns in the table. In the Index structure describing
  10336. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10337. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10338. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10339. ** The second column to be indexed (c1) has an index of 0 in
  10340. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10341. **
  10342. ** The Index.onError field determines whether or not the indexed columns
  10343. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10344. ** it means this is not a unique index. Otherwise it is a unique index
  10345. ** and the value of Index.onError indicate the which conflict resolution
  10346. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10347. ** element.
  10348. */
  10349. struct Index {
  10350. char *zName; /* Name of this index */
  10351. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10352. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  10353. Table *pTable; /* The SQL table being indexed */
  10354. char *zColAff; /* String defining the affinity of each column */
  10355. Index *pNext; /* The next index associated with the same table */
  10356. Schema *pSchema; /* Schema containing this index */
  10357. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10358. char **azColl; /* Array of collation sequence names for index */
  10359. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10360. int tnum; /* DB Page containing root of this index */
  10361. LogEst szIdxRow; /* Estimated average row size in bytes */
  10362. u16 nColumn; /* Number of columns in table used by this index */
  10363. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10364. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10365. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10366. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10367. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10368. int nSample; /* Number of elements in aSample[] */
  10369. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10370. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10371. IndexSample *aSample; /* Samples of the left-most key */
  10372. #endif
  10373. };
  10374. /*
  10375. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10376. ** using a structure of this type. See documentation at the top of the
  10377. ** analyze.c source file for additional information.
  10378. */
  10379. struct IndexSample {
  10380. void *p; /* Pointer to sampled record */
  10381. int n; /* Size of record in bytes */
  10382. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10383. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10384. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10385. };
  10386. /*
  10387. ** Each token coming out of the lexer is an instance of
  10388. ** this structure. Tokens are also used as part of an expression.
  10389. **
  10390. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10391. ** may contain random values. Do not make any assumptions about Token.dyn
  10392. ** and Token.n when Token.z==0.
  10393. */
  10394. struct Token {
  10395. const char *z; /* Text of the token. Not NULL-terminated! */
  10396. unsigned int n; /* Number of characters in this token */
  10397. };
  10398. /*
  10399. ** An instance of this structure contains information needed to generate
  10400. ** code for a SELECT that contains aggregate functions.
  10401. **
  10402. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10403. ** pointer to this structure. The Expr.iColumn field is the index in
  10404. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10405. ** code for that node.
  10406. **
  10407. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10408. ** original Select structure that describes the SELECT statement. These
  10409. ** fields do not need to be freed when deallocating the AggInfo structure.
  10410. */
  10411. struct AggInfo {
  10412. u8 directMode; /* Direct rendering mode means take data directly
  10413. ** from source tables rather than from accumulators */
  10414. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10415. ** than the source table */
  10416. int sortingIdx; /* Cursor number of the sorting index */
  10417. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10418. int nSortingColumn; /* Number of columns in the sorting index */
  10419. ExprList *pGroupBy; /* The group by clause */
  10420. struct AggInfo_col { /* For each column used in source tables */
  10421. Table *pTab; /* Source table */
  10422. int iTable; /* Cursor number of the source table */
  10423. int iColumn; /* Column number within the source table */
  10424. int iSorterColumn; /* Column number in the sorting index */
  10425. int iMem; /* Memory location that acts as accumulator */
  10426. Expr *pExpr; /* The original expression */
  10427. } *aCol;
  10428. int nColumn; /* Number of used entries in aCol[] */
  10429. int nAccumulator; /* Number of columns that show through to the output.
  10430. ** Additional columns are used only as parameters to
  10431. ** aggregate functions */
  10432. struct AggInfo_func { /* For each aggregate function */
  10433. Expr *pExpr; /* Expression encoding the function */
  10434. FuncDef *pFunc; /* The aggregate function implementation */
  10435. int iMem; /* Memory location that acts as accumulator */
  10436. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10437. } *aFunc;
  10438. int nFunc; /* Number of entries in aFunc[] */
  10439. };
  10440. /*
  10441. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10442. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10443. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10444. ** it uses less memory in the Expr object, which is a big memory user
  10445. ** in systems with lots of prepared statements. And few applications
  10446. ** need more than about 10 or 20 variables. But some extreme users want
  10447. ** to have prepared statements with over 32767 variables, and for them
  10448. ** the option is available (at compile-time).
  10449. */
  10450. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10451. typedef i16 ynVar;
  10452. #else
  10453. typedef int ynVar;
  10454. #endif
  10455. /*
  10456. ** Each node of an expression in the parse tree is an instance
  10457. ** of this structure.
  10458. **
  10459. ** Expr.op is the opcode. The integer parser token codes are reused
  10460. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10461. ** code representing the ">=" operator. This same integer code is reused
  10462. ** to represent the greater-than-or-equal-to operator in the expression
  10463. ** tree.
  10464. **
  10465. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10466. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10467. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10468. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10469. ** then Expr.token contains the name of the function.
  10470. **
  10471. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10472. ** binary operator. Either or both may be NULL.
  10473. **
  10474. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10475. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10476. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10477. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10478. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10479. ** valid.
  10480. **
  10481. ** An expression of the form ID or ID.ID refers to a column in a table.
  10482. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10483. ** the integer cursor number of a VDBE cursor pointing to that table and
  10484. ** Expr.iColumn is the column number for the specific column. If the
  10485. ** expression is used as a result in an aggregate SELECT, then the
  10486. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10487. ** it can be accessed after all aggregates are computed.
  10488. **
  10489. ** If the expression is an unbound variable marker (a question mark
  10490. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10491. ** number for that variable.
  10492. **
  10493. ** If the expression is a subquery then Expr.iColumn holds an integer
  10494. ** register number containing the result of the subquery. If the
  10495. ** subquery gives a constant result, then iTable is -1. If the subquery
  10496. ** gives a different answer at different times during statement processing
  10497. ** then iTable is the address of a subroutine that computes the subquery.
  10498. **
  10499. ** If the Expr is of type OP_Column, and the table it is selecting from
  10500. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10501. ** corresponding table definition.
  10502. **
  10503. ** ALLOCATION NOTES:
  10504. **
  10505. ** Expr objects can use a lot of memory space in database schema. To
  10506. ** help reduce memory requirements, sometimes an Expr object will be
  10507. ** truncated. And to reduce the number of memory allocations, sometimes
  10508. ** two or more Expr objects will be stored in a single memory allocation,
  10509. ** together with Expr.zToken strings.
  10510. **
  10511. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10512. ** an Expr object is truncated. When EP_Reduced is set, then all
  10513. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10514. ** are contained within the same memory allocation. Note, however, that
  10515. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10516. ** allocated, regardless of whether or not EP_Reduced is set.
  10517. */
  10518. struct Expr {
  10519. u8 op; /* Operation performed by this node */
  10520. char affinity; /* The affinity of the column or 0 if not a column */
  10521. u32 flags; /* Various flags. EP_* See below */
  10522. union {
  10523. char *zToken; /* Token value. Zero terminated and dequoted */
  10524. int iValue; /* Non-negative integer value if EP_IntValue */
  10525. } u;
  10526. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10527. ** space is allocated for the fields below this point. An attempt to
  10528. ** access them will result in a segfault or malfunction.
  10529. *********************************************************************/
  10530. Expr *pLeft; /* Left subnode */
  10531. Expr *pRight; /* Right subnode */
  10532. union {
  10533. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  10534. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  10535. } x;
  10536. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10537. ** space is allocated for the fields below this point. An attempt to
  10538. ** access them will result in a segfault or malfunction.
  10539. *********************************************************************/
  10540. #if SQLITE_MAX_EXPR_DEPTH>0
  10541. int nHeight; /* Height of the tree headed by this node */
  10542. #endif
  10543. int iTable; /* TK_COLUMN: cursor number of table holding column
  10544. ** TK_REGISTER: register number
  10545. ** TK_TRIGGER: 1 -> new, 0 -> old
  10546. ** EP_Unlikely: 1000 times likelihood */
  10547. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10548. ** TK_VARIABLE: variable number (always >= 1). */
  10549. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10550. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10551. u8 op2; /* TK_REGISTER: original value of Expr.op
  10552. ** TK_COLUMN: the value of p5 for OP_Column
  10553. ** TK_AGG_FUNCTION: nesting depth */
  10554. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10555. Table *pTab; /* Table for TK_COLUMN expressions. */
  10556. };
  10557. /*
  10558. ** The following are the meanings of bits in the Expr.flags field.
  10559. */
  10560. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  10561. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  10562. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  10563. #define EP_Error 0x000008 /* Expression contains one or more errors */
  10564. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  10565. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  10566. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  10567. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  10568. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
  10569. #define EP_FixedDest 0x000200 /* Result needed in a specific register */
  10570. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  10571. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  10572. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  10573. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  10574. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  10575. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  10576. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  10577. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  10578. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  10579. /*
  10580. ** These macros can be used to test, set, or clear bits in the
  10581. ** Expr.flags field.
  10582. */
  10583. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  10584. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  10585. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10586. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10587. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  10588. ** and Accreditation only. It works like ExprSetProperty() during VVA
  10589. ** processes but is a no-op for delivery.
  10590. */
  10591. #ifdef SQLITE_DEBUG
  10592. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  10593. #else
  10594. # define ExprSetVVAProperty(E,P)
  10595. #endif
  10596. /*
  10597. ** Macros to determine the number of bytes required by a normal Expr
  10598. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10599. ** and an Expr struct with the EP_TokenOnly flag set.
  10600. */
  10601. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10602. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10603. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10604. /*
  10605. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10606. ** above sqlite3ExprDup() for details.
  10607. */
  10608. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10609. /*
  10610. ** A list of expressions. Each expression may optionally have a
  10611. ** name. An expr/name combination can be used in several ways, such
  10612. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10613. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10614. ** also be used as the argument to a function, in which case the a.zName
  10615. ** field is not used.
  10616. **
  10617. ** By default the Expr.zSpan field holds a human-readable description of
  10618. ** the expression that is used in the generation of error messages and
  10619. ** column labels. In this case, Expr.zSpan is typically the text of a
  10620. ** column expression as it exists in a SELECT statement. However, if
  10621. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  10622. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  10623. ** form is used for name resolution with nested FROM clauses.
  10624. */
  10625. struct ExprList {
  10626. int nExpr; /* Number of expressions on the list */
  10627. int iECursor; /* VDBE Cursor associated with this ExprList */
  10628. struct ExprList_item { /* For each expression in the list */
  10629. Expr *pExpr; /* The list of expressions */
  10630. char *zName; /* Token associated with this expression */
  10631. char *zSpan; /* Original text of the expression */
  10632. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10633. unsigned done :1; /* A flag to indicate when processing is finished */
  10634. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  10635. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10636. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10637. } *a; /* Alloc a power of two greater or equal to nExpr */
  10638. };
  10639. /*
  10640. ** An instance of this structure is used by the parser to record both
  10641. ** the parse tree for an expression and the span of input text for an
  10642. ** expression.
  10643. */
  10644. struct ExprSpan {
  10645. Expr *pExpr; /* The expression parse tree */
  10646. const char *zStart; /* First character of input text */
  10647. const char *zEnd; /* One character past the end of input text */
  10648. };
  10649. /*
  10650. ** An instance of this structure can hold a simple list of identifiers,
  10651. ** such as the list "a,b,c" in the following statements:
  10652. **
  10653. ** INSERT INTO t(a,b,c) VALUES ...;
  10654. ** CREATE INDEX idx ON t(a,b,c);
  10655. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10656. **
  10657. ** The IdList.a.idx field is used when the IdList represents the list of
  10658. ** column names after a table name in an INSERT statement. In the statement
  10659. **
  10660. ** INSERT INTO t(a,b,c) ...
  10661. **
  10662. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10663. */
  10664. struct IdList {
  10665. struct IdList_item {
  10666. char *zName; /* Name of the identifier */
  10667. int idx; /* Index in some Table.aCol[] of a column named zName */
  10668. } *a;
  10669. int nId; /* Number of identifiers on the list */
  10670. };
  10671. /*
  10672. ** The bitmask datatype defined below is used for various optimizations.
  10673. **
  10674. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10675. ** tables in a join to 32 instead of 64. But it also reduces the size
  10676. ** of the library by 738 bytes on ix86.
  10677. */
  10678. typedef u64 Bitmask;
  10679. /*
  10680. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10681. */
  10682. #define BMS ((int)(sizeof(Bitmask)*8))
  10683. /*
  10684. ** A bit in a Bitmask
  10685. */
  10686. #define MASKBIT(n) (((Bitmask)1)<<(n))
  10687. /*
  10688. ** The following structure describes the FROM clause of a SELECT statement.
  10689. ** Each table or subquery in the FROM clause is a separate element of
  10690. ** the SrcList.a[] array.
  10691. **
  10692. ** With the addition of multiple database support, the following structure
  10693. ** can also be used to describe a particular table such as the table that
  10694. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10695. ** such a table must be a simple name: ID. But in SQLite, the table can
  10696. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10697. **
  10698. ** The jointype starts out showing the join type between the current table
  10699. ** and the next table on the list. The parser builds the list this way.
  10700. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10701. ** jointype expresses the join between the table and the previous table.
  10702. **
  10703. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10704. ** contains more than 63 columns and the 64-th or later column is used.
  10705. */
  10706. struct SrcList {
  10707. u8 nSrc; /* Number of tables or subqueries in the FROM clause */
  10708. u8 nAlloc; /* Number of entries allocated in a[] below */
  10709. struct SrcList_item {
  10710. Schema *pSchema; /* Schema to which this item is fixed */
  10711. char *zDatabase; /* Name of database holding this table */
  10712. char *zName; /* Name of the table */
  10713. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10714. Table *pTab; /* An SQL table corresponding to zName */
  10715. Select *pSelect; /* A SELECT statement used in place of a table name */
  10716. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10717. int regReturn; /* Register holding return address of addrFillSub */
  10718. u8 jointype; /* Type of join between this able and the previous */
  10719. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10720. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10721. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10722. #ifndef SQLITE_OMIT_EXPLAIN
  10723. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10724. #endif
  10725. int iCursor; /* The VDBE cursor number used to access this table */
  10726. Expr *pOn; /* The ON clause of a join */
  10727. IdList *pUsing; /* The USING clause of a join */
  10728. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10729. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10730. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10731. } a[1]; /* One entry for each identifier on the list */
  10732. };
  10733. /*
  10734. ** Permitted values of the SrcList.a.jointype field
  10735. */
  10736. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10737. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10738. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10739. #define JT_LEFT 0x0008 /* Left outer join */
  10740. #define JT_RIGHT 0x0010 /* Right outer join */
  10741. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10742. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10743. /*
  10744. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10745. ** and the WhereInfo.wctrlFlags member.
  10746. */
  10747. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10748. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10749. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10750. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10751. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10752. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10753. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10754. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10755. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10756. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  10757. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  10758. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  10759. /* Allowed return values from sqlite3WhereIsDistinct()
  10760. */
  10761. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  10762. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  10763. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  10764. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  10765. /*
  10766. ** A NameContext defines a context in which to resolve table and column
  10767. ** names. The context consists of a list of tables (the pSrcList) field and
  10768. ** a list of named expression (pEList). The named expression list may
  10769. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10770. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10771. ** pEList corresponds to the result set of a SELECT and is NULL for
  10772. ** other statements.
  10773. **
  10774. ** NameContexts can be nested. When resolving names, the inner-most
  10775. ** context is searched first. If no match is found, the next outer
  10776. ** context is checked. If there is still no match, the next context
  10777. ** is checked. This process continues until either a match is found
  10778. ** or all contexts are check. When a match is found, the nRef member of
  10779. ** the context containing the match is incremented.
  10780. **
  10781. ** Each subquery gets a new NameContext. The pNext field points to the
  10782. ** NameContext in the parent query. Thus the process of scanning the
  10783. ** NameContext list corresponds to searching through successively outer
  10784. ** subqueries looking for a match.
  10785. */
  10786. struct NameContext {
  10787. Parse *pParse; /* The parser */
  10788. SrcList *pSrcList; /* One or more tables used to resolve names */
  10789. ExprList *pEList; /* Optional list of result-set columns */
  10790. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10791. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10792. int nRef; /* Number of names resolved by this context */
  10793. int nErr; /* Number of errors encountered while resolving names */
  10794. u8 ncFlags; /* Zero or more NC_* flags defined below */
  10795. };
  10796. /*
  10797. ** Allowed values for the NameContext, ncFlags field.
  10798. */
  10799. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  10800. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  10801. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  10802. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  10803. #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
  10804. /*
  10805. ** An instance of the following structure contains all information
  10806. ** needed to generate code for a single SELECT statement.
  10807. **
  10808. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10809. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10810. ** limit and nOffset to the value of the offset (or 0 if there is not
  10811. ** offset). But later on, nLimit and nOffset become the memory locations
  10812. ** in the VDBE that record the limit and offset counters.
  10813. **
  10814. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10815. ** These addresses must be stored so that we can go back and fill in
  10816. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10817. ** the number of columns in P2 can be computed at the same time
  10818. ** as the OP_OpenEphm instruction is coded because not
  10819. ** enough information about the compound query is known at that point.
  10820. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10821. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10822. ** sequences for the ORDER BY clause.
  10823. */
  10824. struct Select {
  10825. ExprList *pEList; /* The fields of the result */
  10826. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10827. u16 selFlags; /* Various SF_* values */
  10828. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10829. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10830. u64 nSelectRow; /* Estimated number of result rows */
  10831. SrcList *pSrc; /* The FROM clause */
  10832. Expr *pWhere; /* The WHERE clause */
  10833. ExprList *pGroupBy; /* The GROUP BY clause */
  10834. Expr *pHaving; /* The HAVING clause */
  10835. ExprList *pOrderBy; /* The ORDER BY clause */
  10836. Select *pPrior; /* Prior select in a compound select statement */
  10837. Select *pNext; /* Next select to the left in a compound */
  10838. Select *pRightmost; /* Right-most select in a compound select statement */
  10839. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10840. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10841. };
  10842. /*
  10843. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10844. ** "Select Flag".
  10845. */
  10846. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10847. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10848. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10849. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10850. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10851. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10852. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10853. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10854. #define SF_Materialize 0x0100 /* Force materialization of views */
  10855. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  10856. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  10857. /*
  10858. ** The results of a select can be distributed in several ways. The
  10859. ** "SRT" prefix means "SELECT Result Type".
  10860. */
  10861. #define SRT_Union 1 /* Store result as keys in an index */
  10862. #define SRT_Except 2 /* Remove result from a UNION index */
  10863. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10864. #define SRT_Discard 4 /* Do not save the results anywhere */
  10865. /* The ORDER BY clause is ignored for all of the above */
  10866. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10867. #define SRT_Output 5 /* Output each row of result */
  10868. #define SRT_Mem 6 /* Store result in a memory cell */
  10869. #define SRT_Set 7 /* Store results as keys in an index */
  10870. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10871. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10872. #define SRT_Coroutine 10 /* Generate a single row of result */
  10873. /*
  10874. ** An instance of this object describes where to put of the results of
  10875. ** a SELECT statement.
  10876. */
  10877. struct SelectDest {
  10878. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  10879. char affSdst; /* Affinity used when eDest==SRT_Set */
  10880. int iSDParm; /* A parameter used by the eDest disposal method */
  10881. int iSdst; /* Base register where results are written */
  10882. int nSdst; /* Number of registers allocated */
  10883. };
  10884. /*
  10885. ** During code generation of statements that do inserts into AUTOINCREMENT
  10886. ** tables, the following information is attached to the Table.u.autoInc.p
  10887. ** pointer of each autoincrement table to record some side information that
  10888. ** the code generator needs. We have to keep per-table autoincrement
  10889. ** information in case inserts are down within triggers. Triggers do not
  10890. ** normally coordinate their activities, but we do need to coordinate the
  10891. ** loading and saving of autoincrement information.
  10892. */
  10893. struct AutoincInfo {
  10894. AutoincInfo *pNext; /* Next info block in a list of them all */
  10895. Table *pTab; /* Table this info block refers to */
  10896. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10897. int regCtr; /* Memory register holding the rowid counter */
  10898. };
  10899. /*
  10900. ** Size of the column cache
  10901. */
  10902. #ifndef SQLITE_N_COLCACHE
  10903. # define SQLITE_N_COLCACHE 10
  10904. #endif
  10905. /*
  10906. ** At least one instance of the following structure is created for each
  10907. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10908. ** statement. All such objects are stored in the linked list headed at
  10909. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10910. ** completed.
  10911. **
  10912. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10913. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10914. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10915. ** The Parse.pTriggerPrg list never contains two entries with the same
  10916. ** values for both pTrigger and orconf.
  10917. **
  10918. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10919. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10920. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10921. ** a mask of new.* columns used by the program.
  10922. */
  10923. struct TriggerPrg {
  10924. Trigger *pTrigger; /* Trigger this program was coded from */
  10925. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10926. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10927. int orconf; /* Default ON CONFLICT policy */
  10928. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10929. };
  10930. /*
  10931. ** The yDbMask datatype for the bitmask of all attached databases.
  10932. */
  10933. #if SQLITE_MAX_ATTACHED>30
  10934. typedef sqlite3_uint64 yDbMask;
  10935. #else
  10936. typedef unsigned int yDbMask;
  10937. #endif
  10938. /*
  10939. ** An SQL parser context. A copy of this structure is passed through
  10940. ** the parser and down into all the parser action routine in order to
  10941. ** carry around information that is global to the entire parse.
  10942. **
  10943. ** The structure is divided into two parts. When the parser and code
  10944. ** generate call themselves recursively, the first part of the structure
  10945. ** is constant but the second part is reset at the beginning and end of
  10946. ** each recursion.
  10947. **
  10948. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10949. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10950. ** used to store the set of table-locks required by the statement being
  10951. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10952. ** list.
  10953. */
  10954. struct Parse {
  10955. sqlite3 *db; /* The main database structure */
  10956. char *zErrMsg; /* An error message */
  10957. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10958. int rc; /* Return code from execution */
  10959. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10960. u8 checkSchema; /* Causes schema cookie check after an error */
  10961. u8 nested; /* Number of nested calls to the parser/code generator */
  10962. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10963. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10964. u8 nColCache; /* Number of entries in aColCache[] */
  10965. u8 iColCache; /* Next entry in aColCache[] to replace */
  10966. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  10967. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10968. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  10969. int aTempReg[8]; /* Holding area for temporary registers */
  10970. int nRangeReg; /* Size of the temporary register block */
  10971. int iRangeReg; /* First register in temporary register block */
  10972. int nErr; /* Number of errors seen */
  10973. int nTab; /* Number of previously allocated VDBE cursors */
  10974. int nMem; /* Number of memory cells used so far */
  10975. int nSet; /* Number of sets used so far */
  10976. int nOnce; /* Number of OP_Once instructions so far */
  10977. int ckBase; /* Base register of data during check constraints */
  10978. int iPartIdxTab; /* Table corresponding to a partial index */
  10979. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10980. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10981. struct yColCache {
  10982. int iTable; /* Table cursor number */
  10983. int iColumn; /* Table column number */
  10984. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10985. int iLevel; /* Nesting level */
  10986. int iReg; /* Reg with value of this column. 0 means none. */
  10987. int lru; /* Least recently used entry has the smallest value */
  10988. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10989. yDbMask writeMask; /* Start a write transaction on these databases */
  10990. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10991. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10992. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10993. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10994. int regRoot; /* Register holding root page number for new objects */
  10995. int nMaxArg; /* Max args passed to user function by sub-program */
  10996. Token constraintName;/* Name of the constraint currently being parsed */
  10997. #ifndef SQLITE_OMIT_SHARED_CACHE
  10998. int nTableLock; /* Number of locks in aTableLock */
  10999. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  11000. #endif
  11001. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  11002. /* Information used while coding trigger programs. */
  11003. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  11004. Table *pTriggerTab; /* Table triggers are being coded for */
  11005. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  11006. u32 oldmask; /* Mask of old.* columns referenced */
  11007. u32 newmask; /* Mask of new.* columns referenced */
  11008. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11009. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11010. u8 disableTriggers; /* True to disable triggers */
  11011. /* Above is constant between recursions. Below is reset before and after
  11012. ** each recursion */
  11013. int nVar; /* Number of '?' variables seen in the SQL so far */
  11014. int nzVar; /* Number of available slots in azVar[] */
  11015. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11016. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11017. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11018. int nVtabLock; /* Number of virtual tables to lock */
  11019. #endif
  11020. int nAlias; /* Number of aliased result set columns */
  11021. int nHeight; /* Expression tree height of current sub-select */
  11022. #ifndef SQLITE_OMIT_EXPLAIN
  11023. int iSelectId; /* ID of current select for EXPLAIN output */
  11024. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11025. #endif
  11026. char **azVar; /* Pointers to names of parameters */
  11027. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11028. int *aAlias; /* Register used to hold aliased result */
  11029. const char *zTail; /* All SQL text past the last semicolon parsed */
  11030. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11031. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11032. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11033. Token sNameToken; /* Token with unqualified schema object name */
  11034. Token sLastToken; /* The last token parsed */
  11035. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11036. Token sArg; /* Complete text of a module argument */
  11037. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11038. #endif
  11039. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11040. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11041. };
  11042. /*
  11043. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11044. */
  11045. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11046. #define IN_DECLARE_VTAB 0
  11047. #else
  11048. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11049. #endif
  11050. /*
  11051. ** An instance of the following structure can be declared on a stack and used
  11052. ** to save the Parse.zAuthContext value so that it can be restored later.
  11053. */
  11054. struct AuthContext {
  11055. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11056. Parse *pParse; /* The Parse structure */
  11057. };
  11058. /*
  11059. ** Bitfield flags for P5 value in various opcodes.
  11060. */
  11061. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11062. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11063. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11064. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11065. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11066. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  11067. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11068. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11069. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11070. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11071. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11072. /*
  11073. * Each trigger present in the database schema is stored as an instance of
  11074. * struct Trigger.
  11075. *
  11076. * Pointers to instances of struct Trigger are stored in two ways.
  11077. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11078. * database). This allows Trigger structures to be retrieved by name.
  11079. * 2. All triggers associated with a single table form a linked list, using the
  11080. * pNext member of struct Trigger. A pointer to the first element of the
  11081. * linked list is stored as the "pTrigger" member of the associated
  11082. * struct Table.
  11083. *
  11084. * The "step_list" member points to the first element of a linked list
  11085. * containing the SQL statements specified as the trigger program.
  11086. */
  11087. struct Trigger {
  11088. char *zName; /* The name of the trigger */
  11089. char *table; /* The table or view to which the trigger applies */
  11090. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11091. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11092. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11093. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11094. the <column-list> is stored here */
  11095. Schema *pSchema; /* Schema containing the trigger */
  11096. Schema *pTabSchema; /* Schema containing the table */
  11097. TriggerStep *step_list; /* Link list of trigger program steps */
  11098. Trigger *pNext; /* Next trigger associated with the table */
  11099. };
  11100. /*
  11101. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11102. ** determine which.
  11103. **
  11104. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11105. ** In that cases, the constants below can be ORed together.
  11106. */
  11107. #define TRIGGER_BEFORE 1
  11108. #define TRIGGER_AFTER 2
  11109. /*
  11110. * An instance of struct TriggerStep is used to store a single SQL statement
  11111. * that is a part of a trigger-program.
  11112. *
  11113. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11114. * using the "pNext" member) referenced by the "step_list" member of the
  11115. * associated struct Trigger instance. The first element of the linked list is
  11116. * the first step of the trigger-program.
  11117. *
  11118. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11119. * "SELECT" statement. The meanings of the other members is determined by the
  11120. * value of "op" as follows:
  11121. *
  11122. * (op == TK_INSERT)
  11123. * orconf -> stores the ON CONFLICT algorithm
  11124. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11125. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11126. * target -> A token holding the quoted name of the table to insert into.
  11127. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11128. * this stores values to be inserted. Otherwise NULL.
  11129. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11130. * statement, then this stores the column-names to be
  11131. * inserted into.
  11132. *
  11133. * (op == TK_DELETE)
  11134. * target -> A token holding the quoted name of the table to delete from.
  11135. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11136. * Otherwise NULL.
  11137. *
  11138. * (op == TK_UPDATE)
  11139. * target -> A token holding the quoted name of the table to update rows of.
  11140. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11141. * Otherwise NULL.
  11142. * pExprList -> A list of the columns to update and the expressions to update
  11143. * them to. See sqlite3Update() documentation of "pChanges"
  11144. * argument.
  11145. *
  11146. */
  11147. struct TriggerStep {
  11148. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11149. u8 orconf; /* OE_Rollback etc. */
  11150. Trigger *pTrig; /* The trigger that this step is a part of */
  11151. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11152. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11153. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11154. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  11155. IdList *pIdList; /* Column names for INSERT */
  11156. TriggerStep *pNext; /* Next in the link-list */
  11157. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11158. };
  11159. /*
  11160. ** The following structure contains information used by the sqliteFix...
  11161. ** routines as they walk the parse tree to make database references
  11162. ** explicit.
  11163. */
  11164. typedef struct DbFixer DbFixer;
  11165. struct DbFixer {
  11166. Parse *pParse; /* The parsing context. Error messages written here */
  11167. Schema *pSchema; /* Fix items to this schema */
  11168. int bVarOnly; /* Check for variable references only */
  11169. const char *zDb; /* Make sure all objects are contained in this database */
  11170. const char *zType; /* Type of the container - used for error messages */
  11171. const Token *pName; /* Name of the container - used for error messages */
  11172. };
  11173. /*
  11174. ** An objected used to accumulate the text of a string where we
  11175. ** do not necessarily know how big the string will be in the end.
  11176. */
  11177. struct StrAccum {
  11178. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11179. char *zBase; /* A base allocation. Not from malloc. */
  11180. char *zText; /* The string collected so far */
  11181. int nChar; /* Length of the string so far */
  11182. int nAlloc; /* Amount of space allocated in zText */
  11183. int mxAlloc; /* Maximum allowed string length */
  11184. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11185. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11186. };
  11187. #define STRACCUM_NOMEM 1
  11188. #define STRACCUM_TOOBIG 2
  11189. /*
  11190. ** A pointer to this structure is used to communicate information
  11191. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11192. */
  11193. typedef struct {
  11194. sqlite3 *db; /* The database being initialized */
  11195. char **pzErrMsg; /* Error message stored here */
  11196. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11197. int rc; /* Result code stored here */
  11198. } InitData;
  11199. /*
  11200. ** Structure containing global configuration data for the SQLite library.
  11201. **
  11202. ** This structure also contains some state information.
  11203. */
  11204. struct Sqlite3Config {
  11205. int bMemstat; /* True to enable memory status */
  11206. int bCoreMutex; /* True to enable core mutexing */
  11207. int bFullMutex; /* True to enable full mutexing */
  11208. int bOpenUri; /* True to interpret filenames as URIs */
  11209. int bUseCis; /* Use covering indices for full-scans */
  11210. int mxStrlen; /* Maximum string length */
  11211. int szLookaside; /* Default lookaside buffer size */
  11212. int nLookaside; /* Default lookaside buffer count */
  11213. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11214. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11215. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11216. void *pHeap; /* Heap storage space */
  11217. int nHeap; /* Size of pHeap[] */
  11218. int mnReq, mxReq; /* Min and max heap requests sizes */
  11219. sqlite3_int64 szMmap; /* mmap() space per open file */
  11220. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11221. void *pScratch; /* Scratch memory */
  11222. int szScratch; /* Size of each scratch buffer */
  11223. int nScratch; /* Number of scratch buffers */
  11224. void *pPage; /* Page cache memory */
  11225. int szPage; /* Size of each page in pPage[] */
  11226. int nPage; /* Number of pages in pPage[] */
  11227. int mxParserStack; /* maximum depth of the parser stack */
  11228. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11229. /* The above might be initialized to non-zero. The following need to always
  11230. ** initially be zero, however. */
  11231. int isInit; /* True after initialization has finished */
  11232. int inProgress; /* True while initialization in progress */
  11233. int isMutexInit; /* True after mutexes are initialized */
  11234. int isMallocInit; /* True after malloc is initialized */
  11235. int isPCacheInit; /* True after malloc is initialized */
  11236. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11237. int nRefInitMutex; /* Number of users of pInitMutex */
  11238. void (*xLog)(void*,int,const char*); /* Function for logging */
  11239. void *pLogArg; /* First argument to xLog() */
  11240. int bLocaltimeFault; /* True to fail localtime() calls */
  11241. #ifdef SQLITE_ENABLE_SQLLOG
  11242. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11243. void *pSqllogArg;
  11244. #endif
  11245. };
  11246. /*
  11247. ** Context pointer passed down through the tree-walk.
  11248. */
  11249. struct Walker {
  11250. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11251. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11252. Parse *pParse; /* Parser context. */
  11253. int walkerDepth; /* Number of subqueries */
  11254. u8 bSelectDepthFirst; /* Do subqueries first */
  11255. union { /* Extra data for callback */
  11256. NameContext *pNC; /* Naming context */
  11257. int i; /* Integer value */
  11258. SrcList *pSrcList; /* FROM clause */
  11259. struct SrcCount *pSrcCount; /* Counting column references */
  11260. } u;
  11261. };
  11262. /* Forward declarations */
  11263. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11264. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11265. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11266. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11267. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11268. /*
  11269. ** Return code from the parse-tree walking primitives and their
  11270. ** callbacks.
  11271. */
  11272. #define WRC_Continue 0 /* Continue down into children */
  11273. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11274. #define WRC_Abort 2 /* Abandon the tree walk */
  11275. /*
  11276. ** Assuming zIn points to the first byte of a UTF-8 character,
  11277. ** advance zIn to point to the first byte of the next UTF-8 character.
  11278. */
  11279. #define SQLITE_SKIP_UTF8(zIn) { \
  11280. if( (*(zIn++))>=0xc0 ){ \
  11281. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11282. } \
  11283. }
  11284. /*
  11285. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11286. ** the same name but without the _BKPT suffix. These macros invoke
  11287. ** routines that report the line-number on which the error originated
  11288. ** using sqlite3_log(). The routines also provide a convenient place
  11289. ** to set a debugger breakpoint.
  11290. */
  11291. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11292. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11293. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11294. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11295. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11296. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11297. /*
  11298. ** FTS4 is really an extension for FTS3. It is enabled using the
  11299. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11300. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11301. */
  11302. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11303. # define SQLITE_ENABLE_FTS3
  11304. #endif
  11305. /*
  11306. ** The ctype.h header is needed for non-ASCII systems. It is also
  11307. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11308. */
  11309. #if !defined(SQLITE_ASCII) || \
  11310. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11311. # include <ctype.h>
  11312. #endif
  11313. /*
  11314. ** The following macros mimic the standard library functions toupper(),
  11315. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11316. ** sqlite versions only work for ASCII characters, regardless of locale.
  11317. */
  11318. #ifdef SQLITE_ASCII
  11319. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11320. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11321. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11322. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11323. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11324. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11325. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11326. #else
  11327. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11328. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11329. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11330. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11331. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11332. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11333. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11334. #endif
  11335. /*
  11336. ** Internal function prototypes
  11337. */
  11338. #define sqlite3StrICmp sqlite3_stricmp
  11339. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11340. #define sqlite3StrNICmp sqlite3_strnicmp
  11341. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11342. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11343. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11344. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11345. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11346. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11347. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11348. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11349. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11350. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11351. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11352. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11353. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11354. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11355. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11356. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11357. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11358. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11359. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11360. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11361. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11362. /*
  11363. ** On systems with ample stack space and that support alloca(), make
  11364. ** use of alloca() to obtain space for large automatic objects. By default,
  11365. ** obtain space from malloc().
  11366. **
  11367. ** The alloca() routine never returns NULL. This will cause code paths
  11368. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11369. */
  11370. #ifdef SQLITE_USE_ALLOCA
  11371. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11372. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11373. # define sqlite3StackFree(D,P)
  11374. #else
  11375. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11376. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11377. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11378. #endif
  11379. #ifdef SQLITE_ENABLE_MEMSYS3
  11380. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11381. #endif
  11382. #ifdef SQLITE_ENABLE_MEMSYS5
  11383. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11384. #endif
  11385. #ifndef SQLITE_MUTEX_OMIT
  11386. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11387. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11388. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11389. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11390. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11391. #endif
  11392. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11393. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11394. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11395. #ifndef SQLITE_OMIT_FLOATING_POINT
  11396. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11397. #else
  11398. # define sqlite3IsNaN(X) 0
  11399. #endif
  11400. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11401. #ifndef SQLITE_OMIT_TRACE
  11402. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11403. #endif
  11404. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11405. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11406. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11407. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11408. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11409. #endif
  11410. #if defined(SQLITE_TEST)
  11411. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11412. #endif
  11413. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11414. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11415. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11416. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11417. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11418. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11419. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11420. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11421. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11422. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11423. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11424. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11425. #else
  11426. # define sqlite3ExplainBegin(X)
  11427. # define sqlite3ExplainSelect(A,B)
  11428. # define sqlite3ExplainExpr(A,B)
  11429. # define sqlite3ExplainExprList(A,B)
  11430. # define sqlite3ExplainFinish(X)
  11431. # define sqlite3VdbeExplanation(X) 0
  11432. #endif
  11433. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11434. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11435. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11436. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11437. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11438. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11439. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11440. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11441. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11442. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11443. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11444. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11445. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11446. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11447. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11448. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11449. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11450. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11451. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11452. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11453. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11454. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11455. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11456. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11457. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11458. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11459. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11460. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11461. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11462. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11463. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11464. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11465. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11466. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11467. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11468. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11469. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11470. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11471. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11472. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11473. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11474. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11475. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11476. sqlite3_vfs**,char**,char **);
  11477. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11478. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11479. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11480. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11481. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11482. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11483. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11484. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11485. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11486. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11487. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11488. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11489. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11490. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11491. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11492. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11493. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11494. #else
  11495. # define sqlite3ViewGetColumnNames(A,B) 0
  11496. #endif
  11497. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11498. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11499. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11500. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11501. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11502. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11503. #else
  11504. # define sqlite3AutoincrementBegin(X)
  11505. # define sqlite3AutoincrementEnd(X)
  11506. #endif
  11507. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11508. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11509. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11510. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11511. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11512. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11513. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11514. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11515. Token*, Select*, Expr*, IdList*);
  11516. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11517. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11518. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11519. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11520. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11521. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11522. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11523. Expr*, int, int);
  11524. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11525. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11526. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11527. Expr*,ExprList*,u16,Expr*,Expr*);
  11528. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11529. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11530. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11531. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11532. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11533. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  11534. #endif
  11535. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11536. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11537. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11538. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11539. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  11540. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  11541. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  11542. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  11543. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  11544. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
  11545. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11546. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11547. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11548. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11549. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11550. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11551. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11552. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11553. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11554. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11555. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11556. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11557. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11558. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11559. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11560. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11561. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11562. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11563. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11564. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11565. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11566. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11567. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11568. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11569. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11570. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11571. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  11572. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  11573. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  11574. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11575. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11576. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11577. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11578. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11579. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11580. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11581. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11582. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11583. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11584. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11585. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11586. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11587. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11588. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11589. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11590. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11591. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11592. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11593. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11594. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11595. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11596. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11597. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11598. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11599. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11600. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  11601. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11602. int*,int,int,int,int,int*);
  11603. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11604. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11605. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11606. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11607. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11608. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  11609. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11610. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11611. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11612. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11613. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11614. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11615. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11616. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11617. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11618. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11619. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11620. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11621. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11622. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11623. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11624. #endif
  11625. #ifndef SQLITE_OMIT_TRIGGER
  11626. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11627. Expr*,int, int);
  11628. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11629. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11630. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11631. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11632. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11633. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11634. int, int, int);
  11635. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11636. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11637. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11638. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11639. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11640. ExprList*,Select*,u8);
  11641. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11642. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11643. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11644. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11645. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11646. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11647. #else
  11648. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11649. # define sqlite3DeleteTrigger(A,B)
  11650. # define sqlite3DropTriggerPtr(A,B)
  11651. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11652. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11653. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11654. # define sqlite3TriggerList(X, Y) 0
  11655. # define sqlite3ParseToplevel(p) p
  11656. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11657. #endif
  11658. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11659. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11660. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11661. #ifndef SQLITE_OMIT_AUTHORIZATION
  11662. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11663. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11664. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11665. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11666. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11667. #else
  11668. # define sqlite3AuthRead(a,b,c,d)
  11669. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11670. # define sqlite3AuthContextPush(a,b,c)
  11671. # define sqlite3AuthContextPop(a) ((void)(a))
  11672. #endif
  11673. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11674. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11675. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11676. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11677. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11678. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11679. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11680. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11681. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11682. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11683. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11684. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11685. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11686. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11687. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  11688. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  11689. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11690. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  11691. #endif
  11692. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  11693. /*
  11694. ** Routines to read and write variable-length integers. These used to
  11695. ** be defined locally, but now we use the varint routines in the util.c
  11696. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11697. ** are coded to assume the single byte case is already handled (which
  11698. ** the MACRO form does).
  11699. */
  11700. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11701. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11702. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11703. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11704. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11705. /*
  11706. ** The header of a record consists of a sequence variable-length integers.
  11707. ** These integers are almost always small and are encoded as a single byte.
  11708. ** The following macros take advantage this fact to provide a fast encode
  11709. ** and decode of the integers in a record header. It is faster for the common
  11710. ** case where the integer is a single byte. It is a little slower when the
  11711. ** integer is two or more bytes. But overall it is faster.
  11712. **
  11713. ** The following expressions are equivalent:
  11714. **
  11715. ** x = sqlite3GetVarint32( A, &B );
  11716. ** x = sqlite3PutVarint32( A, B );
  11717. **
  11718. ** x = getVarint32( A, B );
  11719. ** x = putVarint32( A, B );
  11720. **
  11721. */
  11722. #define getVarint32(A,B) \
  11723. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  11724. #define putVarint32(A,B) \
  11725. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  11726. sqlite3PutVarint32((A),(B)))
  11727. #define getVarint sqlite3GetVarint
  11728. #define putVarint sqlite3PutVarint
  11729. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11730. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11731. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11732. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11733. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11734. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11735. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11736. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11737. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11738. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11739. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  11740. defined(SQLITE_DEBUG_OS_TRACE)
  11741. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  11742. #endif
  11743. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11744. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11745. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11746. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11747. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11748. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11749. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11750. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11751. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11752. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11753. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11754. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11755. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11756. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11757. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11758. #ifdef SQLITE_ENABLE_8_3_NAMES
  11759. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11760. #else
  11761. # define sqlite3FileSuffix3(X,Y)
  11762. #endif
  11763. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11764. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11765. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11766. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11767. void(*)(void*));
  11768. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11769. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11770. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11771. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11772. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11773. #ifndef SQLITE_AMALGAMATION
  11774. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11775. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11776. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11777. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11778. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11779. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11780. #ifndef SQLITE_OMIT_WSD
  11781. SQLITE_PRIVATE int sqlite3PendingByte;
  11782. #endif
  11783. #endif
  11784. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11785. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11786. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11787. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11788. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11789. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11790. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11791. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11792. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11793. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  11794. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11795. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11796. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  11797. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11798. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11799. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11800. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11801. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11802. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  11803. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11804. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11805. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11806. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11807. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11808. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11809. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11810. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11811. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11812. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11813. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11814. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11815. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11816. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  11817. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11818. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11819. void (*)(sqlite3_context*,int,sqlite3_value **),
  11820. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11821. FuncDestructor *pDestructor
  11822. );
  11823. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11824. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11825. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11826. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11827. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11828. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11829. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11830. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11831. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11832. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11833. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11834. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11835. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  11836. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  11837. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  11838. #endif
  11839. /*
  11840. ** The interface to the LEMON-generated parser
  11841. */
  11842. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11843. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11844. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11845. #ifdef YYTRACKMAXSTACKDEPTH
  11846. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11847. #endif
  11848. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11849. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11850. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11851. #else
  11852. # define sqlite3CloseExtensions(X)
  11853. #endif
  11854. #ifndef SQLITE_OMIT_SHARED_CACHE
  11855. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11856. #else
  11857. #define sqlite3TableLock(v,w,x,y,z)
  11858. #endif
  11859. #ifdef SQLITE_TEST
  11860. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11861. #endif
  11862. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11863. # define sqlite3VtabClear(Y)
  11864. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11865. # define sqlite3VtabRollback(X)
  11866. # define sqlite3VtabCommit(X)
  11867. # define sqlite3VtabInSync(db) 0
  11868. # define sqlite3VtabLock(X)
  11869. # define sqlite3VtabUnlock(X)
  11870. # define sqlite3VtabUnlockList(X)
  11871. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11872. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11873. #else
  11874. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11875. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11876. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  11877. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11878. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11879. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11880. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11881. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11882. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11883. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  11884. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11885. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11886. #endif
  11887. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11888. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11889. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11890. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11891. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11892. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11893. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11894. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11895. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11896. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11897. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11898. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  11899. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11900. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11901. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11902. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11903. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11904. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11905. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11906. #ifndef SQLITE_OMIT_WAL
  11907. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11908. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11909. #endif
  11910. /* Declarations for functions in fkey.c. All of these are replaced by
  11911. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11912. ** key functionality is available. If OMIT_TRIGGER is defined but
  11913. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11914. ** this case foreign keys are parsed, but no other functionality is
  11915. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11916. */
  11917. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11918. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  11919. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11920. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  11921. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11922. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11923. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11924. #else
  11925. #define sqlite3FkActions(a,b,c,d,e,f)
  11926. #define sqlite3FkCheck(a,b,c,d,e,f)
  11927. #define sqlite3FkDropTable(a,b,c)
  11928. #define sqlite3FkOldmask(a,b) 0
  11929. #define sqlite3FkRequired(a,b,c,d) 0
  11930. #endif
  11931. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11932. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11933. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  11934. #else
  11935. #define sqlite3FkDelete(a,b)
  11936. #define sqlite3FkLocateIndex(a,b,c,d,e)
  11937. #endif
  11938. /*
  11939. ** Available fault injectors. Should be numbered beginning with 0.
  11940. */
  11941. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11942. #define SQLITE_FAULTINJECTOR_COUNT 1
  11943. /*
  11944. ** The interface to the code in fault.c used for identifying "benign"
  11945. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11946. ** is not defined.
  11947. */
  11948. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11949. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11950. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11951. #else
  11952. #define sqlite3BeginBenignMalloc()
  11953. #define sqlite3EndBenignMalloc()
  11954. #endif
  11955. #define IN_INDEX_ROWID 1
  11956. #define IN_INDEX_EPH 2
  11957. #define IN_INDEX_INDEX_ASC 3
  11958. #define IN_INDEX_INDEX_DESC 4
  11959. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11960. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11961. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11962. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11963. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11964. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  11965. #else
  11966. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11967. #define sqlite3JournalExists(p) 1
  11968. #endif
  11969. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11970. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11971. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11972. #if SQLITE_MAX_EXPR_DEPTH>0
  11973. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11974. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11975. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11976. #else
  11977. #define sqlite3ExprSetHeight(x,y)
  11978. #define sqlite3SelectExprHeight(x) 0
  11979. #define sqlite3ExprCheckHeight(x,y)
  11980. #endif
  11981. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11982. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11983. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11984. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11985. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11986. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11987. #else
  11988. #define sqlite3ConnectionBlocked(x,y)
  11989. #define sqlite3ConnectionUnlocked(x)
  11990. #define sqlite3ConnectionClosed(x)
  11991. #endif
  11992. #ifdef SQLITE_DEBUG
  11993. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11994. #endif
  11995. /*
  11996. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11997. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11998. ** print I/O tracing messages.
  11999. */
  12000. #ifdef SQLITE_ENABLE_IOTRACE
  12001. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  12002. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  12003. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  12004. #else
  12005. # define IOTRACE(A)
  12006. # define sqlite3VdbeIOTraceSql(X)
  12007. #endif
  12008. /*
  12009. ** These routines are available for the mem2.c debugging memory allocator
  12010. ** only. They are used to verify that different "types" of memory
  12011. ** allocations are properly tracked by the system.
  12012. **
  12013. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12014. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12015. ** a single bit set.
  12016. **
  12017. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12018. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12019. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12020. **
  12021. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12022. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12023. **
  12024. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12025. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12026. ** it might have been allocated by lookaside, except the allocation was
  12027. ** too large or lookaside was already full. It is important to verify
  12028. ** that allocations that might have been satisfied by lookaside are not
  12029. ** passed back to non-lookaside free() routines. Asserts such as the
  12030. ** example above are placed on the non-lookaside free() routines to verify
  12031. ** this constraint.
  12032. **
  12033. ** All of this is no-op for a production build. It only comes into
  12034. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12035. */
  12036. #ifdef SQLITE_MEMDEBUG
  12037. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12038. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12039. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12040. #else
  12041. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12042. # define sqlite3MemdebugHasType(X,Y) 1
  12043. # define sqlite3MemdebugNoType(X,Y) 1
  12044. #endif
  12045. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12046. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  12047. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12048. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12049. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  12050. #endif /* _SQLITEINT_H_ */
  12051. /************** End of sqliteInt.h *******************************************/
  12052. /************** Begin file global.c ******************************************/
  12053. /*
  12054. ** 2008 June 13
  12055. **
  12056. ** The author disclaims copyright to this source code. In place of
  12057. ** a legal notice, here is a blessing:
  12058. **
  12059. ** May you do good and not evil.
  12060. ** May you find forgiveness for yourself and forgive others.
  12061. ** May you share freely, never taking more than you give.
  12062. **
  12063. *************************************************************************
  12064. **
  12065. ** This file contains definitions of global variables and contants.
  12066. */
  12067. /* An array to map all upper-case characters into their corresponding
  12068. ** lower-case character.
  12069. **
  12070. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12071. ** handle case conversions for the UTF character set since the tables
  12072. ** involved are nearly as big or bigger than SQLite itself.
  12073. */
  12074. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12075. #ifdef SQLITE_ASCII
  12076. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12077. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12078. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12079. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12080. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12081. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12082. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12083. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12084. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12085. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12086. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12087. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12088. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12089. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12090. 252,253,254,255
  12091. #endif
  12092. #ifdef SQLITE_EBCDIC
  12093. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12094. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12095. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12096. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12097. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12098. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12099. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12100. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12101. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12102. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12103. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12104. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12105. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12106. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12107. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12108. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12109. #endif
  12110. };
  12111. /*
  12112. ** The following 256 byte lookup table is used to support SQLites built-in
  12113. ** equivalents to the following standard library functions:
  12114. **
  12115. ** isspace() 0x01
  12116. ** isalpha() 0x02
  12117. ** isdigit() 0x04
  12118. ** isalnum() 0x06
  12119. ** isxdigit() 0x08
  12120. ** toupper() 0x20
  12121. ** SQLite identifier character 0x40
  12122. **
  12123. ** Bit 0x20 is set if the mapped character requires translation to upper
  12124. ** case. i.e. if the character is a lower-case ASCII character.
  12125. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12126. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12127. **
  12128. ** (x & ~(map[x]&0x20))
  12129. **
  12130. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12131. ** array. tolower() is used more often than toupper() by SQLite.
  12132. **
  12133. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12134. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12135. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12136. ** part of an identifier is 0x46.
  12137. **
  12138. ** SQLite's versions are identical to the standard versions assuming a
  12139. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12140. */
  12141. #ifdef SQLITE_ASCII
  12142. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12143. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12144. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12145. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12146. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12147. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12148. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12149. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12150. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12151. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12152. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12153. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12154. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12155. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12156. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12157. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12158. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12159. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12160. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12161. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12162. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12163. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12164. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12165. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12166. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12167. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12168. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12169. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12170. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12171. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12172. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12173. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12174. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12175. };
  12176. #endif
  12177. #ifndef SQLITE_USE_URI
  12178. # define SQLITE_USE_URI 0
  12179. #endif
  12180. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12181. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12182. #endif
  12183. /*
  12184. ** The following singleton contains the global configuration for
  12185. ** the SQLite library.
  12186. */
  12187. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12188. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12189. 1, /* bCoreMutex */
  12190. SQLITE_THREADSAFE==1, /* bFullMutex */
  12191. SQLITE_USE_URI, /* bOpenUri */
  12192. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12193. 0x7ffffffe, /* mxStrlen */
  12194. 128, /* szLookaside */
  12195. 500, /* nLookaside */
  12196. {0,0,0,0,0,0,0,0}, /* m */
  12197. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12198. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12199. (void*)0, /* pHeap */
  12200. 0, /* nHeap */
  12201. 0, 0, /* mnHeap, mxHeap */
  12202. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12203. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12204. (void*)0, /* pScratch */
  12205. 0, /* szScratch */
  12206. 0, /* nScratch */
  12207. (void*)0, /* pPage */
  12208. 0, /* szPage */
  12209. 0, /* nPage */
  12210. 0, /* mxParserStack */
  12211. 0, /* sharedCacheEnabled */
  12212. /* All the rest should always be initialized to zero */
  12213. 0, /* isInit */
  12214. 0, /* inProgress */
  12215. 0, /* isMutexInit */
  12216. 0, /* isMallocInit */
  12217. 0, /* isPCacheInit */
  12218. 0, /* pInitMutex */
  12219. 0, /* nRefInitMutex */
  12220. 0, /* xLog */
  12221. 0, /* pLogArg */
  12222. 0, /* bLocaltimeFault */
  12223. #ifdef SQLITE_ENABLE_SQLLOG
  12224. 0, /* xSqllog */
  12225. 0 /* pSqllogArg */
  12226. #endif
  12227. };
  12228. /*
  12229. ** Hash table for global functions - functions common to all
  12230. ** database connections. After initialization, this table is
  12231. ** read-only.
  12232. */
  12233. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12234. /*
  12235. ** Constant tokens for values 0 and 1.
  12236. */
  12237. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12238. { "0", 1 },
  12239. { "1", 1 }
  12240. };
  12241. /*
  12242. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12243. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12244. ** the database page that contains the pending byte. It never attempts
  12245. ** to read or write that page. The pending byte page is set assign
  12246. ** for use by the VFS layers as space for managing file locks.
  12247. **
  12248. ** During testing, it is often desirable to move the pending byte to
  12249. ** a different position in the file. This allows code that has to
  12250. ** deal with the pending byte to run on files that are much smaller
  12251. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12252. ** move the pending byte.
  12253. **
  12254. ** IMPORTANT: Changing the pending byte to any value other than
  12255. ** 0x40000000 results in an incompatible database file format!
  12256. ** Changing the pending byte during operating results in undefined
  12257. ** and dileterious behavior.
  12258. */
  12259. #ifndef SQLITE_OMIT_WSD
  12260. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12261. #endif
  12262. /*
  12263. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12264. ** created by mkopcodeh.awk during compilation. Data is obtained
  12265. ** from the comments following the "case OP_xxxx:" statements in
  12266. ** the vdbe.c file.
  12267. */
  12268. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12269. /************** End of global.c **********************************************/
  12270. /************** Begin file ctime.c *******************************************/
  12271. /*
  12272. ** 2010 February 23
  12273. **
  12274. ** The author disclaims copyright to this source code. In place of
  12275. ** a legal notice, here is a blessing:
  12276. **
  12277. ** May you do good and not evil.
  12278. ** May you find forgiveness for yourself and forgive others.
  12279. ** May you share freely, never taking more than you give.
  12280. **
  12281. *************************************************************************
  12282. **
  12283. ** This file implements routines used to report what compile-time options
  12284. ** SQLite was built with.
  12285. */
  12286. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12287. /*
  12288. ** An array of names of all compile-time options. This array should
  12289. ** be sorted A-Z.
  12290. **
  12291. ** This array looks large, but in a typical installation actually uses
  12292. ** only a handful of compile-time options, so most times this array is usually
  12293. ** rather short and uses little memory space.
  12294. */
  12295. static const char * const azCompileOpt[] = {
  12296. /* These macros are provided to "stringify" the value of the define
  12297. ** for those options in which the value is meaningful. */
  12298. #define CTIMEOPT_VAL_(opt) #opt
  12299. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12300. #ifdef SQLITE_32BIT_ROWID
  12301. "32BIT_ROWID",
  12302. #endif
  12303. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12304. "4_BYTE_ALIGNED_MALLOC",
  12305. #endif
  12306. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12307. "CASE_SENSITIVE_LIKE",
  12308. #endif
  12309. #ifdef SQLITE_CHECK_PAGES
  12310. "CHECK_PAGES",
  12311. #endif
  12312. #ifdef SQLITE_COVERAGE_TEST
  12313. "COVERAGE_TEST",
  12314. #endif
  12315. #ifdef SQLITE_DEBUG
  12316. "DEBUG",
  12317. #endif
  12318. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12319. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12320. #endif
  12321. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  12322. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  12323. #endif
  12324. #ifdef SQLITE_DISABLE_DIRSYNC
  12325. "DISABLE_DIRSYNC",
  12326. #endif
  12327. #ifdef SQLITE_DISABLE_LFS
  12328. "DISABLE_LFS",
  12329. #endif
  12330. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12331. "ENABLE_ATOMIC_WRITE",
  12332. #endif
  12333. #ifdef SQLITE_ENABLE_CEROD
  12334. "ENABLE_CEROD",
  12335. #endif
  12336. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12337. "ENABLE_COLUMN_METADATA",
  12338. #endif
  12339. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12340. "ENABLE_EXPENSIVE_ASSERT",
  12341. #endif
  12342. #ifdef SQLITE_ENABLE_FTS1
  12343. "ENABLE_FTS1",
  12344. #endif
  12345. #ifdef SQLITE_ENABLE_FTS2
  12346. "ENABLE_FTS2",
  12347. #endif
  12348. #ifdef SQLITE_ENABLE_FTS3
  12349. "ENABLE_FTS3",
  12350. #endif
  12351. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12352. "ENABLE_FTS3_PARENTHESIS",
  12353. #endif
  12354. #ifdef SQLITE_ENABLE_FTS4
  12355. "ENABLE_FTS4",
  12356. #endif
  12357. #ifdef SQLITE_ENABLE_ICU
  12358. "ENABLE_ICU",
  12359. #endif
  12360. #ifdef SQLITE_ENABLE_IOTRACE
  12361. "ENABLE_IOTRACE",
  12362. #endif
  12363. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12364. "ENABLE_LOAD_EXTENSION",
  12365. #endif
  12366. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12367. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12368. #endif
  12369. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12370. "ENABLE_MEMORY_MANAGEMENT",
  12371. #endif
  12372. #ifdef SQLITE_ENABLE_MEMSYS3
  12373. "ENABLE_MEMSYS3",
  12374. #endif
  12375. #ifdef SQLITE_ENABLE_MEMSYS5
  12376. "ENABLE_MEMSYS5",
  12377. #endif
  12378. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12379. "ENABLE_OVERSIZE_CELL_CHECK",
  12380. #endif
  12381. #ifdef SQLITE_ENABLE_RTREE
  12382. "ENABLE_RTREE",
  12383. #endif
  12384. #if defined(SQLITE_ENABLE_STAT4)
  12385. "ENABLE_STAT4",
  12386. #elif defined(SQLITE_ENABLE_STAT3)
  12387. "ENABLE_STAT3",
  12388. #endif
  12389. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12390. "ENABLE_UNLOCK_NOTIFY",
  12391. #endif
  12392. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12393. "ENABLE_UPDATE_DELETE_LIMIT",
  12394. #endif
  12395. #ifdef SQLITE_HAS_CODEC
  12396. "HAS_CODEC",
  12397. #endif
  12398. #ifdef SQLITE_HAVE_ISNAN
  12399. "HAVE_ISNAN",
  12400. #endif
  12401. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12402. "HOMEGROWN_RECURSIVE_MUTEX",
  12403. #endif
  12404. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12405. "IGNORE_AFP_LOCK_ERRORS",
  12406. #endif
  12407. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12408. "IGNORE_FLOCK_LOCK_ERRORS",
  12409. #endif
  12410. #ifdef SQLITE_INT64_TYPE
  12411. "INT64_TYPE",
  12412. #endif
  12413. #ifdef SQLITE_LOCK_TRACE
  12414. "LOCK_TRACE",
  12415. #endif
  12416. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  12417. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  12418. #endif
  12419. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12420. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12421. #endif
  12422. #ifdef SQLITE_MEMDEBUG
  12423. "MEMDEBUG",
  12424. #endif
  12425. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12426. "MIXED_ENDIAN_64BIT_FLOAT",
  12427. #endif
  12428. #ifdef SQLITE_NO_SYNC
  12429. "NO_SYNC",
  12430. #endif
  12431. #ifdef SQLITE_OMIT_ALTERTABLE
  12432. "OMIT_ALTERTABLE",
  12433. #endif
  12434. #ifdef SQLITE_OMIT_ANALYZE
  12435. "OMIT_ANALYZE",
  12436. #endif
  12437. #ifdef SQLITE_OMIT_ATTACH
  12438. "OMIT_ATTACH",
  12439. #endif
  12440. #ifdef SQLITE_OMIT_AUTHORIZATION
  12441. "OMIT_AUTHORIZATION",
  12442. #endif
  12443. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12444. "OMIT_AUTOINCREMENT",
  12445. #endif
  12446. #ifdef SQLITE_OMIT_AUTOINIT
  12447. "OMIT_AUTOINIT",
  12448. #endif
  12449. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12450. "OMIT_AUTOMATIC_INDEX",
  12451. #endif
  12452. #ifdef SQLITE_OMIT_AUTORESET
  12453. "OMIT_AUTORESET",
  12454. #endif
  12455. #ifdef SQLITE_OMIT_AUTOVACUUM
  12456. "OMIT_AUTOVACUUM",
  12457. #endif
  12458. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12459. "OMIT_BETWEEN_OPTIMIZATION",
  12460. #endif
  12461. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12462. "OMIT_BLOB_LITERAL",
  12463. #endif
  12464. #ifdef SQLITE_OMIT_BTREECOUNT
  12465. "OMIT_BTREECOUNT",
  12466. #endif
  12467. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12468. "OMIT_BUILTIN_TEST",
  12469. #endif
  12470. #ifdef SQLITE_OMIT_CAST
  12471. "OMIT_CAST",
  12472. #endif
  12473. #ifdef SQLITE_OMIT_CHECK
  12474. "OMIT_CHECK",
  12475. #endif
  12476. #ifdef SQLITE_OMIT_COMPLETE
  12477. "OMIT_COMPLETE",
  12478. #endif
  12479. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12480. "OMIT_COMPOUND_SELECT",
  12481. #endif
  12482. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12483. "OMIT_DATETIME_FUNCS",
  12484. #endif
  12485. #ifdef SQLITE_OMIT_DECLTYPE
  12486. "OMIT_DECLTYPE",
  12487. #endif
  12488. #ifdef SQLITE_OMIT_DEPRECATED
  12489. "OMIT_DEPRECATED",
  12490. #endif
  12491. #ifdef SQLITE_OMIT_DISKIO
  12492. "OMIT_DISKIO",
  12493. #endif
  12494. #ifdef SQLITE_OMIT_EXPLAIN
  12495. "OMIT_EXPLAIN",
  12496. #endif
  12497. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12498. "OMIT_FLAG_PRAGMAS",
  12499. #endif
  12500. #ifdef SQLITE_OMIT_FLOATING_POINT
  12501. "OMIT_FLOATING_POINT",
  12502. #endif
  12503. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12504. "OMIT_FOREIGN_KEY",
  12505. #endif
  12506. #ifdef SQLITE_OMIT_GET_TABLE
  12507. "OMIT_GET_TABLE",
  12508. #endif
  12509. #ifdef SQLITE_OMIT_INCRBLOB
  12510. "OMIT_INCRBLOB",
  12511. #endif
  12512. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12513. "OMIT_INTEGRITY_CHECK",
  12514. #endif
  12515. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12516. "OMIT_LIKE_OPTIMIZATION",
  12517. #endif
  12518. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12519. "OMIT_LOAD_EXTENSION",
  12520. #endif
  12521. #ifdef SQLITE_OMIT_LOCALTIME
  12522. "OMIT_LOCALTIME",
  12523. #endif
  12524. #ifdef SQLITE_OMIT_LOOKASIDE
  12525. "OMIT_LOOKASIDE",
  12526. #endif
  12527. #ifdef SQLITE_OMIT_MEMORYDB
  12528. "OMIT_MEMORYDB",
  12529. #endif
  12530. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12531. "OMIT_OR_OPTIMIZATION",
  12532. #endif
  12533. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12534. "OMIT_PAGER_PRAGMAS",
  12535. #endif
  12536. #ifdef SQLITE_OMIT_PRAGMA
  12537. "OMIT_PRAGMA",
  12538. #endif
  12539. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12540. "OMIT_PROGRESS_CALLBACK",
  12541. #endif
  12542. #ifdef SQLITE_OMIT_QUICKBALANCE
  12543. "OMIT_QUICKBALANCE",
  12544. #endif
  12545. #ifdef SQLITE_OMIT_REINDEX
  12546. "OMIT_REINDEX",
  12547. #endif
  12548. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12549. "OMIT_SCHEMA_PRAGMAS",
  12550. #endif
  12551. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12552. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12553. #endif
  12554. #ifdef SQLITE_OMIT_SHARED_CACHE
  12555. "OMIT_SHARED_CACHE",
  12556. #endif
  12557. #ifdef SQLITE_OMIT_SUBQUERY
  12558. "OMIT_SUBQUERY",
  12559. #endif
  12560. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12561. "OMIT_TCL_VARIABLE",
  12562. #endif
  12563. #ifdef SQLITE_OMIT_TEMPDB
  12564. "OMIT_TEMPDB",
  12565. #endif
  12566. #ifdef SQLITE_OMIT_TRACE
  12567. "OMIT_TRACE",
  12568. #endif
  12569. #ifdef SQLITE_OMIT_TRIGGER
  12570. "OMIT_TRIGGER",
  12571. #endif
  12572. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12573. "OMIT_TRUNCATE_OPTIMIZATION",
  12574. #endif
  12575. #ifdef SQLITE_OMIT_UTF16
  12576. "OMIT_UTF16",
  12577. #endif
  12578. #ifdef SQLITE_OMIT_VACUUM
  12579. "OMIT_VACUUM",
  12580. #endif
  12581. #ifdef SQLITE_OMIT_VIEW
  12582. "OMIT_VIEW",
  12583. #endif
  12584. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12585. "OMIT_VIRTUALTABLE",
  12586. #endif
  12587. #ifdef SQLITE_OMIT_WAL
  12588. "OMIT_WAL",
  12589. #endif
  12590. #ifdef SQLITE_OMIT_WSD
  12591. "OMIT_WSD",
  12592. #endif
  12593. #ifdef SQLITE_OMIT_XFER_OPT
  12594. "OMIT_XFER_OPT",
  12595. #endif
  12596. #ifdef SQLITE_PERFORMANCE_TRACE
  12597. "PERFORMANCE_TRACE",
  12598. #endif
  12599. #ifdef SQLITE_PROXY_DEBUG
  12600. "PROXY_DEBUG",
  12601. #endif
  12602. #ifdef SQLITE_RTREE_INT_ONLY
  12603. "RTREE_INT_ONLY",
  12604. #endif
  12605. #ifdef SQLITE_SECURE_DELETE
  12606. "SECURE_DELETE",
  12607. #endif
  12608. #ifdef SQLITE_SMALL_STACK
  12609. "SMALL_STACK",
  12610. #endif
  12611. #ifdef SQLITE_SOUNDEX
  12612. "SOUNDEX",
  12613. #endif
  12614. #ifdef SQLITE_TCL
  12615. "TCL",
  12616. #endif
  12617. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  12618. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12619. #endif
  12620. #ifdef SQLITE_TEST
  12621. "TEST",
  12622. #endif
  12623. #if defined(SQLITE_THREADSAFE)
  12624. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12625. #endif
  12626. #ifdef SQLITE_USE_ALLOCA
  12627. "USE_ALLOCA",
  12628. #endif
  12629. #ifdef SQLITE_ZERO_MALLOC
  12630. "ZERO_MALLOC"
  12631. #endif
  12632. };
  12633. /*
  12634. ** Given the name of a compile-time option, return true if that option
  12635. ** was used and false if not.
  12636. **
  12637. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12638. ** is not required for a match.
  12639. */
  12640. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12641. int i, n;
  12642. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12643. n = sqlite3Strlen30(zOptName);
  12644. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12645. ** linear search is adequate. No need for a binary search. */
  12646. for(i=0; i<ArraySize(azCompileOpt); i++){
  12647. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  12648. && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
  12649. ){
  12650. return 1;
  12651. }
  12652. }
  12653. return 0;
  12654. }
  12655. /*
  12656. ** Return the N-th compile-time option string. If N is out of range,
  12657. ** return a NULL pointer.
  12658. */
  12659. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12660. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12661. return azCompileOpt[N];
  12662. }
  12663. return 0;
  12664. }
  12665. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12666. /************** End of ctime.c ***********************************************/
  12667. /************** Begin file status.c ******************************************/
  12668. /*
  12669. ** 2008 June 18
  12670. **
  12671. ** The author disclaims copyright to this source code. In place of
  12672. ** a legal notice, here is a blessing:
  12673. **
  12674. ** May you do good and not evil.
  12675. ** May you find forgiveness for yourself and forgive others.
  12676. ** May you share freely, never taking more than you give.
  12677. **
  12678. *************************************************************************
  12679. **
  12680. ** This module implements the sqlite3_status() interface and related
  12681. ** functionality.
  12682. */
  12683. /************** Include vdbeInt.h in the middle of status.c ******************/
  12684. /************** Begin file vdbeInt.h *****************************************/
  12685. /*
  12686. ** 2003 September 6
  12687. **
  12688. ** The author disclaims copyright to this source code. In place of
  12689. ** a legal notice, here is a blessing:
  12690. **
  12691. ** May you do good and not evil.
  12692. ** May you find forgiveness for yourself and forgive others.
  12693. ** May you share freely, never taking more than you give.
  12694. **
  12695. *************************************************************************
  12696. ** This is the header file for information that is private to the
  12697. ** VDBE. This information used to all be at the top of the single
  12698. ** source code file "vdbe.c". When that file became too big (over
  12699. ** 6000 lines long) it was split up into several smaller files and
  12700. ** this header information was factored out.
  12701. */
  12702. #ifndef _VDBEINT_H_
  12703. #define _VDBEINT_H_
  12704. /*
  12705. ** The maximum number of times that a statement will try to reparse
  12706. ** itself before giving up and returning SQLITE_SCHEMA.
  12707. */
  12708. #ifndef SQLITE_MAX_SCHEMA_RETRY
  12709. # define SQLITE_MAX_SCHEMA_RETRY 50
  12710. #endif
  12711. /*
  12712. ** SQL is translated into a sequence of instructions to be
  12713. ** executed by a virtual machine. Each instruction is an instance
  12714. ** of the following structure.
  12715. */
  12716. typedef struct VdbeOp Op;
  12717. /*
  12718. ** Boolean values
  12719. */
  12720. typedef unsigned char Bool;
  12721. /* Opaque type used by code in vdbesort.c */
  12722. typedef struct VdbeSorter VdbeSorter;
  12723. /* Opaque type used by the explainer */
  12724. typedef struct Explain Explain;
  12725. /* Elements of the linked list at Vdbe.pAuxData */
  12726. typedef struct AuxData AuxData;
  12727. /*
  12728. ** A cursor is a pointer into a single BTree within a database file.
  12729. ** The cursor can seek to a BTree entry with a particular key, or
  12730. ** loop over all entries of the Btree. You can also insert new BTree
  12731. ** entries or retrieve the key or data from the entry that the cursor
  12732. ** is currently pointing to.
  12733. **
  12734. ** Every cursor that the virtual machine has open is represented by an
  12735. ** instance of the following structure.
  12736. */
  12737. struct VdbeCursor {
  12738. BtCursor *pCursor; /* The cursor structure of the backend */
  12739. Btree *pBt; /* Separate file holding temporary table */
  12740. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12741. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12742. int pseudoTableReg; /* Register holding pseudotable content. */
  12743. int nField; /* Number of fields in the header */
  12744. Bool zeroed; /* True if zeroed out and ready for reuse */
  12745. Bool rowidIsValid; /* True if lastRowid is valid */
  12746. Bool atFirst; /* True if pointing to first entry */
  12747. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12748. Bool nullRow; /* True if pointing to a row with no data */
  12749. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12750. Bool isTable; /* True if a table requiring integer keys */
  12751. Bool isIndex; /* True if an index containing keys only - no data */
  12752. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12753. Bool isSorter; /* True if a new-style sorter */
  12754. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12755. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12756. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12757. i64 seqCount; /* Sequence counter */
  12758. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12759. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12760. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12761. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12762. ** OP_IsUnique opcode on this cursor. */
  12763. int seekResult;
  12764. /* Cached information about the header for the data record that the
  12765. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12766. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12767. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12768. ** the cache is out of date.
  12769. **
  12770. ** aRow might point to (ephemeral) data for the current row, or it might
  12771. ** be NULL.
  12772. */
  12773. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12774. int payloadSize; /* Total number of bytes in the record */
  12775. u32 *aType; /* Type values for all entries in the record */
  12776. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12777. u8 *aRow; /* Data for the current row, if all on one page */
  12778. };
  12779. typedef struct VdbeCursor VdbeCursor;
  12780. /*
  12781. ** When a sub-program is executed (OP_Program), a structure of this type
  12782. ** is allocated to store the current value of the program counter, as
  12783. ** well as the current memory cell array and various other frame specific
  12784. ** values stored in the Vdbe struct. When the sub-program is finished,
  12785. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12786. ** restoring the state of the VM to as it was before the sub-program
  12787. ** began executing.
  12788. **
  12789. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12790. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12791. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12792. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12793. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12794. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12795. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12796. ** child frame are released.
  12797. **
  12798. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12799. ** set to NULL if the currently executing frame is the main program.
  12800. */
  12801. typedef struct VdbeFrame VdbeFrame;
  12802. struct VdbeFrame {
  12803. Vdbe *v; /* VM this frame belongs to */
  12804. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12805. Op *aOp; /* Program instructions for parent frame */
  12806. Mem *aMem; /* Array of memory cells for parent frame */
  12807. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12808. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12809. void *token; /* Copy of SubProgram.token */
  12810. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12811. int nCursor; /* Number of entries in apCsr */
  12812. int pc; /* Program Counter in parent (calling) frame */
  12813. int nOp; /* Size of aOp array */
  12814. int nMem; /* Number of entries in aMem */
  12815. int nOnceFlag; /* Number of entries in aOnceFlag */
  12816. int nChildMem; /* Number of memory cells for child frame */
  12817. int nChildCsr; /* Number of cursors for child frame */
  12818. int nChange; /* Statement changes (Vdbe.nChanges) */
  12819. };
  12820. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12821. /*
  12822. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12823. */
  12824. #define CACHE_STALE 0
  12825. /*
  12826. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12827. ** structures. Each Mem struct may cache multiple representations (string,
  12828. ** integer etc.) of the same value.
  12829. */
  12830. struct Mem {
  12831. sqlite3 *db; /* The associated database connection */
  12832. char *z; /* String or BLOB value */
  12833. double r; /* Real value */
  12834. union {
  12835. i64 i; /* Integer value used when MEM_Int is set in flags */
  12836. int nZero; /* Used when bit MEM_Zero is set in flags */
  12837. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12838. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12839. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12840. } u;
  12841. int n; /* Number of characters in string value, excluding '\0' */
  12842. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12843. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12844. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12845. #ifdef SQLITE_DEBUG
  12846. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12847. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12848. #endif
  12849. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12850. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12851. };
  12852. /* One or more of the following flags are set to indicate the validOK
  12853. ** representations of the value stored in the Mem struct.
  12854. **
  12855. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12856. ** No other flags may be set in this case.
  12857. **
  12858. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12859. ** Usually this is encoded in the same unicode encoding as the main
  12860. ** database (see below for exceptions). If the MEM_Term flag is also
  12861. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12862. ** flags may coexist with the MEM_Str flag.
  12863. */
  12864. #define MEM_Null 0x0001 /* Value is NULL */
  12865. #define MEM_Str 0x0002 /* Value is a string */
  12866. #define MEM_Int 0x0004 /* Value is an integer */
  12867. #define MEM_Real 0x0008 /* Value is a real number */
  12868. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12869. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12870. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12871. #define MEM_Invalid 0x0080 /* Value is undefined */
  12872. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12873. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12874. /* Whenever Mem contains a valid string or blob representation, one of
  12875. ** the following flags must be set to determine the memory management
  12876. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12877. ** string is \000 or \u0000 terminated
  12878. */
  12879. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12880. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12881. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12882. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12883. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12884. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12885. #ifdef SQLITE_OMIT_INCRBLOB
  12886. #undef MEM_Zero
  12887. #define MEM_Zero 0x0000
  12888. #endif
  12889. /*
  12890. ** Clear any existing type flags from a Mem and replace them with f
  12891. */
  12892. #define MemSetTypeFlag(p, f) \
  12893. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12894. /*
  12895. ** Return true if a memory cell is not marked as invalid. This macro
  12896. ** is for use inside assert() statements only.
  12897. */
  12898. #ifdef SQLITE_DEBUG
  12899. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12900. #endif
  12901. /*
  12902. ** Each auxilliary data pointer stored by a user defined function
  12903. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  12904. ** of this structure. All such structures associated with a single VM
  12905. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  12906. ** when the VM is halted (if not before).
  12907. */
  12908. struct AuxData {
  12909. int iOp; /* Instruction number of OP_Function opcode */
  12910. int iArg; /* Index of function argument. */
  12911. void *pAux; /* Aux data pointer */
  12912. void (*xDelete)(void *); /* Destructor for the aux data */
  12913. AuxData *pNext; /* Next element in list */
  12914. };
  12915. /*
  12916. ** The "context" argument for a installable function. A pointer to an
  12917. ** instance of this structure is the first argument to the routines used
  12918. ** implement the SQL functions.
  12919. **
  12920. ** There is a typedef for this structure in sqlite.h. So all routines,
  12921. ** even the public interface to SQLite, can use a pointer to this structure.
  12922. ** But this file is the only place where the internal details of this
  12923. ** structure are known.
  12924. **
  12925. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12926. ** (Mem) which are only defined there.
  12927. */
  12928. struct sqlite3_context {
  12929. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12930. Mem s; /* The return value is stored here */
  12931. Mem *pMem; /* Memory cell used to store aggregate context */
  12932. CollSeq *pColl; /* Collating sequence */
  12933. Vdbe *pVdbe; /* The VM that owns this context */
  12934. int iOp; /* Instruction number of OP_Function */
  12935. int isError; /* Error code returned by the function. */
  12936. u8 skipFlag; /* Skip skip accumulator loading if true */
  12937. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  12938. };
  12939. /*
  12940. ** An Explain object accumulates indented output which is helpful
  12941. ** in describing recursive data structures.
  12942. */
  12943. struct Explain {
  12944. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12945. StrAccum str; /* The string being accumulated */
  12946. int nIndent; /* Number of elements in aIndent */
  12947. u16 aIndent[100]; /* Levels of indentation */
  12948. char zBase[100]; /* Initial space */
  12949. };
  12950. /* A bitfield type for use inside of structures. Always follow with :N where
  12951. ** N is the number of bits.
  12952. */
  12953. typedef unsigned bft; /* Bit Field Type */
  12954. /*
  12955. ** An instance of the virtual machine. This structure contains the complete
  12956. ** state of the virtual machine.
  12957. **
  12958. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12959. ** is really a pointer to an instance of this structure.
  12960. **
  12961. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12962. ** any virtual table method invocations made by the vdbe program. It is
  12963. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12964. ** variable is used for two purposes: to allow xDestroy methods to execute
  12965. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12966. ** malloc failure when SQLite is invoked recursively by a virtual table
  12967. ** method function.
  12968. */
  12969. struct Vdbe {
  12970. sqlite3 *db; /* The database connection that owns this statement */
  12971. Op *aOp; /* Space to hold the virtual machine's program */
  12972. Mem *aMem; /* The memory locations */
  12973. Mem **apArg; /* Arguments to currently executing user function */
  12974. Mem *aColName; /* Column names to return */
  12975. Mem *pResultSet; /* Pointer to an array of results */
  12976. int nMem; /* Number of memory locations currently allocated */
  12977. int nOp; /* Number of instructions in the program */
  12978. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12979. int nLabel; /* Number of labels used */
  12980. int *aLabel; /* Space to hold the labels */
  12981. u16 nResColumn; /* Number of columns in one row of the result set */
  12982. int nCursor; /* Number of slots in apCsr[] */
  12983. u32 magic; /* Magic number for sanity checking */
  12984. char *zErrMsg; /* Error message written here */
  12985. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12986. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12987. Mem *aVar; /* Values for the OP_Variable opcode. */
  12988. char **azVar; /* Name of variables */
  12989. ynVar nVar; /* Number of entries in aVar[] */
  12990. ynVar nzVar; /* Number of entries in azVar[] */
  12991. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12992. int pc; /* The program counter */
  12993. int rc; /* Value to return */
  12994. u8 errorAction; /* Recovery action to do in case of an error */
  12995. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12996. bft explain:2; /* True if EXPLAIN present on SQL command */
  12997. bft inVtabMethod:2; /* See comments above */
  12998. bft changeCntOn:1; /* True to update the change-counter */
  12999. bft expired:1; /* True if the VM needs to be recompiled */
  13000. bft runOnlyOnce:1; /* Automatically expire on reset */
  13001. bft usesStmtJournal:1; /* True if uses a statement journal */
  13002. bft readOnly:1; /* True for statements that do not write */
  13003. bft bIsReader:1; /* True for statements that read */
  13004. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  13005. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  13006. int nChange; /* Number of db changes made since last reset */
  13007. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  13008. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13009. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13010. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13011. #ifndef SQLITE_OMIT_TRACE
  13012. i64 startTime; /* Time when query started - used for profiling */
  13013. #endif
  13014. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13015. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13016. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13017. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13018. char *zSql; /* Text of the SQL statement that generated this */
  13019. void *pFree; /* Free this when deleting the vdbe */
  13020. #ifdef SQLITE_DEBUG
  13021. FILE *trace; /* Write an execution trace here, if not NULL */
  13022. #endif
  13023. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  13024. Explain *pExplain; /* The explainer */
  13025. char *zExplain; /* Explanation of data structures */
  13026. #endif
  13027. VdbeFrame *pFrame; /* Parent frame */
  13028. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13029. int nFrame; /* Number of frames in pFrame list */
  13030. u32 expmask; /* Binding to these vars invalidates VM */
  13031. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13032. int nOnceFlag; /* Size of array aOnceFlag[] */
  13033. u8 *aOnceFlag; /* Flags for OP_Once */
  13034. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13035. };
  13036. /*
  13037. ** The following are allowed values for Vdbe.magic
  13038. */
  13039. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13040. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13041. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13042. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13043. /*
  13044. ** Function prototypes
  13045. */
  13046. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13047. void sqliteVdbePopStack(Vdbe*,int);
  13048. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13049. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13050. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13051. #endif
  13052. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13053. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13054. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  13055. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13056. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13057. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13058. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  13059. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  13060. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13061. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13062. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13063. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13064. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13065. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13066. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13067. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13068. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13069. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13070. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13071. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13072. #ifdef SQLITE_OMIT_FLOATING_POINT
  13073. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13074. #else
  13075. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13076. #endif
  13077. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13078. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13079. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13080. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13081. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  13082. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13083. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13084. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13085. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13086. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13087. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13088. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  13089. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13090. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  13091. #define VdbeMemRelease(X) \
  13092. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  13093. sqlite3VdbeMemReleaseExternal(X);
  13094. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13095. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13096. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13097. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13098. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13099. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13100. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  13101. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13102. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  13103. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13104. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13105. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13106. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  13107. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  13108. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  13109. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13110. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13111. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13112. #else
  13113. # define sqlite3VdbeEnter(X)
  13114. # define sqlite3VdbeLeave(X)
  13115. #endif
  13116. #ifdef SQLITE_DEBUG
  13117. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13118. #endif
  13119. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13120. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13121. #else
  13122. # define sqlite3VdbeCheckFk(p,i) 0
  13123. #endif
  13124. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13125. #ifdef SQLITE_DEBUG
  13126. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13127. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13128. #endif
  13129. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13130. #ifndef SQLITE_OMIT_INCRBLOB
  13131. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13132. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13133. #else
  13134. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13135. #define ExpandBlob(P) SQLITE_OK
  13136. #endif
  13137. #endif /* !defined(_VDBEINT_H_) */
  13138. /************** End of vdbeInt.h *********************************************/
  13139. /************** Continuing where we left off in status.c *********************/
  13140. /*
  13141. ** Variables in which to record status information.
  13142. */
  13143. typedef struct sqlite3StatType sqlite3StatType;
  13144. static SQLITE_WSD struct sqlite3StatType {
  13145. int nowValue[10]; /* Current value */
  13146. int mxValue[10]; /* Maximum value */
  13147. } sqlite3Stat = { {0,}, {0,} };
  13148. /* The "wsdStat" macro will resolve to the status information
  13149. ** state vector. If writable static data is unsupported on the target,
  13150. ** we have to locate the state vector at run-time. In the more common
  13151. ** case where writable static data is supported, wsdStat can refer directly
  13152. ** to the "sqlite3Stat" state vector declared above.
  13153. */
  13154. #ifdef SQLITE_OMIT_WSD
  13155. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13156. # define wsdStat x[0]
  13157. #else
  13158. # define wsdStatInit
  13159. # define wsdStat sqlite3Stat
  13160. #endif
  13161. /*
  13162. ** Return the current value of a status parameter.
  13163. */
  13164. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13165. wsdStatInit;
  13166. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13167. return wsdStat.nowValue[op];
  13168. }
  13169. /*
  13170. ** Add N to the value of a status record. It is assumed that the
  13171. ** caller holds appropriate locks.
  13172. */
  13173. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13174. wsdStatInit;
  13175. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13176. wsdStat.nowValue[op] += N;
  13177. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13178. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13179. }
  13180. }
  13181. /*
  13182. ** Set the value of a status to X.
  13183. */
  13184. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13185. wsdStatInit;
  13186. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13187. wsdStat.nowValue[op] = X;
  13188. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13189. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13190. }
  13191. }
  13192. /*
  13193. ** Query status information.
  13194. **
  13195. ** This implementation assumes that reading or writing an aligned
  13196. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13197. ** then this routine is not threadsafe.
  13198. */
  13199. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13200. wsdStatInit;
  13201. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13202. return SQLITE_MISUSE_BKPT;
  13203. }
  13204. *pCurrent = wsdStat.nowValue[op];
  13205. *pHighwater = wsdStat.mxValue[op];
  13206. if( resetFlag ){
  13207. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13208. }
  13209. return SQLITE_OK;
  13210. }
  13211. /*
  13212. ** Query status information for a single database connection
  13213. */
  13214. SQLITE_API int sqlite3_db_status(
  13215. sqlite3 *db, /* The database connection whose status is desired */
  13216. int op, /* Status verb */
  13217. int *pCurrent, /* Write current value here */
  13218. int *pHighwater, /* Write high-water mark here */
  13219. int resetFlag /* Reset high-water mark if true */
  13220. ){
  13221. int rc = SQLITE_OK; /* Return code */
  13222. sqlite3_mutex_enter(db->mutex);
  13223. switch( op ){
  13224. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13225. *pCurrent = db->lookaside.nOut;
  13226. *pHighwater = db->lookaside.mxOut;
  13227. if( resetFlag ){
  13228. db->lookaside.mxOut = db->lookaside.nOut;
  13229. }
  13230. break;
  13231. }
  13232. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13233. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13234. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13235. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13236. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13237. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13238. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13239. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13240. *pCurrent = 0;
  13241. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13242. if( resetFlag ){
  13243. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13244. }
  13245. break;
  13246. }
  13247. /*
  13248. ** Return an approximation for the amount of memory currently used
  13249. ** by all pagers associated with the given database connection. The
  13250. ** highwater mark is meaningless and is returned as zero.
  13251. */
  13252. case SQLITE_DBSTATUS_CACHE_USED: {
  13253. int totalUsed = 0;
  13254. int i;
  13255. sqlite3BtreeEnterAll(db);
  13256. for(i=0; i<db->nDb; i++){
  13257. Btree *pBt = db->aDb[i].pBt;
  13258. if( pBt ){
  13259. Pager *pPager = sqlite3BtreePager(pBt);
  13260. totalUsed += sqlite3PagerMemUsed(pPager);
  13261. }
  13262. }
  13263. sqlite3BtreeLeaveAll(db);
  13264. *pCurrent = totalUsed;
  13265. *pHighwater = 0;
  13266. break;
  13267. }
  13268. /*
  13269. ** *pCurrent gets an accurate estimate of the amount of memory used
  13270. ** to store the schema for all databases (main, temp, and any ATTACHed
  13271. ** databases. *pHighwater is set to zero.
  13272. */
  13273. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13274. int i; /* Used to iterate through schemas */
  13275. int nByte = 0; /* Used to accumulate return value */
  13276. sqlite3BtreeEnterAll(db);
  13277. db->pnBytesFreed = &nByte;
  13278. for(i=0; i<db->nDb; i++){
  13279. Schema *pSchema = db->aDb[i].pSchema;
  13280. if( ALWAYS(pSchema!=0) ){
  13281. HashElem *p;
  13282. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13283. pSchema->tblHash.count
  13284. + pSchema->trigHash.count
  13285. + pSchema->idxHash.count
  13286. + pSchema->fkeyHash.count
  13287. );
  13288. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13289. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13290. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13291. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13292. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13293. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13294. }
  13295. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13296. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13297. }
  13298. }
  13299. }
  13300. db->pnBytesFreed = 0;
  13301. sqlite3BtreeLeaveAll(db);
  13302. *pHighwater = 0;
  13303. *pCurrent = nByte;
  13304. break;
  13305. }
  13306. /*
  13307. ** *pCurrent gets an accurate estimate of the amount of memory used
  13308. ** to store all prepared statements.
  13309. ** *pHighwater is set to zero.
  13310. */
  13311. case SQLITE_DBSTATUS_STMT_USED: {
  13312. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13313. int nByte = 0; /* Used to accumulate return value */
  13314. db->pnBytesFreed = &nByte;
  13315. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13316. sqlite3VdbeClearObject(db, pVdbe);
  13317. sqlite3DbFree(db, pVdbe);
  13318. }
  13319. db->pnBytesFreed = 0;
  13320. *pHighwater = 0;
  13321. *pCurrent = nByte;
  13322. break;
  13323. }
  13324. /*
  13325. ** Set *pCurrent to the total cache hits or misses encountered by all
  13326. ** pagers the database handle is connected to. *pHighwater is always set
  13327. ** to zero.
  13328. */
  13329. case SQLITE_DBSTATUS_CACHE_HIT:
  13330. case SQLITE_DBSTATUS_CACHE_MISS:
  13331. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13332. int i;
  13333. int nRet = 0;
  13334. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13335. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13336. for(i=0; i<db->nDb; i++){
  13337. if( db->aDb[i].pBt ){
  13338. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13339. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13340. }
  13341. }
  13342. *pHighwater = 0;
  13343. *pCurrent = nRet;
  13344. break;
  13345. }
  13346. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  13347. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  13348. ** have been satisfied. The *pHighwater is always set to zero.
  13349. */
  13350. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  13351. *pHighwater = 0;
  13352. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  13353. break;
  13354. }
  13355. default: {
  13356. rc = SQLITE_ERROR;
  13357. }
  13358. }
  13359. sqlite3_mutex_leave(db->mutex);
  13360. return rc;
  13361. }
  13362. /************** End of status.c **********************************************/
  13363. /************** Begin file date.c ********************************************/
  13364. /*
  13365. ** 2003 October 31
  13366. **
  13367. ** The author disclaims copyright to this source code. In place of
  13368. ** a legal notice, here is a blessing:
  13369. **
  13370. ** May you do good and not evil.
  13371. ** May you find forgiveness for yourself and forgive others.
  13372. ** May you share freely, never taking more than you give.
  13373. **
  13374. *************************************************************************
  13375. ** This file contains the C functions that implement date and time
  13376. ** functions for SQLite.
  13377. **
  13378. ** There is only one exported symbol in this file - the function
  13379. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13380. ** All other code has file scope.
  13381. **
  13382. ** SQLite processes all times and dates as Julian Day numbers. The
  13383. ** dates and times are stored as the number of days since noon
  13384. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13385. ** calendar system.
  13386. **
  13387. ** 1970-01-01 00:00:00 is JD 2440587.5
  13388. ** 2000-01-01 00:00:00 is JD 2451544.5
  13389. **
  13390. ** This implemention requires years to be expressed as a 4-digit number
  13391. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13392. ** be represented, even though julian day numbers allow a much wider
  13393. ** range of dates.
  13394. **
  13395. ** The Gregorian calendar system is used for all dates and times,
  13396. ** even those that predate the Gregorian calendar. Historians usually
  13397. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13398. ** dates afterwards, depending on locale. Beware of this difference.
  13399. **
  13400. ** The conversion algorithms are implemented based on descriptions
  13401. ** in the following text:
  13402. **
  13403. ** Jean Meeus
  13404. ** Astronomical Algorithms, 2nd Edition, 1998
  13405. ** ISBM 0-943396-61-1
  13406. ** Willmann-Bell, Inc
  13407. ** Richmond, Virginia (USA)
  13408. */
  13409. /* #include <stdlib.h> */
  13410. /* #include <assert.h> */
  13411. #include <time.h>
  13412. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13413. /*
  13414. ** A structure for holding a single date and time.
  13415. */
  13416. typedef struct DateTime DateTime;
  13417. struct DateTime {
  13418. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13419. int Y, M, D; /* Year, month, and day */
  13420. int h, m; /* Hour and minutes */
  13421. int tz; /* Timezone offset in minutes */
  13422. double s; /* Seconds */
  13423. char validYMD; /* True (1) if Y,M,D are valid */
  13424. char validHMS; /* True (1) if h,m,s are valid */
  13425. char validJD; /* True (1) if iJD is valid */
  13426. char validTZ; /* True (1) if tz is valid */
  13427. };
  13428. /*
  13429. ** Convert zDate into one or more integers. Additional arguments
  13430. ** come in groups of 5 as follows:
  13431. **
  13432. ** N number of digits in the integer
  13433. ** min minimum allowed value of the integer
  13434. ** max maximum allowed value of the integer
  13435. ** nextC first character after the integer
  13436. ** pVal where to write the integers value.
  13437. **
  13438. ** Conversions continue until one with nextC==0 is encountered.
  13439. ** The function returns the number of successful conversions.
  13440. */
  13441. static int getDigits(const char *zDate, ...){
  13442. va_list ap;
  13443. int val;
  13444. int N;
  13445. int min;
  13446. int max;
  13447. int nextC;
  13448. int *pVal;
  13449. int cnt = 0;
  13450. va_start(ap, zDate);
  13451. do{
  13452. N = va_arg(ap, int);
  13453. min = va_arg(ap, int);
  13454. max = va_arg(ap, int);
  13455. nextC = va_arg(ap, int);
  13456. pVal = va_arg(ap, int*);
  13457. val = 0;
  13458. while( N-- ){
  13459. if( !sqlite3Isdigit(*zDate) ){
  13460. goto end_getDigits;
  13461. }
  13462. val = val*10 + *zDate - '0';
  13463. zDate++;
  13464. }
  13465. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13466. goto end_getDigits;
  13467. }
  13468. *pVal = val;
  13469. zDate++;
  13470. cnt++;
  13471. }while( nextC );
  13472. end_getDigits:
  13473. va_end(ap);
  13474. return cnt;
  13475. }
  13476. /*
  13477. ** Parse a timezone extension on the end of a date-time.
  13478. ** The extension is of the form:
  13479. **
  13480. ** (+/-)HH:MM
  13481. **
  13482. ** Or the "zulu" notation:
  13483. **
  13484. ** Z
  13485. **
  13486. ** If the parse is successful, write the number of minutes
  13487. ** of change in p->tz and return 0. If a parser error occurs,
  13488. ** return non-zero.
  13489. **
  13490. ** A missing specifier is not considered an error.
  13491. */
  13492. static int parseTimezone(const char *zDate, DateTime *p){
  13493. int sgn = 0;
  13494. int nHr, nMn;
  13495. int c;
  13496. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13497. p->tz = 0;
  13498. c = *zDate;
  13499. if( c=='-' ){
  13500. sgn = -1;
  13501. }else if( c=='+' ){
  13502. sgn = +1;
  13503. }else if( c=='Z' || c=='z' ){
  13504. zDate++;
  13505. goto zulu_time;
  13506. }else{
  13507. return c!=0;
  13508. }
  13509. zDate++;
  13510. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13511. return 1;
  13512. }
  13513. zDate += 5;
  13514. p->tz = sgn*(nMn + nHr*60);
  13515. zulu_time:
  13516. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13517. return *zDate!=0;
  13518. }
  13519. /*
  13520. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13521. ** The HH, MM, and SS must each be exactly 2 digits. The
  13522. ** fractional seconds FFFF can be one or more digits.
  13523. **
  13524. ** Return 1 if there is a parsing error and 0 on success.
  13525. */
  13526. static int parseHhMmSs(const char *zDate, DateTime *p){
  13527. int h, m, s;
  13528. double ms = 0.0;
  13529. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13530. return 1;
  13531. }
  13532. zDate += 5;
  13533. if( *zDate==':' ){
  13534. zDate++;
  13535. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13536. return 1;
  13537. }
  13538. zDate += 2;
  13539. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13540. double rScale = 1.0;
  13541. zDate++;
  13542. while( sqlite3Isdigit(*zDate) ){
  13543. ms = ms*10.0 + *zDate - '0';
  13544. rScale *= 10.0;
  13545. zDate++;
  13546. }
  13547. ms /= rScale;
  13548. }
  13549. }else{
  13550. s = 0;
  13551. }
  13552. p->validJD = 0;
  13553. p->validHMS = 1;
  13554. p->h = h;
  13555. p->m = m;
  13556. p->s = s + ms;
  13557. if( parseTimezone(zDate, p) ) return 1;
  13558. p->validTZ = (p->tz!=0)?1:0;
  13559. return 0;
  13560. }
  13561. /*
  13562. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13563. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13564. **
  13565. ** Reference: Meeus page 61
  13566. */
  13567. static void computeJD(DateTime *p){
  13568. int Y, M, D, A, B, X1, X2;
  13569. if( p->validJD ) return;
  13570. if( p->validYMD ){
  13571. Y = p->Y;
  13572. M = p->M;
  13573. D = p->D;
  13574. }else{
  13575. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13576. M = 1;
  13577. D = 1;
  13578. }
  13579. if( M<=2 ){
  13580. Y--;
  13581. M += 12;
  13582. }
  13583. A = Y/100;
  13584. B = 2 - A + (A/4);
  13585. X1 = 36525*(Y+4716)/100;
  13586. X2 = 306001*(M+1)/10000;
  13587. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13588. p->validJD = 1;
  13589. if( p->validHMS ){
  13590. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13591. if( p->validTZ ){
  13592. p->iJD -= p->tz*60000;
  13593. p->validYMD = 0;
  13594. p->validHMS = 0;
  13595. p->validTZ = 0;
  13596. }
  13597. }
  13598. }
  13599. /*
  13600. ** Parse dates of the form
  13601. **
  13602. ** YYYY-MM-DD HH:MM:SS.FFF
  13603. ** YYYY-MM-DD HH:MM:SS
  13604. ** YYYY-MM-DD HH:MM
  13605. ** YYYY-MM-DD
  13606. **
  13607. ** Write the result into the DateTime structure and return 0
  13608. ** on success and 1 if the input string is not a well-formed
  13609. ** date.
  13610. */
  13611. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13612. int Y, M, D, neg;
  13613. if( zDate[0]=='-' ){
  13614. zDate++;
  13615. neg = 1;
  13616. }else{
  13617. neg = 0;
  13618. }
  13619. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13620. return 1;
  13621. }
  13622. zDate += 10;
  13623. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13624. if( parseHhMmSs(zDate, p)==0 ){
  13625. /* We got the time */
  13626. }else if( *zDate==0 ){
  13627. p->validHMS = 0;
  13628. }else{
  13629. return 1;
  13630. }
  13631. p->validJD = 0;
  13632. p->validYMD = 1;
  13633. p->Y = neg ? -Y : Y;
  13634. p->M = M;
  13635. p->D = D;
  13636. if( p->validTZ ){
  13637. computeJD(p);
  13638. }
  13639. return 0;
  13640. }
  13641. /*
  13642. ** Set the time to the current time reported by the VFS.
  13643. **
  13644. ** Return the number of errors.
  13645. */
  13646. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13647. p->iJD = sqlite3StmtCurrentTime(context);
  13648. if( p->iJD>0 ){
  13649. p->validJD = 1;
  13650. return 0;
  13651. }else{
  13652. return 1;
  13653. }
  13654. }
  13655. /*
  13656. ** Attempt to parse the given string into a Julian Day Number. Return
  13657. ** the number of errors.
  13658. **
  13659. ** The following are acceptable forms for the input string:
  13660. **
  13661. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13662. ** DDDD.DD
  13663. ** now
  13664. **
  13665. ** In the first form, the +/-HH:MM is always optional. The fractional
  13666. ** seconds extension (the ".FFF") is optional. The seconds portion
  13667. ** (":SS.FFF") is option. The year and date can be omitted as long
  13668. ** as there is a time string. The time string can be omitted as long
  13669. ** as there is a year and date.
  13670. */
  13671. static int parseDateOrTime(
  13672. sqlite3_context *context,
  13673. const char *zDate,
  13674. DateTime *p
  13675. ){
  13676. double r;
  13677. if( parseYyyyMmDd(zDate,p)==0 ){
  13678. return 0;
  13679. }else if( parseHhMmSs(zDate, p)==0 ){
  13680. return 0;
  13681. }else if( sqlite3StrICmp(zDate,"now")==0){
  13682. return setDateTimeToCurrent(context, p);
  13683. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13684. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13685. p->validJD = 1;
  13686. return 0;
  13687. }
  13688. return 1;
  13689. }
  13690. /*
  13691. ** Compute the Year, Month, and Day from the julian day number.
  13692. */
  13693. static void computeYMD(DateTime *p){
  13694. int Z, A, B, C, D, E, X1;
  13695. if( p->validYMD ) return;
  13696. if( !p->validJD ){
  13697. p->Y = 2000;
  13698. p->M = 1;
  13699. p->D = 1;
  13700. }else{
  13701. Z = (int)((p->iJD + 43200000)/86400000);
  13702. A = (int)((Z - 1867216.25)/36524.25);
  13703. A = Z + 1 + A - (A/4);
  13704. B = A + 1524;
  13705. C = (int)((B - 122.1)/365.25);
  13706. D = (36525*C)/100;
  13707. E = (int)((B-D)/30.6001);
  13708. X1 = (int)(30.6001*E);
  13709. p->D = B - D - X1;
  13710. p->M = E<14 ? E-1 : E-13;
  13711. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13712. }
  13713. p->validYMD = 1;
  13714. }
  13715. /*
  13716. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13717. */
  13718. static void computeHMS(DateTime *p){
  13719. int s;
  13720. if( p->validHMS ) return;
  13721. computeJD(p);
  13722. s = (int)((p->iJD + 43200000) % 86400000);
  13723. p->s = s/1000.0;
  13724. s = (int)p->s;
  13725. p->s -= s;
  13726. p->h = s/3600;
  13727. s -= p->h*3600;
  13728. p->m = s/60;
  13729. p->s += s - p->m*60;
  13730. p->validHMS = 1;
  13731. }
  13732. /*
  13733. ** Compute both YMD and HMS
  13734. */
  13735. static void computeYMD_HMS(DateTime *p){
  13736. computeYMD(p);
  13737. computeHMS(p);
  13738. }
  13739. /*
  13740. ** Clear the YMD and HMS and the TZ
  13741. */
  13742. static void clearYMD_HMS_TZ(DateTime *p){
  13743. p->validYMD = 0;
  13744. p->validHMS = 0;
  13745. p->validTZ = 0;
  13746. }
  13747. /*
  13748. ** On recent Windows platforms, the localtime_s() function is available
  13749. ** as part of the "Secure CRT". It is essentially equivalent to
  13750. ** localtime_r() available under most POSIX platforms, except that the
  13751. ** order of the parameters is reversed.
  13752. **
  13753. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13754. **
  13755. ** If the user has not indicated to use localtime_r() or localtime_s()
  13756. ** already, check for an MSVC build environment that provides
  13757. ** localtime_s().
  13758. */
  13759. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13760. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13761. #define HAVE_LOCALTIME_S 1
  13762. #endif
  13763. #ifndef SQLITE_OMIT_LOCALTIME
  13764. /*
  13765. ** The following routine implements the rough equivalent of localtime_r()
  13766. ** using whatever operating-system specific localtime facility that
  13767. ** is available. This routine returns 0 on success and
  13768. ** non-zero on any kind of error.
  13769. **
  13770. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13771. ** routine will always fail.
  13772. **
  13773. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  13774. ** library function localtime_r() is used to assist in the calculation of
  13775. ** local time.
  13776. */
  13777. static int osLocaltime(time_t *t, struct tm *pTm){
  13778. int rc;
  13779. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13780. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13781. struct tm *pX;
  13782. #if SQLITE_THREADSAFE>0
  13783. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13784. #endif
  13785. sqlite3_mutex_enter(mutex);
  13786. pX = localtime(t);
  13787. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13788. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13789. #endif
  13790. if( pX ) *pTm = *pX;
  13791. sqlite3_mutex_leave(mutex);
  13792. rc = pX==0;
  13793. #else
  13794. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13795. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13796. #endif
  13797. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13798. rc = localtime_r(t, pTm)==0;
  13799. #else
  13800. rc = localtime_s(pTm, t);
  13801. #endif /* HAVE_LOCALTIME_R */
  13802. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13803. return rc;
  13804. }
  13805. #endif /* SQLITE_OMIT_LOCALTIME */
  13806. #ifndef SQLITE_OMIT_LOCALTIME
  13807. /*
  13808. ** Compute the difference (in milliseconds) between localtime and UTC
  13809. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13810. ** return this value and set *pRc to SQLITE_OK.
  13811. **
  13812. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13813. ** is undefined in this case.
  13814. */
  13815. static sqlite3_int64 localtimeOffset(
  13816. DateTime *p, /* Date at which to calculate offset */
  13817. sqlite3_context *pCtx, /* Write error here if one occurs */
  13818. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13819. ){
  13820. DateTime x, y;
  13821. time_t t;
  13822. struct tm sLocal;
  13823. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13824. memset(&sLocal, 0, sizeof(sLocal));
  13825. x = *p;
  13826. computeYMD_HMS(&x);
  13827. if( x.Y<1971 || x.Y>=2038 ){
  13828. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  13829. ** works for years between 1970 and 2037. For dates outside this range,
  13830. ** SQLite attempts to map the year into an equivalent year within this
  13831. ** range, do the calculation, then map the year back.
  13832. */
  13833. x.Y = 2000;
  13834. x.M = 1;
  13835. x.D = 1;
  13836. x.h = 0;
  13837. x.m = 0;
  13838. x.s = 0.0;
  13839. } else {
  13840. int s = (int)(x.s + 0.5);
  13841. x.s = s;
  13842. }
  13843. x.tz = 0;
  13844. x.validJD = 0;
  13845. computeJD(&x);
  13846. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13847. if( osLocaltime(&t, &sLocal) ){
  13848. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13849. *pRc = SQLITE_ERROR;
  13850. return 0;
  13851. }
  13852. y.Y = sLocal.tm_year + 1900;
  13853. y.M = sLocal.tm_mon + 1;
  13854. y.D = sLocal.tm_mday;
  13855. y.h = sLocal.tm_hour;
  13856. y.m = sLocal.tm_min;
  13857. y.s = sLocal.tm_sec;
  13858. y.validYMD = 1;
  13859. y.validHMS = 1;
  13860. y.validJD = 0;
  13861. y.validTZ = 0;
  13862. computeJD(&y);
  13863. *pRc = SQLITE_OK;
  13864. return y.iJD - x.iJD;
  13865. }
  13866. #endif /* SQLITE_OMIT_LOCALTIME */
  13867. /*
  13868. ** Process a modifier to a date-time stamp. The modifiers are
  13869. ** as follows:
  13870. **
  13871. ** NNN days
  13872. ** NNN hours
  13873. ** NNN minutes
  13874. ** NNN.NNNN seconds
  13875. ** NNN months
  13876. ** NNN years
  13877. ** start of month
  13878. ** start of year
  13879. ** start of week
  13880. ** start of day
  13881. ** weekday N
  13882. ** unixepoch
  13883. ** localtime
  13884. ** utc
  13885. **
  13886. ** Return 0 on success and 1 if there is any kind of error. If the error
  13887. ** is in a system call (i.e. localtime()), then an error message is written
  13888. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13889. ** written to pCtx.
  13890. */
  13891. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13892. int rc = 1;
  13893. int n;
  13894. double r;
  13895. char *z, zBuf[30];
  13896. z = zBuf;
  13897. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13898. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13899. }
  13900. z[n] = 0;
  13901. switch( z[0] ){
  13902. #ifndef SQLITE_OMIT_LOCALTIME
  13903. case 'l': {
  13904. /* localtime
  13905. **
  13906. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13907. ** show local time.
  13908. */
  13909. if( strcmp(z, "localtime")==0 ){
  13910. computeJD(p);
  13911. p->iJD += localtimeOffset(p, pCtx, &rc);
  13912. clearYMD_HMS_TZ(p);
  13913. }
  13914. break;
  13915. }
  13916. #endif
  13917. case 'u': {
  13918. /*
  13919. ** unixepoch
  13920. **
  13921. ** Treat the current value of p->iJD as the number of
  13922. ** seconds since 1970. Convert to a real julian day number.
  13923. */
  13924. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13925. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13926. clearYMD_HMS_TZ(p);
  13927. rc = 0;
  13928. }
  13929. #ifndef SQLITE_OMIT_LOCALTIME
  13930. else if( strcmp(z, "utc")==0 ){
  13931. sqlite3_int64 c1;
  13932. computeJD(p);
  13933. c1 = localtimeOffset(p, pCtx, &rc);
  13934. if( rc==SQLITE_OK ){
  13935. p->iJD -= c1;
  13936. clearYMD_HMS_TZ(p);
  13937. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13938. }
  13939. }
  13940. #endif
  13941. break;
  13942. }
  13943. case 'w': {
  13944. /*
  13945. ** weekday N
  13946. **
  13947. ** Move the date to the same time on the next occurrence of
  13948. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13949. ** date is already on the appropriate weekday, this is a no-op.
  13950. */
  13951. if( strncmp(z, "weekday ", 8)==0
  13952. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13953. && (n=(int)r)==r && n>=0 && r<7 ){
  13954. sqlite3_int64 Z;
  13955. computeYMD_HMS(p);
  13956. p->validTZ = 0;
  13957. p->validJD = 0;
  13958. computeJD(p);
  13959. Z = ((p->iJD + 129600000)/86400000) % 7;
  13960. if( Z>n ) Z -= 7;
  13961. p->iJD += (n - Z)*86400000;
  13962. clearYMD_HMS_TZ(p);
  13963. rc = 0;
  13964. }
  13965. break;
  13966. }
  13967. case 's': {
  13968. /*
  13969. ** start of TTTTT
  13970. **
  13971. ** Move the date backwards to the beginning of the current day,
  13972. ** or month or year.
  13973. */
  13974. if( strncmp(z, "start of ", 9)!=0 ) break;
  13975. z += 9;
  13976. computeYMD(p);
  13977. p->validHMS = 1;
  13978. p->h = p->m = 0;
  13979. p->s = 0.0;
  13980. p->validTZ = 0;
  13981. p->validJD = 0;
  13982. if( strcmp(z,"month")==0 ){
  13983. p->D = 1;
  13984. rc = 0;
  13985. }else if( strcmp(z,"year")==0 ){
  13986. computeYMD(p);
  13987. p->M = 1;
  13988. p->D = 1;
  13989. rc = 0;
  13990. }else if( strcmp(z,"day")==0 ){
  13991. rc = 0;
  13992. }
  13993. break;
  13994. }
  13995. case '+':
  13996. case '-':
  13997. case '0':
  13998. case '1':
  13999. case '2':
  14000. case '3':
  14001. case '4':
  14002. case '5':
  14003. case '6':
  14004. case '7':
  14005. case '8':
  14006. case '9': {
  14007. double rRounder;
  14008. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14009. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14010. rc = 1;
  14011. break;
  14012. }
  14013. if( z[n]==':' ){
  14014. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14015. ** specified number of hours, minutes, seconds, and fractional seconds
  14016. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14017. ** omitted.
  14018. */
  14019. const char *z2 = z;
  14020. DateTime tx;
  14021. sqlite3_int64 day;
  14022. if( !sqlite3Isdigit(*z2) ) z2++;
  14023. memset(&tx, 0, sizeof(tx));
  14024. if( parseHhMmSs(z2, &tx) ) break;
  14025. computeJD(&tx);
  14026. tx.iJD -= 43200000;
  14027. day = tx.iJD/86400000;
  14028. tx.iJD -= day*86400000;
  14029. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14030. computeJD(p);
  14031. clearYMD_HMS_TZ(p);
  14032. p->iJD += tx.iJD;
  14033. rc = 0;
  14034. break;
  14035. }
  14036. z += n;
  14037. while( sqlite3Isspace(*z) ) z++;
  14038. n = sqlite3Strlen30(z);
  14039. if( n>10 || n<3 ) break;
  14040. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14041. computeJD(p);
  14042. rc = 0;
  14043. rRounder = r<0 ? -0.5 : +0.5;
  14044. if( n==3 && strcmp(z,"day")==0 ){
  14045. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14046. }else if( n==4 && strcmp(z,"hour")==0 ){
  14047. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14048. }else if( n==6 && strcmp(z,"minute")==0 ){
  14049. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14050. }else if( n==6 && strcmp(z,"second")==0 ){
  14051. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14052. }else if( n==5 && strcmp(z,"month")==0 ){
  14053. int x, y;
  14054. computeYMD_HMS(p);
  14055. p->M += (int)r;
  14056. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14057. p->Y += x;
  14058. p->M -= x*12;
  14059. p->validJD = 0;
  14060. computeJD(p);
  14061. y = (int)r;
  14062. if( y!=r ){
  14063. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14064. }
  14065. }else if( n==4 && strcmp(z,"year")==0 ){
  14066. int y = (int)r;
  14067. computeYMD_HMS(p);
  14068. p->Y += y;
  14069. p->validJD = 0;
  14070. computeJD(p);
  14071. if( y!=r ){
  14072. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14073. }
  14074. }else{
  14075. rc = 1;
  14076. }
  14077. clearYMD_HMS_TZ(p);
  14078. break;
  14079. }
  14080. default: {
  14081. break;
  14082. }
  14083. }
  14084. return rc;
  14085. }
  14086. /*
  14087. ** Process time function arguments. argv[0] is a date-time stamp.
  14088. ** argv[1] and following are modifiers. Parse them all and write
  14089. ** the resulting time into the DateTime structure p. Return 0
  14090. ** on success and 1 if there are any errors.
  14091. **
  14092. ** If there are zero parameters (if even argv[0] is undefined)
  14093. ** then assume a default value of "now" for argv[0].
  14094. */
  14095. static int isDate(
  14096. sqlite3_context *context,
  14097. int argc,
  14098. sqlite3_value **argv,
  14099. DateTime *p
  14100. ){
  14101. int i;
  14102. const unsigned char *z;
  14103. int eType;
  14104. memset(p, 0, sizeof(*p));
  14105. if( argc==0 ){
  14106. return setDateTimeToCurrent(context, p);
  14107. }
  14108. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14109. || eType==SQLITE_INTEGER ){
  14110. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14111. p->validJD = 1;
  14112. }else{
  14113. z = sqlite3_value_text(argv[0]);
  14114. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14115. return 1;
  14116. }
  14117. }
  14118. for(i=1; i<argc; i++){
  14119. z = sqlite3_value_text(argv[i]);
  14120. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14121. }
  14122. return 0;
  14123. }
  14124. /*
  14125. ** The following routines implement the various date and time functions
  14126. ** of SQLite.
  14127. */
  14128. /*
  14129. ** julianday( TIMESTRING, MOD, MOD, ...)
  14130. **
  14131. ** Return the julian day number of the date specified in the arguments
  14132. */
  14133. static void juliandayFunc(
  14134. sqlite3_context *context,
  14135. int argc,
  14136. sqlite3_value **argv
  14137. ){
  14138. DateTime x;
  14139. if( isDate(context, argc, argv, &x)==0 ){
  14140. computeJD(&x);
  14141. sqlite3_result_double(context, x.iJD/86400000.0);
  14142. }
  14143. }
  14144. /*
  14145. ** datetime( TIMESTRING, MOD, MOD, ...)
  14146. **
  14147. ** Return YYYY-MM-DD HH:MM:SS
  14148. */
  14149. static void datetimeFunc(
  14150. sqlite3_context *context,
  14151. int argc,
  14152. sqlite3_value **argv
  14153. ){
  14154. DateTime x;
  14155. if( isDate(context, argc, argv, &x)==0 ){
  14156. char zBuf[100];
  14157. computeYMD_HMS(&x);
  14158. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14159. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14160. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14161. }
  14162. }
  14163. /*
  14164. ** time( TIMESTRING, MOD, MOD, ...)
  14165. **
  14166. ** Return HH:MM:SS
  14167. */
  14168. static void timeFunc(
  14169. sqlite3_context *context,
  14170. int argc,
  14171. sqlite3_value **argv
  14172. ){
  14173. DateTime x;
  14174. if( isDate(context, argc, argv, &x)==0 ){
  14175. char zBuf[100];
  14176. computeHMS(&x);
  14177. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14178. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14179. }
  14180. }
  14181. /*
  14182. ** date( TIMESTRING, MOD, MOD, ...)
  14183. **
  14184. ** Return YYYY-MM-DD
  14185. */
  14186. static void dateFunc(
  14187. sqlite3_context *context,
  14188. int argc,
  14189. sqlite3_value **argv
  14190. ){
  14191. DateTime x;
  14192. if( isDate(context, argc, argv, &x)==0 ){
  14193. char zBuf[100];
  14194. computeYMD(&x);
  14195. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14196. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14197. }
  14198. }
  14199. /*
  14200. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14201. **
  14202. ** Return a string described by FORMAT. Conversions as follows:
  14203. **
  14204. ** %d day of month
  14205. ** %f ** fractional seconds SS.SSS
  14206. ** %H hour 00-24
  14207. ** %j day of year 000-366
  14208. ** %J ** Julian day number
  14209. ** %m month 01-12
  14210. ** %M minute 00-59
  14211. ** %s seconds since 1970-01-01
  14212. ** %S seconds 00-59
  14213. ** %w day of week 0-6 sunday==0
  14214. ** %W week of year 00-53
  14215. ** %Y year 0000-9999
  14216. ** %% %
  14217. */
  14218. static void strftimeFunc(
  14219. sqlite3_context *context,
  14220. int argc,
  14221. sqlite3_value **argv
  14222. ){
  14223. DateTime x;
  14224. u64 n;
  14225. size_t i,j;
  14226. char *z;
  14227. sqlite3 *db;
  14228. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14229. char zBuf[100];
  14230. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14231. db = sqlite3_context_db_handle(context);
  14232. for(i=0, n=1; zFmt[i]; i++, n++){
  14233. if( zFmt[i]=='%' ){
  14234. switch( zFmt[i+1] ){
  14235. case 'd':
  14236. case 'H':
  14237. case 'm':
  14238. case 'M':
  14239. case 'S':
  14240. case 'W':
  14241. n++;
  14242. /* fall thru */
  14243. case 'w':
  14244. case '%':
  14245. break;
  14246. case 'f':
  14247. n += 8;
  14248. break;
  14249. case 'j':
  14250. n += 3;
  14251. break;
  14252. case 'Y':
  14253. n += 8;
  14254. break;
  14255. case 's':
  14256. case 'J':
  14257. n += 50;
  14258. break;
  14259. default:
  14260. return; /* ERROR. return a NULL */
  14261. }
  14262. i++;
  14263. }
  14264. }
  14265. testcase( n==sizeof(zBuf)-1 );
  14266. testcase( n==sizeof(zBuf) );
  14267. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14268. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14269. if( n<sizeof(zBuf) ){
  14270. z = zBuf;
  14271. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14272. sqlite3_result_error_toobig(context);
  14273. return;
  14274. }else{
  14275. z = sqlite3DbMallocRaw(db, (int)n);
  14276. if( z==0 ){
  14277. sqlite3_result_error_nomem(context);
  14278. return;
  14279. }
  14280. }
  14281. computeJD(&x);
  14282. computeYMD_HMS(&x);
  14283. for(i=j=0; zFmt[i]; i++){
  14284. if( zFmt[i]!='%' ){
  14285. z[j++] = zFmt[i];
  14286. }else{
  14287. i++;
  14288. switch( zFmt[i] ){
  14289. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14290. case 'f': {
  14291. double s = x.s;
  14292. if( s>59.999 ) s = 59.999;
  14293. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14294. j += sqlite3Strlen30(&z[j]);
  14295. break;
  14296. }
  14297. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14298. case 'W': /* Fall thru */
  14299. case 'j': {
  14300. int nDay; /* Number of days since 1st day of year */
  14301. DateTime y = x;
  14302. y.validJD = 0;
  14303. y.M = 1;
  14304. y.D = 1;
  14305. computeJD(&y);
  14306. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14307. if( zFmt[i]=='W' ){
  14308. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14309. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14310. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14311. j += 2;
  14312. }else{
  14313. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14314. j += 3;
  14315. }
  14316. break;
  14317. }
  14318. case 'J': {
  14319. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14320. j+=sqlite3Strlen30(&z[j]);
  14321. break;
  14322. }
  14323. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14324. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14325. case 's': {
  14326. sqlite3_snprintf(30,&z[j],"%lld",
  14327. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14328. j += sqlite3Strlen30(&z[j]);
  14329. break;
  14330. }
  14331. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14332. case 'w': {
  14333. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14334. break;
  14335. }
  14336. case 'Y': {
  14337. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14338. break;
  14339. }
  14340. default: z[j++] = '%'; break;
  14341. }
  14342. }
  14343. }
  14344. z[j] = 0;
  14345. sqlite3_result_text(context, z, -1,
  14346. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14347. }
  14348. /*
  14349. ** current_time()
  14350. **
  14351. ** This function returns the same value as time('now').
  14352. */
  14353. static void ctimeFunc(
  14354. sqlite3_context *context,
  14355. int NotUsed,
  14356. sqlite3_value **NotUsed2
  14357. ){
  14358. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14359. timeFunc(context, 0, 0);
  14360. }
  14361. /*
  14362. ** current_date()
  14363. **
  14364. ** This function returns the same value as date('now').
  14365. */
  14366. static void cdateFunc(
  14367. sqlite3_context *context,
  14368. int NotUsed,
  14369. sqlite3_value **NotUsed2
  14370. ){
  14371. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14372. dateFunc(context, 0, 0);
  14373. }
  14374. /*
  14375. ** current_timestamp()
  14376. **
  14377. ** This function returns the same value as datetime('now').
  14378. */
  14379. static void ctimestampFunc(
  14380. sqlite3_context *context,
  14381. int NotUsed,
  14382. sqlite3_value **NotUsed2
  14383. ){
  14384. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14385. datetimeFunc(context, 0, 0);
  14386. }
  14387. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14388. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14389. /*
  14390. ** If the library is compiled to omit the full-scale date and time
  14391. ** handling (to get a smaller binary), the following minimal version
  14392. ** of the functions current_time(), current_date() and current_timestamp()
  14393. ** are included instead. This is to support column declarations that
  14394. ** include "DEFAULT CURRENT_TIME" etc.
  14395. **
  14396. ** This function uses the C-library functions time(), gmtime()
  14397. ** and strftime(). The format string to pass to strftime() is supplied
  14398. ** as the user-data for the function.
  14399. */
  14400. static void currentTimeFunc(
  14401. sqlite3_context *context,
  14402. int argc,
  14403. sqlite3_value **argv
  14404. ){
  14405. time_t t;
  14406. char *zFormat = (char *)sqlite3_user_data(context);
  14407. sqlite3 *db;
  14408. sqlite3_int64 iT;
  14409. struct tm *pTm;
  14410. struct tm sNow;
  14411. char zBuf[20];
  14412. UNUSED_PARAMETER(argc);
  14413. UNUSED_PARAMETER(argv);
  14414. iT = sqlite3StmtCurrentTime(context);
  14415. if( iT<=0 ) return;
  14416. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14417. #ifdef HAVE_GMTIME_R
  14418. pTm = gmtime_r(&t, &sNow);
  14419. #else
  14420. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14421. pTm = gmtime(&t);
  14422. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14423. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14424. #endif
  14425. if( pTm ){
  14426. strftime(zBuf, 20, zFormat, &sNow);
  14427. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14428. }
  14429. }
  14430. #endif
  14431. /*
  14432. ** This function registered all of the above C functions as SQL
  14433. ** functions. This should be the only routine in this file with
  14434. ** external linkage.
  14435. */
  14436. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14437. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14438. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14439. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14440. FUNCTION(date, -1, 0, 0, dateFunc ),
  14441. FUNCTION(time, -1, 0, 0, timeFunc ),
  14442. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14443. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14444. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14445. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14446. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14447. #else
  14448. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14449. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14450. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14451. #endif
  14452. };
  14453. int i;
  14454. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14455. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14456. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14457. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14458. }
  14459. }
  14460. /************** End of date.c ************************************************/
  14461. /************** Begin file os.c **********************************************/
  14462. /*
  14463. ** 2005 November 29
  14464. **
  14465. ** The author disclaims copyright to this source code. In place of
  14466. ** a legal notice, here is a blessing:
  14467. **
  14468. ** May you do good and not evil.
  14469. ** May you find forgiveness for yourself and forgive others.
  14470. ** May you share freely, never taking more than you give.
  14471. **
  14472. ******************************************************************************
  14473. **
  14474. ** This file contains OS interface code that is common to all
  14475. ** architectures.
  14476. */
  14477. #define _SQLITE_OS_C_ 1
  14478. #undef _SQLITE_OS_C_
  14479. /*
  14480. ** The default SQLite sqlite3_vfs implementations do not allocate
  14481. ** memory (actually, os_unix.c allocates a small amount of memory
  14482. ** from within OsOpen()), but some third-party implementations may.
  14483. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14484. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14485. **
  14486. ** The following functions are instrumented for malloc() failure
  14487. ** testing:
  14488. **
  14489. ** sqlite3OsRead()
  14490. ** sqlite3OsWrite()
  14491. ** sqlite3OsSync()
  14492. ** sqlite3OsFileSize()
  14493. ** sqlite3OsLock()
  14494. ** sqlite3OsCheckReservedLock()
  14495. ** sqlite3OsFileControl()
  14496. ** sqlite3OsShmMap()
  14497. ** sqlite3OsOpen()
  14498. ** sqlite3OsDelete()
  14499. ** sqlite3OsAccess()
  14500. ** sqlite3OsFullPathname()
  14501. **
  14502. */
  14503. #if defined(SQLITE_TEST)
  14504. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14505. #define DO_OS_MALLOC_TEST(x) \
  14506. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14507. void *pTstAlloc = sqlite3Malloc(10); \
  14508. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14509. sqlite3_free(pTstAlloc); \
  14510. }
  14511. #else
  14512. #define DO_OS_MALLOC_TEST(x)
  14513. #endif
  14514. /*
  14515. ** The following routines are convenience wrappers around methods
  14516. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14517. ** of this would be completely automatic if SQLite were coded using
  14518. ** C++ instead of plain old C.
  14519. */
  14520. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14521. int rc = SQLITE_OK;
  14522. if( pId->pMethods ){
  14523. rc = pId->pMethods->xClose(pId);
  14524. pId->pMethods = 0;
  14525. }
  14526. return rc;
  14527. }
  14528. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14529. DO_OS_MALLOC_TEST(id);
  14530. return id->pMethods->xRead(id, pBuf, amt, offset);
  14531. }
  14532. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14533. DO_OS_MALLOC_TEST(id);
  14534. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14535. }
  14536. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14537. return id->pMethods->xTruncate(id, size);
  14538. }
  14539. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14540. DO_OS_MALLOC_TEST(id);
  14541. return id->pMethods->xSync(id, flags);
  14542. }
  14543. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14544. DO_OS_MALLOC_TEST(id);
  14545. return id->pMethods->xFileSize(id, pSize);
  14546. }
  14547. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14548. DO_OS_MALLOC_TEST(id);
  14549. return id->pMethods->xLock(id, lockType);
  14550. }
  14551. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14552. return id->pMethods->xUnlock(id, lockType);
  14553. }
  14554. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14555. DO_OS_MALLOC_TEST(id);
  14556. return id->pMethods->xCheckReservedLock(id, pResOut);
  14557. }
  14558. /*
  14559. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14560. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14561. ** when simply tossing information over the wall to the VFS and we do not
  14562. ** really care if the VFS receives and understands the information since it
  14563. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14564. ** routine has no return value since the return value would be meaningless.
  14565. */
  14566. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14567. DO_OS_MALLOC_TEST(id);
  14568. return id->pMethods->xFileControl(id, op, pArg);
  14569. }
  14570. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14571. (void)id->pMethods->xFileControl(id, op, pArg);
  14572. }
  14573. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14574. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14575. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14576. }
  14577. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14578. return id->pMethods->xDeviceCharacteristics(id);
  14579. }
  14580. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14581. return id->pMethods->xShmLock(id, offset, n, flags);
  14582. }
  14583. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14584. id->pMethods->xShmBarrier(id);
  14585. }
  14586. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14587. return id->pMethods->xShmUnmap(id, deleteFlag);
  14588. }
  14589. SQLITE_PRIVATE int sqlite3OsShmMap(
  14590. sqlite3_file *id, /* Database file handle */
  14591. int iPage,
  14592. int pgsz,
  14593. int bExtend, /* True to extend file if necessary */
  14594. void volatile **pp /* OUT: Pointer to mapping */
  14595. ){
  14596. DO_OS_MALLOC_TEST(id);
  14597. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14598. }
  14599. #if SQLITE_MAX_MMAP_SIZE>0
  14600. /* The real implementation of xFetch and xUnfetch */
  14601. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14602. DO_OS_MALLOC_TEST(id);
  14603. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  14604. }
  14605. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14606. return id->pMethods->xUnfetch(id, iOff, p);
  14607. }
  14608. #else
  14609. /* No-op stubs to use when memory-mapped I/O is disabled */
  14610. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14611. *pp = 0;
  14612. return SQLITE_OK;
  14613. }
  14614. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14615. return SQLITE_OK;
  14616. }
  14617. #endif
  14618. /*
  14619. ** The next group of routines are convenience wrappers around the
  14620. ** VFS methods.
  14621. */
  14622. SQLITE_PRIVATE int sqlite3OsOpen(
  14623. sqlite3_vfs *pVfs,
  14624. const char *zPath,
  14625. sqlite3_file *pFile,
  14626. int flags,
  14627. int *pFlagsOut
  14628. ){
  14629. int rc;
  14630. DO_OS_MALLOC_TEST(0);
  14631. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14632. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14633. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14634. ** reaching the VFS. */
  14635. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14636. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14637. return rc;
  14638. }
  14639. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14640. DO_OS_MALLOC_TEST(0);
  14641. assert( dirSync==0 || dirSync==1 );
  14642. return pVfs->xDelete(pVfs, zPath, dirSync);
  14643. }
  14644. SQLITE_PRIVATE int sqlite3OsAccess(
  14645. sqlite3_vfs *pVfs,
  14646. const char *zPath,
  14647. int flags,
  14648. int *pResOut
  14649. ){
  14650. DO_OS_MALLOC_TEST(0);
  14651. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14652. }
  14653. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14654. sqlite3_vfs *pVfs,
  14655. const char *zPath,
  14656. int nPathOut,
  14657. char *zPathOut
  14658. ){
  14659. DO_OS_MALLOC_TEST(0);
  14660. zPathOut[0] = 0;
  14661. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14662. }
  14663. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14664. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14665. return pVfs->xDlOpen(pVfs, zPath);
  14666. }
  14667. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14668. pVfs->xDlError(pVfs, nByte, zBufOut);
  14669. }
  14670. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14671. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14672. }
  14673. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14674. pVfs->xDlClose(pVfs, pHandle);
  14675. }
  14676. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14677. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14678. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14679. }
  14680. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14681. return pVfs->xSleep(pVfs, nMicro);
  14682. }
  14683. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14684. int rc;
  14685. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14686. ** method to get the current date and time if that method is available
  14687. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14688. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14689. ** unavailable.
  14690. */
  14691. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14692. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14693. }else{
  14694. double r;
  14695. rc = pVfs->xCurrentTime(pVfs, &r);
  14696. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14697. }
  14698. return rc;
  14699. }
  14700. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14701. sqlite3_vfs *pVfs,
  14702. const char *zFile,
  14703. sqlite3_file **ppFile,
  14704. int flags,
  14705. int *pOutFlags
  14706. ){
  14707. int rc = SQLITE_NOMEM;
  14708. sqlite3_file *pFile;
  14709. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14710. if( pFile ){
  14711. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14712. if( rc!=SQLITE_OK ){
  14713. sqlite3_free(pFile);
  14714. }else{
  14715. *ppFile = pFile;
  14716. }
  14717. }
  14718. return rc;
  14719. }
  14720. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14721. int rc = SQLITE_OK;
  14722. assert( pFile );
  14723. rc = sqlite3OsClose(pFile);
  14724. sqlite3_free(pFile);
  14725. return rc;
  14726. }
  14727. /*
  14728. ** This function is a wrapper around the OS specific implementation of
  14729. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14730. ** ability to simulate a malloc failure, so that the handling of an
  14731. ** error in sqlite3_os_init() by the upper layers can be tested.
  14732. */
  14733. SQLITE_PRIVATE int sqlite3OsInit(void){
  14734. void *p = sqlite3_malloc(10);
  14735. if( p==0 ) return SQLITE_NOMEM;
  14736. sqlite3_free(p);
  14737. return sqlite3_os_init();
  14738. }
  14739. /*
  14740. ** The list of all registered VFS implementations.
  14741. */
  14742. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14743. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14744. /*
  14745. ** Locate a VFS by name. If no name is given, simply return the
  14746. ** first VFS on the list.
  14747. */
  14748. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14749. sqlite3_vfs *pVfs = 0;
  14750. #if SQLITE_THREADSAFE
  14751. sqlite3_mutex *mutex;
  14752. #endif
  14753. #ifndef SQLITE_OMIT_AUTOINIT
  14754. int rc = sqlite3_initialize();
  14755. if( rc ) return 0;
  14756. #endif
  14757. #if SQLITE_THREADSAFE
  14758. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14759. #endif
  14760. sqlite3_mutex_enter(mutex);
  14761. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14762. if( zVfs==0 ) break;
  14763. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14764. }
  14765. sqlite3_mutex_leave(mutex);
  14766. return pVfs;
  14767. }
  14768. /*
  14769. ** Unlink a VFS from the linked list
  14770. */
  14771. static void vfsUnlink(sqlite3_vfs *pVfs){
  14772. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14773. if( pVfs==0 ){
  14774. /* No-op */
  14775. }else if( vfsList==pVfs ){
  14776. vfsList = pVfs->pNext;
  14777. }else if( vfsList ){
  14778. sqlite3_vfs *p = vfsList;
  14779. while( p->pNext && p->pNext!=pVfs ){
  14780. p = p->pNext;
  14781. }
  14782. if( p->pNext==pVfs ){
  14783. p->pNext = pVfs->pNext;
  14784. }
  14785. }
  14786. }
  14787. /*
  14788. ** Register a VFS with the system. It is harmless to register the same
  14789. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14790. ** true.
  14791. */
  14792. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14793. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14794. #ifndef SQLITE_OMIT_AUTOINIT
  14795. int rc = sqlite3_initialize();
  14796. if( rc ) return rc;
  14797. #endif
  14798. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14799. sqlite3_mutex_enter(mutex);
  14800. vfsUnlink(pVfs);
  14801. if( makeDflt || vfsList==0 ){
  14802. pVfs->pNext = vfsList;
  14803. vfsList = pVfs;
  14804. }else{
  14805. pVfs->pNext = vfsList->pNext;
  14806. vfsList->pNext = pVfs;
  14807. }
  14808. assert(vfsList);
  14809. sqlite3_mutex_leave(mutex);
  14810. return SQLITE_OK;
  14811. }
  14812. /*
  14813. ** Unregister a VFS so that it is no longer accessible.
  14814. */
  14815. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14816. #if SQLITE_THREADSAFE
  14817. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14818. #endif
  14819. sqlite3_mutex_enter(mutex);
  14820. vfsUnlink(pVfs);
  14821. sqlite3_mutex_leave(mutex);
  14822. return SQLITE_OK;
  14823. }
  14824. /************** End of os.c **************************************************/
  14825. /************** Begin file fault.c *******************************************/
  14826. /*
  14827. ** 2008 Jan 22
  14828. **
  14829. ** The author disclaims copyright to this source code. In place of
  14830. ** a legal notice, here is a blessing:
  14831. **
  14832. ** May you do good and not evil.
  14833. ** May you find forgiveness for yourself and forgive others.
  14834. ** May you share freely, never taking more than you give.
  14835. **
  14836. *************************************************************************
  14837. **
  14838. ** This file contains code to support the concept of "benign"
  14839. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14840. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14841. ** and returns 0).
  14842. **
  14843. ** Most malloc failures are non-benign. After they occur, SQLite
  14844. ** abandons the current operation and returns an error code (usually
  14845. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14846. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14847. ** is completely recoverable simply by not carrying out the resize. The
  14848. ** hash table will continue to function normally. So a malloc failure
  14849. ** during a hash table resize is a benign fault.
  14850. */
  14851. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14852. /*
  14853. ** Global variables.
  14854. */
  14855. typedef struct BenignMallocHooks BenignMallocHooks;
  14856. static SQLITE_WSD struct BenignMallocHooks {
  14857. void (*xBenignBegin)(void);
  14858. void (*xBenignEnd)(void);
  14859. } sqlite3Hooks = { 0, 0 };
  14860. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14861. ** structure. If writable static data is unsupported on the target,
  14862. ** we have to locate the state vector at run-time. In the more common
  14863. ** case where writable static data is supported, wsdHooks can refer directly
  14864. ** to the "sqlite3Hooks" state vector declared above.
  14865. */
  14866. #ifdef SQLITE_OMIT_WSD
  14867. # define wsdHooksInit \
  14868. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14869. # define wsdHooks x[0]
  14870. #else
  14871. # define wsdHooksInit
  14872. # define wsdHooks sqlite3Hooks
  14873. #endif
  14874. /*
  14875. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14876. ** sqlite3EndBenignMalloc() are called, respectively.
  14877. */
  14878. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14879. void (*xBenignBegin)(void),
  14880. void (*xBenignEnd)(void)
  14881. ){
  14882. wsdHooksInit;
  14883. wsdHooks.xBenignBegin = xBenignBegin;
  14884. wsdHooks.xBenignEnd = xBenignEnd;
  14885. }
  14886. /*
  14887. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14888. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14889. ** indicates that subsequent malloc failures are non-benign.
  14890. */
  14891. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14892. wsdHooksInit;
  14893. if( wsdHooks.xBenignBegin ){
  14894. wsdHooks.xBenignBegin();
  14895. }
  14896. }
  14897. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14898. wsdHooksInit;
  14899. if( wsdHooks.xBenignEnd ){
  14900. wsdHooks.xBenignEnd();
  14901. }
  14902. }
  14903. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14904. /************** End of fault.c ***********************************************/
  14905. /************** Begin file mem0.c ********************************************/
  14906. /*
  14907. ** 2008 October 28
  14908. **
  14909. ** The author disclaims copyright to this source code. In place of
  14910. ** a legal notice, here is a blessing:
  14911. **
  14912. ** May you do good and not evil.
  14913. ** May you find forgiveness for yourself and forgive others.
  14914. ** May you share freely, never taking more than you give.
  14915. **
  14916. *************************************************************************
  14917. **
  14918. ** This file contains a no-op memory allocation drivers for use when
  14919. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14920. ** here always fail. SQLite will not operate with these drivers. These
  14921. ** are merely placeholders. Real drivers must be substituted using
  14922. ** sqlite3_config() before SQLite will operate.
  14923. */
  14924. /*
  14925. ** This version of the memory allocator is the default. It is
  14926. ** used when no other memory allocator is specified using compile-time
  14927. ** macros.
  14928. */
  14929. #ifdef SQLITE_ZERO_MALLOC
  14930. /*
  14931. ** No-op versions of all memory allocation routines
  14932. */
  14933. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14934. static void sqlite3MemFree(void *pPrior){ return; }
  14935. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14936. static int sqlite3MemSize(void *pPrior){ return 0; }
  14937. static int sqlite3MemRoundup(int n){ return n; }
  14938. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14939. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14940. /*
  14941. ** This routine is the only routine in this file with external linkage.
  14942. **
  14943. ** Populate the low-level memory allocation function pointers in
  14944. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14945. */
  14946. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14947. static const sqlite3_mem_methods defaultMethods = {
  14948. sqlite3MemMalloc,
  14949. sqlite3MemFree,
  14950. sqlite3MemRealloc,
  14951. sqlite3MemSize,
  14952. sqlite3MemRoundup,
  14953. sqlite3MemInit,
  14954. sqlite3MemShutdown,
  14955. 0
  14956. };
  14957. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14958. }
  14959. #endif /* SQLITE_ZERO_MALLOC */
  14960. /************** End of mem0.c ************************************************/
  14961. /************** Begin file mem1.c ********************************************/
  14962. /*
  14963. ** 2007 August 14
  14964. **
  14965. ** The author disclaims copyright to this source code. In place of
  14966. ** a legal notice, here is a blessing:
  14967. **
  14968. ** May you do good and not evil.
  14969. ** May you find forgiveness for yourself and forgive others.
  14970. ** May you share freely, never taking more than you give.
  14971. **
  14972. *************************************************************************
  14973. **
  14974. ** This file contains low-level memory allocation drivers for when
  14975. ** SQLite will use the standard C-library malloc/realloc/free interface
  14976. ** to obtain the memory it needs.
  14977. **
  14978. ** This file contains implementations of the low-level memory allocation
  14979. ** routines specified in the sqlite3_mem_methods object. The content of
  14980. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  14981. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  14982. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  14983. ** default configuration is to use memory allocation routines in this
  14984. ** file.
  14985. **
  14986. ** C-preprocessor macro summary:
  14987. **
  14988. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  14989. ** the malloc_usable_size() interface exists
  14990. ** on the target platform. Or, this symbol
  14991. ** can be set manually, if desired.
  14992. ** If an equivalent interface exists by
  14993. ** a different name, using a separate -D
  14994. ** option to rename it.
  14995. **
  14996. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  14997. ** memory allocator. Set this symbol to enable
  14998. ** building on older macs.
  14999. **
  15000. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  15001. ** _msize() on windows systems. This might
  15002. ** be necessary when compiling for Delphi,
  15003. ** for example.
  15004. */
  15005. /*
  15006. ** This version of the memory allocator is the default. It is
  15007. ** used when no other memory allocator is specified using compile-time
  15008. ** macros.
  15009. */
  15010. #ifdef SQLITE_SYSTEM_MALLOC
  15011. /*
  15012. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  15013. ** The use of _msize() is automatic, but can be disabled by compiling
  15014. ** with -DSQLITE_WITHOUT_MSIZE
  15015. */
  15016. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15017. # define SQLITE_MALLOCSIZE _msize
  15018. #endif
  15019. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15020. /*
  15021. ** Use the zone allocator available on apple products unless the
  15022. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15023. */
  15024. #include <sys/sysctl.h>
  15025. #include <malloc/malloc.h>
  15026. #include <libkern/OSAtomic.h>
  15027. static malloc_zone_t* _sqliteZone_;
  15028. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15029. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15030. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15031. #define SQLITE_MALLOCSIZE(x) \
  15032. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15033. #elif defined(SQLITE_OS_RTT)
  15034. #include <rtthread.h>
  15035. /*
  15036. ** Use standard C library malloc and free on non-Apple systems.
  15037. ** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15038. */
  15039. #define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x)
  15040. #define SQLITE_FREE(x) rt_free(x)
  15041. #define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y))
  15042. #if (!defined(SQLITE_WITHOUT_MSIZE)) \
  15043. && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15044. # error "not have malloc_usable_size()"
  15045. #endif
  15046. #ifdef HAVE_MALLOC_USABLE_SIZE
  15047. # undef SQLITE_MALLOCSIZE
  15048. #endif
  15049. #else /* if not __APPLE__ */
  15050. /*
  15051. ** Use standard C library malloc and free on non-Apple systems.
  15052. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15053. */
  15054. #define SQLITE_MALLOC(x) malloc(x)
  15055. #define SQLITE_FREE(x) free(x)
  15056. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15057. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  15058. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15059. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  15060. #endif
  15061. #ifdef HAVE_MALLOC_USABLE_SIZE
  15062. # ifndef SQLITE_MALLOCSIZE
  15063. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15064. # endif
  15065. #else
  15066. # undef SQLITE_MALLOCSIZE
  15067. #endif
  15068. #endif /* __APPLE__ or not __APPLE__ */
  15069. /*
  15070. ** Like malloc(), but remember the size of the allocation
  15071. ** so that we can find it later using sqlite3MemSize().
  15072. **
  15073. ** For this low-level routine, we are guaranteed that nByte>0 because
  15074. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15075. ** routines.
  15076. */
  15077. static void *sqlite3MemMalloc(int nByte){
  15078. #ifdef SQLITE_MALLOCSIZE
  15079. void *p = SQLITE_MALLOC( nByte );
  15080. if( p==0 ){
  15081. testcase( sqlite3GlobalConfig.xLog!=0 );
  15082. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15083. }
  15084. return p;
  15085. #else
  15086. sqlite3_int64 *p;
  15087. assert( nByte>0 );
  15088. nByte = ROUND8(nByte);
  15089. p = SQLITE_MALLOC( nByte+8 );
  15090. if( p ){
  15091. p[0] = nByte;
  15092. p++;
  15093. }else{
  15094. testcase( sqlite3GlobalConfig.xLog!=0 );
  15095. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15096. }
  15097. return (void *)p;
  15098. #endif
  15099. }
  15100. /*
  15101. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15102. ** or sqlite3MemRealloc().
  15103. **
  15104. ** For this low-level routine, we already know that pPrior!=0 since
  15105. ** cases where pPrior==0 will have been intecepted and dealt with
  15106. ** by higher-level routines.
  15107. */
  15108. static void sqlite3MemFree(void *pPrior){
  15109. #ifdef SQLITE_MALLOCSIZE
  15110. SQLITE_FREE(pPrior);
  15111. #else
  15112. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15113. assert( pPrior!=0 );
  15114. p--;
  15115. SQLITE_FREE(p);
  15116. #endif
  15117. }
  15118. /*
  15119. ** Report the allocated size of a prior return from xMalloc()
  15120. ** or xRealloc().
  15121. */
  15122. static int sqlite3MemSize(void *pPrior){
  15123. #ifdef SQLITE_MALLOCSIZE
  15124. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15125. #else
  15126. sqlite3_int64 *p;
  15127. if( pPrior==0 ) return 0;
  15128. p = (sqlite3_int64*)pPrior;
  15129. p--;
  15130. return (int)p[0];
  15131. #endif
  15132. }
  15133. /*
  15134. ** Like realloc(). Resize an allocation previously obtained from
  15135. ** sqlite3MemMalloc().
  15136. **
  15137. ** For this low-level interface, we know that pPrior!=0. Cases where
  15138. ** pPrior==0 while have been intercepted by higher-level routine and
  15139. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  15140. ** cases where nByte<=0 will have been intercepted by higher-level
  15141. ** routines and redirected to xFree.
  15142. */
  15143. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15144. #ifdef SQLITE_MALLOCSIZE
  15145. void *p = SQLITE_REALLOC(pPrior, nByte);
  15146. if( p==0 ){
  15147. testcase( sqlite3GlobalConfig.xLog!=0 );
  15148. sqlite3_log(SQLITE_NOMEM,
  15149. "failed memory resize %u to %u bytes",
  15150. SQLITE_MALLOCSIZE(pPrior), nByte);
  15151. }
  15152. return p;
  15153. #else
  15154. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15155. assert( pPrior!=0 && nByte>0 );
  15156. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15157. p--;
  15158. p = SQLITE_REALLOC(p, nByte+8 );
  15159. if( p ){
  15160. p[0] = nByte;
  15161. p++;
  15162. }else{
  15163. testcase( sqlite3GlobalConfig.xLog!=0 );
  15164. sqlite3_log(SQLITE_NOMEM,
  15165. "failed memory resize %u to %u bytes",
  15166. sqlite3MemSize(pPrior), nByte);
  15167. }
  15168. return (void*)p;
  15169. #endif
  15170. }
  15171. /*
  15172. ** Round up a request size to the next valid allocation size.
  15173. */
  15174. static int sqlite3MemRoundup(int n){
  15175. return ROUND8(n);
  15176. }
  15177. /*
  15178. ** Initialize this module.
  15179. */
  15180. static int sqlite3MemInit(void *NotUsed){
  15181. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15182. int cpuCount;
  15183. size_t len;
  15184. if( _sqliteZone_ ){
  15185. return SQLITE_OK;
  15186. }
  15187. len = sizeof(cpuCount);
  15188. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15189. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15190. if( cpuCount>1 ){
  15191. /* defer MT decisions to system malloc */
  15192. _sqliteZone_ = malloc_default_zone();
  15193. }else{
  15194. /* only 1 core, use our own zone to contention over global locks,
  15195. ** e.g. we have our own dedicated locks */
  15196. bool success;
  15197. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15198. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15199. do{
  15200. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15201. (void * volatile *)&_sqliteZone_);
  15202. }while(!_sqliteZone_);
  15203. if( !success ){
  15204. /* somebody registered a zone first */
  15205. malloc_destroy_zone(newzone);
  15206. }
  15207. }
  15208. #endif
  15209. UNUSED_PARAMETER(NotUsed);
  15210. return SQLITE_OK;
  15211. }
  15212. /*
  15213. ** Deinitialize this module.
  15214. */
  15215. static void sqlite3MemShutdown(void *NotUsed){
  15216. UNUSED_PARAMETER(NotUsed);
  15217. return;
  15218. }
  15219. /*
  15220. ** This routine is the only routine in this file with external linkage.
  15221. **
  15222. ** Populate the low-level memory allocation function pointers in
  15223. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15224. */
  15225. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15226. static const sqlite3_mem_methods defaultMethods = {
  15227. sqlite3MemMalloc,
  15228. sqlite3MemFree,
  15229. sqlite3MemRealloc,
  15230. sqlite3MemSize,
  15231. sqlite3MemRoundup,
  15232. sqlite3MemInit,
  15233. sqlite3MemShutdown,
  15234. 0
  15235. };
  15236. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15237. }
  15238. #endif /* SQLITE_SYSTEM_MALLOC */
  15239. /************** End of mem1.c ************************************************/
  15240. /************** Begin file mem2.c ********************************************/
  15241. /*
  15242. ** 2007 August 15
  15243. **
  15244. ** The author disclaims copyright to this source code. In place of
  15245. ** a legal notice, here is a blessing:
  15246. **
  15247. ** May you do good and not evil.
  15248. ** May you find forgiveness for yourself and forgive others.
  15249. ** May you share freely, never taking more than you give.
  15250. **
  15251. *************************************************************************
  15252. **
  15253. ** This file contains low-level memory allocation drivers for when
  15254. ** SQLite will use the standard C-library malloc/realloc/free interface
  15255. ** to obtain the memory it needs while adding lots of additional debugging
  15256. ** information to each allocation in order to help detect and fix memory
  15257. ** leaks and memory usage errors.
  15258. **
  15259. ** This file contains implementations of the low-level memory allocation
  15260. ** routines specified in the sqlite3_mem_methods object.
  15261. */
  15262. /*
  15263. ** This version of the memory allocator is used only if the
  15264. ** SQLITE_MEMDEBUG macro is defined
  15265. */
  15266. #ifdef SQLITE_MEMDEBUG
  15267. /*
  15268. ** The backtrace functionality is only available with GLIBC
  15269. */
  15270. #ifdef __GLIBC__
  15271. extern int backtrace(void**,int);
  15272. extern void backtrace_symbols_fd(void*const*,int,int);
  15273. #else
  15274. # define backtrace(A,B) 1
  15275. # define backtrace_symbols_fd(A,B,C)
  15276. #endif
  15277. /* #include <stdio.h> */
  15278. /*
  15279. ** Each memory allocation looks like this:
  15280. **
  15281. ** ------------------------------------------------------------------------
  15282. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15283. ** ------------------------------------------------------------------------
  15284. **
  15285. ** The application code sees only a pointer to the allocation. We have
  15286. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15287. ** MemBlockHdr tells us the size of the allocation and the number of
  15288. ** backtrace pointers. There is also a guard word at the end of the
  15289. ** MemBlockHdr.
  15290. */
  15291. struct MemBlockHdr {
  15292. i64 iSize; /* Size of this allocation */
  15293. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15294. char nBacktrace; /* Number of backtraces on this alloc */
  15295. char nBacktraceSlots; /* Available backtrace slots */
  15296. u8 nTitle; /* Bytes of title; includes '\0' */
  15297. u8 eType; /* Allocation type code */
  15298. int iForeGuard; /* Guard word for sanity */
  15299. };
  15300. /*
  15301. ** Guard words
  15302. */
  15303. #define FOREGUARD 0x80F5E153
  15304. #define REARGUARD 0xE4676B53
  15305. /*
  15306. ** Number of malloc size increments to track.
  15307. */
  15308. #define NCSIZE 1000
  15309. /*
  15310. ** All of the static variables used by this module are collected
  15311. ** into a single structure named "mem". This is to keep the
  15312. ** static variables organized and to reduce namespace pollution
  15313. ** when this module is combined with other in the amalgamation.
  15314. */
  15315. static struct {
  15316. /*
  15317. ** Mutex to control access to the memory allocation subsystem.
  15318. */
  15319. sqlite3_mutex *mutex;
  15320. /*
  15321. ** Head and tail of a linked list of all outstanding allocations
  15322. */
  15323. struct MemBlockHdr *pFirst;
  15324. struct MemBlockHdr *pLast;
  15325. /*
  15326. ** The number of levels of backtrace to save in new allocations.
  15327. */
  15328. int nBacktrace;
  15329. void (*xBacktrace)(int, int, void **);
  15330. /*
  15331. ** Title text to insert in front of each block
  15332. */
  15333. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15334. char zTitle[100]; /* The title text */
  15335. /*
  15336. ** sqlite3MallocDisallow() increments the following counter.
  15337. ** sqlite3MallocAllow() decrements it.
  15338. */
  15339. int disallow; /* Do not allow memory allocation */
  15340. /*
  15341. ** Gather statistics on the sizes of memory allocations.
  15342. ** nAlloc[i] is the number of allocation attempts of i*8
  15343. ** bytes. i==NCSIZE is the number of allocation attempts for
  15344. ** sizes more than NCSIZE*8 bytes.
  15345. */
  15346. int nAlloc[NCSIZE]; /* Total number of allocations */
  15347. int nCurrent[NCSIZE]; /* Current number of allocations */
  15348. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15349. } mem;
  15350. /*
  15351. ** Adjust memory usage statistics
  15352. */
  15353. static void adjustStats(int iSize, int increment){
  15354. int i = ROUND8(iSize)/8;
  15355. if( i>NCSIZE-1 ){
  15356. i = NCSIZE - 1;
  15357. }
  15358. if( increment>0 ){
  15359. mem.nAlloc[i]++;
  15360. mem.nCurrent[i]++;
  15361. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15362. mem.mxCurrent[i] = mem.nCurrent[i];
  15363. }
  15364. }else{
  15365. mem.nCurrent[i]--;
  15366. assert( mem.nCurrent[i]>=0 );
  15367. }
  15368. }
  15369. /*
  15370. ** Given an allocation, find the MemBlockHdr for that allocation.
  15371. **
  15372. ** This routine checks the guards at either end of the allocation and
  15373. ** if they are incorrect it asserts.
  15374. */
  15375. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15376. struct MemBlockHdr *p;
  15377. int *pInt;
  15378. u8 *pU8;
  15379. int nReserve;
  15380. p = (struct MemBlockHdr*)pAllocation;
  15381. p--;
  15382. assert( p->iForeGuard==(int)FOREGUARD );
  15383. nReserve = ROUND8(p->iSize);
  15384. pInt = (int*)pAllocation;
  15385. pU8 = (u8*)pAllocation;
  15386. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15387. /* This checks any of the "extra" bytes allocated due
  15388. ** to rounding up to an 8 byte boundary to ensure
  15389. ** they haven't been overwritten.
  15390. */
  15391. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15392. return p;
  15393. }
  15394. /*
  15395. ** Return the number of bytes currently allocated at address p.
  15396. */
  15397. static int sqlite3MemSize(void *p){
  15398. struct MemBlockHdr *pHdr;
  15399. if( !p ){
  15400. return 0;
  15401. }
  15402. pHdr = sqlite3MemsysGetHeader(p);
  15403. return (int)pHdr->iSize;
  15404. }
  15405. /*
  15406. ** Initialize the memory allocation subsystem.
  15407. */
  15408. static int sqlite3MemInit(void *NotUsed){
  15409. UNUSED_PARAMETER(NotUsed);
  15410. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15411. if( !sqlite3GlobalConfig.bMemstat ){
  15412. /* If memory status is enabled, then the malloc.c wrapper will already
  15413. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15414. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15415. }
  15416. return SQLITE_OK;
  15417. }
  15418. /*
  15419. ** Deinitialize the memory allocation subsystem.
  15420. */
  15421. static void sqlite3MemShutdown(void *NotUsed){
  15422. UNUSED_PARAMETER(NotUsed);
  15423. mem.mutex = 0;
  15424. }
  15425. /*
  15426. ** Round up a request size to the next valid allocation size.
  15427. */
  15428. static int sqlite3MemRoundup(int n){
  15429. return ROUND8(n);
  15430. }
  15431. /*
  15432. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15433. ** the content of a new memory allocation to unpredictable values and
  15434. ** to clear the content of a freed allocation to unpredictable values.
  15435. */
  15436. static void randomFill(char *pBuf, int nByte){
  15437. unsigned int x, y, r;
  15438. x = SQLITE_PTR_TO_INT(pBuf);
  15439. y = nByte | 1;
  15440. while( nByte >= 4 ){
  15441. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15442. y = y*1103515245 + 12345;
  15443. r = x ^ y;
  15444. *(int*)pBuf = r;
  15445. pBuf += 4;
  15446. nByte -= 4;
  15447. }
  15448. while( nByte-- > 0 ){
  15449. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15450. y = y*1103515245 + 12345;
  15451. r = x ^ y;
  15452. *(pBuf++) = r & 0xff;
  15453. }
  15454. }
  15455. /*
  15456. ** Allocate nByte bytes of memory.
  15457. */
  15458. static void *sqlite3MemMalloc(int nByte){
  15459. struct MemBlockHdr *pHdr;
  15460. void **pBt;
  15461. char *z;
  15462. int *pInt;
  15463. void *p = 0;
  15464. int totalSize;
  15465. int nReserve;
  15466. sqlite3_mutex_enter(mem.mutex);
  15467. assert( mem.disallow==0 );
  15468. nReserve = ROUND8(nByte);
  15469. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15470. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15471. p = malloc(totalSize);
  15472. if( p ){
  15473. z = p;
  15474. pBt = (void**)&z[mem.nTitle];
  15475. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15476. pHdr->pNext = 0;
  15477. pHdr->pPrev = mem.pLast;
  15478. if( mem.pLast ){
  15479. mem.pLast->pNext = pHdr;
  15480. }else{
  15481. mem.pFirst = pHdr;
  15482. }
  15483. mem.pLast = pHdr;
  15484. pHdr->iForeGuard = FOREGUARD;
  15485. pHdr->eType = MEMTYPE_HEAP;
  15486. pHdr->nBacktraceSlots = mem.nBacktrace;
  15487. pHdr->nTitle = mem.nTitle;
  15488. if( mem.nBacktrace ){
  15489. void *aAddr[40];
  15490. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15491. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15492. assert(pBt[0]);
  15493. if( mem.xBacktrace ){
  15494. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15495. }
  15496. }else{
  15497. pHdr->nBacktrace = 0;
  15498. }
  15499. if( mem.nTitle ){
  15500. memcpy(z, mem.zTitle, mem.nTitle);
  15501. }
  15502. pHdr->iSize = nByte;
  15503. adjustStats(nByte, +1);
  15504. pInt = (int*)&pHdr[1];
  15505. pInt[nReserve/sizeof(int)] = REARGUARD;
  15506. randomFill((char*)pInt, nByte);
  15507. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15508. p = (void*)pInt;
  15509. }
  15510. sqlite3_mutex_leave(mem.mutex);
  15511. return p;
  15512. }
  15513. /*
  15514. ** Free memory.
  15515. */
  15516. static void sqlite3MemFree(void *pPrior){
  15517. struct MemBlockHdr *pHdr;
  15518. void **pBt;
  15519. char *z;
  15520. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15521. || mem.mutex!=0 );
  15522. pHdr = sqlite3MemsysGetHeader(pPrior);
  15523. pBt = (void**)pHdr;
  15524. pBt -= pHdr->nBacktraceSlots;
  15525. sqlite3_mutex_enter(mem.mutex);
  15526. if( pHdr->pPrev ){
  15527. assert( pHdr->pPrev->pNext==pHdr );
  15528. pHdr->pPrev->pNext = pHdr->pNext;
  15529. }else{
  15530. assert( mem.pFirst==pHdr );
  15531. mem.pFirst = pHdr->pNext;
  15532. }
  15533. if( pHdr->pNext ){
  15534. assert( pHdr->pNext->pPrev==pHdr );
  15535. pHdr->pNext->pPrev = pHdr->pPrev;
  15536. }else{
  15537. assert( mem.pLast==pHdr );
  15538. mem.pLast = pHdr->pPrev;
  15539. }
  15540. z = (char*)pBt;
  15541. z -= pHdr->nTitle;
  15542. adjustStats((int)pHdr->iSize, -1);
  15543. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15544. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15545. free(z);
  15546. sqlite3_mutex_leave(mem.mutex);
  15547. }
  15548. /*
  15549. ** Change the size of an existing memory allocation.
  15550. **
  15551. ** For this debugging implementation, we *always* make a copy of the
  15552. ** allocation into a new place in memory. In this way, if the
  15553. ** higher level code is using pointer to the old allocation, it is
  15554. ** much more likely to break and we are much more liking to find
  15555. ** the error.
  15556. */
  15557. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15558. struct MemBlockHdr *pOldHdr;
  15559. void *pNew;
  15560. assert( mem.disallow==0 );
  15561. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15562. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15563. pNew = sqlite3MemMalloc(nByte);
  15564. if( pNew ){
  15565. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  15566. if( nByte>pOldHdr->iSize ){
  15567. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  15568. }
  15569. sqlite3MemFree(pPrior);
  15570. }
  15571. return pNew;
  15572. }
  15573. /*
  15574. ** Populate the low-level memory allocation function pointers in
  15575. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15576. */
  15577. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15578. static const sqlite3_mem_methods defaultMethods = {
  15579. sqlite3MemMalloc,
  15580. sqlite3MemFree,
  15581. sqlite3MemRealloc,
  15582. sqlite3MemSize,
  15583. sqlite3MemRoundup,
  15584. sqlite3MemInit,
  15585. sqlite3MemShutdown,
  15586. 0
  15587. };
  15588. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15589. }
  15590. /*
  15591. ** Set the "type" of an allocation.
  15592. */
  15593. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15594. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15595. struct MemBlockHdr *pHdr;
  15596. pHdr = sqlite3MemsysGetHeader(p);
  15597. assert( pHdr->iForeGuard==FOREGUARD );
  15598. pHdr->eType = eType;
  15599. }
  15600. }
  15601. /*
  15602. ** Return TRUE if the mask of type in eType matches the type of the
  15603. ** allocation p. Also return true if p==NULL.
  15604. **
  15605. ** This routine is designed for use within an assert() statement, to
  15606. ** verify the type of an allocation. For example:
  15607. **
  15608. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15609. */
  15610. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15611. int rc = 1;
  15612. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15613. struct MemBlockHdr *pHdr;
  15614. pHdr = sqlite3MemsysGetHeader(p);
  15615. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15616. if( (pHdr->eType&eType)==0 ){
  15617. rc = 0;
  15618. }
  15619. }
  15620. return rc;
  15621. }
  15622. /*
  15623. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15624. ** allocation p. Also return true if p==NULL.
  15625. **
  15626. ** This routine is designed for use within an assert() statement, to
  15627. ** verify the type of an allocation. For example:
  15628. **
  15629. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15630. */
  15631. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15632. int rc = 1;
  15633. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15634. struct MemBlockHdr *pHdr;
  15635. pHdr = sqlite3MemsysGetHeader(p);
  15636. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15637. if( (pHdr->eType&eType)!=0 ){
  15638. rc = 0;
  15639. }
  15640. }
  15641. return rc;
  15642. }
  15643. /*
  15644. ** Set the number of backtrace levels kept for each allocation.
  15645. ** A value of zero turns off backtracing. The number is always rounded
  15646. ** up to a multiple of 2.
  15647. */
  15648. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15649. if( depth<0 ){ depth = 0; }
  15650. if( depth>20 ){ depth = 20; }
  15651. depth = (depth+1)&0xfe;
  15652. mem.nBacktrace = depth;
  15653. }
  15654. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15655. mem.xBacktrace = xBacktrace;
  15656. }
  15657. /*
  15658. ** Set the title string for subsequent allocations.
  15659. */
  15660. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15661. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15662. sqlite3_mutex_enter(mem.mutex);
  15663. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15664. memcpy(mem.zTitle, zTitle, n);
  15665. mem.zTitle[n] = 0;
  15666. mem.nTitle = ROUND8(n);
  15667. sqlite3_mutex_leave(mem.mutex);
  15668. }
  15669. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15670. struct MemBlockHdr *pHdr;
  15671. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15672. void **pBt = (void**)pHdr;
  15673. pBt -= pHdr->nBacktraceSlots;
  15674. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15675. }
  15676. }
  15677. /*
  15678. ** Open the file indicated and write a log of all unfreed memory
  15679. ** allocations into that log.
  15680. */
  15681. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15682. FILE *out;
  15683. struct MemBlockHdr *pHdr;
  15684. void **pBt;
  15685. int i;
  15686. out = fopen(zFilename, "w");
  15687. if( out==0 ){
  15688. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15689. zFilename);
  15690. return;
  15691. }
  15692. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15693. char *z = (char*)pHdr;
  15694. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15695. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15696. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15697. if( pHdr->nBacktrace ){
  15698. fflush(out);
  15699. pBt = (void**)pHdr;
  15700. pBt -= pHdr->nBacktraceSlots;
  15701. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15702. fprintf(out, "\n");
  15703. }
  15704. }
  15705. fprintf(out, "COUNTS:\n");
  15706. for(i=0; i<NCSIZE-1; i++){
  15707. if( mem.nAlloc[i] ){
  15708. fprintf(out, " %5d: %10d %10d %10d\n",
  15709. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15710. }
  15711. }
  15712. if( mem.nAlloc[NCSIZE-1] ){
  15713. fprintf(out, " %5d: %10d %10d %10d\n",
  15714. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15715. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15716. }
  15717. fclose(out);
  15718. }
  15719. /*
  15720. ** Return the number of times sqlite3MemMalloc() has been called.
  15721. */
  15722. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15723. int i;
  15724. int nTotal = 0;
  15725. for(i=0; i<NCSIZE; i++){
  15726. nTotal += mem.nAlloc[i];
  15727. }
  15728. return nTotal;
  15729. }
  15730. #endif /* SQLITE_MEMDEBUG */
  15731. /************** End of mem2.c ************************************************/
  15732. /************** Begin file mem3.c ********************************************/
  15733. /*
  15734. ** 2007 October 14
  15735. **
  15736. ** The author disclaims copyright to this source code. In place of
  15737. ** a legal notice, here is a blessing:
  15738. **
  15739. ** May you do good and not evil.
  15740. ** May you find forgiveness for yourself and forgive others.
  15741. ** May you share freely, never taking more than you give.
  15742. **
  15743. *************************************************************************
  15744. ** This file contains the C functions that implement a memory
  15745. ** allocation subsystem for use by SQLite.
  15746. **
  15747. ** This version of the memory allocation subsystem omits all
  15748. ** use of malloc(). The SQLite user supplies a block of memory
  15749. ** before calling sqlite3_initialize() from which allocations
  15750. ** are made and returned by the xMalloc() and xRealloc()
  15751. ** implementations. Once sqlite3_initialize() has been called,
  15752. ** the amount of memory available to SQLite is fixed and cannot
  15753. ** be changed.
  15754. **
  15755. ** This version of the memory allocation subsystem is included
  15756. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15757. */
  15758. /*
  15759. ** This version of the memory allocator is only built into the library
  15760. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15761. ** mean that the library will use a memory-pool by default, just that
  15762. ** it is available. The mempool allocator is activated by calling
  15763. ** sqlite3_config().
  15764. */
  15765. #ifdef SQLITE_ENABLE_MEMSYS3
  15766. /*
  15767. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15768. */
  15769. #define MX_SMALL 10
  15770. /*
  15771. ** Number of freelist hash slots
  15772. */
  15773. #define N_HASH 61
  15774. /*
  15775. ** A memory allocation (also called a "chunk") consists of two or
  15776. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15777. ** a header that is not returned to the user.
  15778. **
  15779. ** A chunk is two or more blocks that is either checked out or
  15780. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15781. ** size of the allocation in blocks if the allocation is free.
  15782. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15783. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15784. ** is true if the previous chunk is checked out and false if the
  15785. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15786. ** the previous chunk in blocks if the previous chunk is on the
  15787. ** freelist. If the previous chunk is checked out, then
  15788. ** u.hdr.prevSize can be part of the data for that chunk and should
  15789. ** not be read or written.
  15790. **
  15791. ** We often identify a chunk by its index in mem3.aPool[]. When
  15792. ** this is done, the chunk index refers to the second block of
  15793. ** the chunk. In this way, the first chunk has an index of 1.
  15794. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15795. ** of a NULL pointer.
  15796. **
  15797. ** The second block of free chunks is of the form u.list. The
  15798. ** two fields form a double-linked list of chunks of related sizes.
  15799. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15800. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15801. **
  15802. ** The second block of a chunk is user data if the chunk is checked
  15803. ** out. If a chunk is checked out, the user data may extend into
  15804. ** the u.hdr.prevSize value of the following chunk.
  15805. */
  15806. typedef struct Mem3Block Mem3Block;
  15807. struct Mem3Block {
  15808. union {
  15809. struct {
  15810. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15811. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15812. } hdr;
  15813. struct {
  15814. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15815. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15816. } list;
  15817. } u;
  15818. };
  15819. /*
  15820. ** All of the static variables used by this module are collected
  15821. ** into a single structure named "mem3". This is to keep the
  15822. ** static variables organized and to reduce namespace pollution
  15823. ** when this module is combined with other in the amalgamation.
  15824. */
  15825. static SQLITE_WSD struct Mem3Global {
  15826. /*
  15827. ** Memory available for allocation. nPool is the size of the array
  15828. ** (in Mem3Blocks) pointed to by aPool less 2.
  15829. */
  15830. u32 nPool;
  15831. Mem3Block *aPool;
  15832. /*
  15833. ** True if we are evaluating an out-of-memory callback.
  15834. */
  15835. int alarmBusy;
  15836. /*
  15837. ** Mutex to control access to the memory allocation subsystem.
  15838. */
  15839. sqlite3_mutex *mutex;
  15840. /*
  15841. ** The minimum amount of free space that we have seen.
  15842. */
  15843. u32 mnMaster;
  15844. /*
  15845. ** iMaster is the index of the master chunk. Most new allocations
  15846. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15847. ** of the current master. iMaster is 0 if there is not master chunk.
  15848. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15849. */
  15850. u32 iMaster;
  15851. u32 szMaster;
  15852. /*
  15853. ** Array of lists of free blocks according to the block size
  15854. ** for smaller chunks, or a hash on the block size for larger
  15855. ** chunks.
  15856. */
  15857. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15858. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15859. } mem3 = { 97535575 };
  15860. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15861. /*
  15862. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15863. ** on. *pRoot is the list that i is a member of.
  15864. */
  15865. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15866. u32 next = mem3.aPool[i].u.list.next;
  15867. u32 prev = mem3.aPool[i].u.list.prev;
  15868. assert( sqlite3_mutex_held(mem3.mutex) );
  15869. if( prev==0 ){
  15870. *pRoot = next;
  15871. }else{
  15872. mem3.aPool[prev].u.list.next = next;
  15873. }
  15874. if( next ){
  15875. mem3.aPool[next].u.list.prev = prev;
  15876. }
  15877. mem3.aPool[i].u.list.next = 0;
  15878. mem3.aPool[i].u.list.prev = 0;
  15879. }
  15880. /*
  15881. ** Unlink the chunk at index i from
  15882. ** whatever list is currently a member of.
  15883. */
  15884. static void memsys3Unlink(u32 i){
  15885. u32 size, hash;
  15886. assert( sqlite3_mutex_held(mem3.mutex) );
  15887. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15888. assert( i>=1 );
  15889. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15890. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15891. assert( size>=2 );
  15892. if( size <= MX_SMALL ){
  15893. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15894. }else{
  15895. hash = size % N_HASH;
  15896. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15897. }
  15898. }
  15899. /*
  15900. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15901. ** at *pRoot.
  15902. */
  15903. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15904. assert( sqlite3_mutex_held(mem3.mutex) );
  15905. mem3.aPool[i].u.list.next = *pRoot;
  15906. mem3.aPool[i].u.list.prev = 0;
  15907. if( *pRoot ){
  15908. mem3.aPool[*pRoot].u.list.prev = i;
  15909. }
  15910. *pRoot = i;
  15911. }
  15912. /*
  15913. ** Link the chunk at index i into either the appropriate
  15914. ** small chunk list, or into the large chunk hash table.
  15915. */
  15916. static void memsys3Link(u32 i){
  15917. u32 size, hash;
  15918. assert( sqlite3_mutex_held(mem3.mutex) );
  15919. assert( i>=1 );
  15920. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15921. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15922. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15923. assert( size>=2 );
  15924. if( size <= MX_SMALL ){
  15925. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15926. }else{
  15927. hash = size % N_HASH;
  15928. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15929. }
  15930. }
  15931. /*
  15932. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15933. ** will already be held (obtained by code in malloc.c) if
  15934. ** sqlite3GlobalConfig.bMemStat is true.
  15935. */
  15936. static void memsys3Enter(void){
  15937. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15938. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15939. }
  15940. sqlite3_mutex_enter(mem3.mutex);
  15941. }
  15942. static void memsys3Leave(void){
  15943. sqlite3_mutex_leave(mem3.mutex);
  15944. }
  15945. /*
  15946. ** Called when we are unable to satisfy an allocation of nBytes.
  15947. */
  15948. static void memsys3OutOfMemory(int nByte){
  15949. if( !mem3.alarmBusy ){
  15950. mem3.alarmBusy = 1;
  15951. assert( sqlite3_mutex_held(mem3.mutex) );
  15952. sqlite3_mutex_leave(mem3.mutex);
  15953. sqlite3_release_memory(nByte);
  15954. sqlite3_mutex_enter(mem3.mutex);
  15955. mem3.alarmBusy = 0;
  15956. }
  15957. }
  15958. /*
  15959. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15960. ** size parameters for check-out and return a pointer to the
  15961. ** user portion of the chunk.
  15962. */
  15963. static void *memsys3Checkout(u32 i, u32 nBlock){
  15964. u32 x;
  15965. assert( sqlite3_mutex_held(mem3.mutex) );
  15966. assert( i>=1 );
  15967. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15968. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15969. x = mem3.aPool[i-1].u.hdr.size4x;
  15970. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15971. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15972. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15973. return &mem3.aPool[i];
  15974. }
  15975. /*
  15976. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15977. ** Return a pointer to the new allocation. Or, if the master chunk
  15978. ** is not large enough, return 0.
  15979. */
  15980. static void *memsys3FromMaster(u32 nBlock){
  15981. assert( sqlite3_mutex_held(mem3.mutex) );
  15982. assert( mem3.szMaster>=nBlock );
  15983. if( nBlock>=mem3.szMaster-1 ){
  15984. /* Use the entire master */
  15985. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15986. mem3.iMaster = 0;
  15987. mem3.szMaster = 0;
  15988. mem3.mnMaster = 0;
  15989. return p;
  15990. }else{
  15991. /* Split the master block. Return the tail. */
  15992. u32 newi, x;
  15993. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15994. assert( newi > mem3.iMaster+1 );
  15995. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15996. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15997. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15998. mem3.szMaster -= nBlock;
  15999. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  16000. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16001. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16002. if( mem3.szMaster < mem3.mnMaster ){
  16003. mem3.mnMaster = mem3.szMaster;
  16004. }
  16005. return (void*)&mem3.aPool[newi];
  16006. }
  16007. }
  16008. /*
  16009. ** *pRoot is the head of a list of free chunks of the same size
  16010. ** or same size hash. In other words, *pRoot is an entry in either
  16011. ** mem3.aiSmall[] or mem3.aiHash[].
  16012. **
  16013. ** This routine examines all entries on the given list and tries
  16014. ** to coalesce each entries with adjacent free chunks.
  16015. **
  16016. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  16017. ** the current mem3.iMaster with the new larger chunk. In order for
  16018. ** this mem3.iMaster replacement to work, the master chunk must be
  16019. ** linked into the hash tables. That is not the normal state of
  16020. ** affairs, of course. The calling routine must link the master
  16021. ** chunk before invoking this routine, then must unlink the (possibly
  16022. ** changed) master chunk once this routine has finished.
  16023. */
  16024. static void memsys3Merge(u32 *pRoot){
  16025. u32 iNext, prev, size, i, x;
  16026. assert( sqlite3_mutex_held(mem3.mutex) );
  16027. for(i=*pRoot; i>0; i=iNext){
  16028. iNext = mem3.aPool[i].u.list.next;
  16029. size = mem3.aPool[i-1].u.hdr.size4x;
  16030. assert( (size&1)==0 );
  16031. if( (size&2)==0 ){
  16032. memsys3UnlinkFromList(i, pRoot);
  16033. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16034. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16035. if( prev==iNext ){
  16036. iNext = mem3.aPool[prev].u.list.next;
  16037. }
  16038. memsys3Unlink(prev);
  16039. size = i + size/4 - prev;
  16040. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16041. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16042. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16043. memsys3Link(prev);
  16044. i = prev;
  16045. }else{
  16046. size /= 4;
  16047. }
  16048. if( size>mem3.szMaster ){
  16049. mem3.iMaster = i;
  16050. mem3.szMaster = size;
  16051. }
  16052. }
  16053. }
  16054. /*
  16055. ** Return a block of memory of at least nBytes in size.
  16056. ** Return NULL if unable.
  16057. **
  16058. ** This function assumes that the necessary mutexes, if any, are
  16059. ** already held by the caller. Hence "Unsafe".
  16060. */
  16061. static void *memsys3MallocUnsafe(int nByte){
  16062. u32 i;
  16063. u32 nBlock;
  16064. u32 toFree;
  16065. assert( sqlite3_mutex_held(mem3.mutex) );
  16066. assert( sizeof(Mem3Block)==8 );
  16067. if( nByte<=12 ){
  16068. nBlock = 2;
  16069. }else{
  16070. nBlock = (nByte + 11)/8;
  16071. }
  16072. assert( nBlock>=2 );
  16073. /* STEP 1:
  16074. ** Look for an entry of the correct size in either the small
  16075. ** chunk table or in the large chunk hash table. This is
  16076. ** successful most of the time (about 9 times out of 10).
  16077. */
  16078. if( nBlock <= MX_SMALL ){
  16079. i = mem3.aiSmall[nBlock-2];
  16080. if( i>0 ){
  16081. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16082. return memsys3Checkout(i, nBlock);
  16083. }
  16084. }else{
  16085. int hash = nBlock % N_HASH;
  16086. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16087. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16088. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16089. return memsys3Checkout(i, nBlock);
  16090. }
  16091. }
  16092. }
  16093. /* STEP 2:
  16094. ** Try to satisfy the allocation by carving a piece off of the end
  16095. ** of the master chunk. This step usually works if step 1 fails.
  16096. */
  16097. if( mem3.szMaster>=nBlock ){
  16098. return memsys3FromMaster(nBlock);
  16099. }
  16100. /* STEP 3:
  16101. ** Loop through the entire memory pool. Coalesce adjacent free
  16102. ** chunks. Recompute the master chunk as the largest free chunk.
  16103. ** Then try again to satisfy the allocation by carving a piece off
  16104. ** of the end of the master chunk. This step happens very
  16105. ** rarely (we hope!)
  16106. */
  16107. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16108. memsys3OutOfMemory(toFree);
  16109. if( mem3.iMaster ){
  16110. memsys3Link(mem3.iMaster);
  16111. mem3.iMaster = 0;
  16112. mem3.szMaster = 0;
  16113. }
  16114. for(i=0; i<N_HASH; i++){
  16115. memsys3Merge(&mem3.aiHash[i]);
  16116. }
  16117. for(i=0; i<MX_SMALL-1; i++){
  16118. memsys3Merge(&mem3.aiSmall[i]);
  16119. }
  16120. if( mem3.szMaster ){
  16121. memsys3Unlink(mem3.iMaster);
  16122. if( mem3.szMaster>=nBlock ){
  16123. return memsys3FromMaster(nBlock);
  16124. }
  16125. }
  16126. }
  16127. /* If none of the above worked, then we fail. */
  16128. return 0;
  16129. }
  16130. /*
  16131. ** Free an outstanding memory allocation.
  16132. **
  16133. ** This function assumes that the necessary mutexes, if any, are
  16134. ** already held by the caller. Hence "Unsafe".
  16135. */
  16136. static void memsys3FreeUnsafe(void *pOld){
  16137. Mem3Block *p = (Mem3Block*)pOld;
  16138. int i;
  16139. u32 size, x;
  16140. assert( sqlite3_mutex_held(mem3.mutex) );
  16141. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16142. i = p - mem3.aPool;
  16143. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16144. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16145. assert( i+size<=mem3.nPool+1 );
  16146. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16147. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16148. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16149. memsys3Link(i);
  16150. /* Try to expand the master using the newly freed chunk */
  16151. if( mem3.iMaster ){
  16152. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16153. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16154. mem3.iMaster -= size;
  16155. mem3.szMaster += size;
  16156. memsys3Unlink(mem3.iMaster);
  16157. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16158. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16159. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16160. }
  16161. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16162. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16163. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16164. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16165. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16166. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16167. }
  16168. }
  16169. }
  16170. /*
  16171. ** Return the size of an outstanding allocation, in bytes. The
  16172. ** size returned omits the 8-byte header overhead. This only
  16173. ** works for chunks that are currently checked out.
  16174. */
  16175. static int memsys3Size(void *p){
  16176. Mem3Block *pBlock;
  16177. if( p==0 ) return 0;
  16178. pBlock = (Mem3Block*)p;
  16179. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16180. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16181. }
  16182. /*
  16183. ** Round up a request size to the next valid allocation size.
  16184. */
  16185. static int memsys3Roundup(int n){
  16186. if( n<=12 ){
  16187. return 12;
  16188. }else{
  16189. return ((n+11)&~7) - 4;
  16190. }
  16191. }
  16192. /*
  16193. ** Allocate nBytes of memory.
  16194. */
  16195. static void *memsys3Malloc(int nBytes){
  16196. sqlite3_int64 *p;
  16197. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16198. memsys3Enter();
  16199. p = memsys3MallocUnsafe(nBytes);
  16200. memsys3Leave();
  16201. return (void*)p;
  16202. }
  16203. /*
  16204. ** Free memory.
  16205. */
  16206. static void memsys3Free(void *pPrior){
  16207. assert( pPrior );
  16208. memsys3Enter();
  16209. memsys3FreeUnsafe(pPrior);
  16210. memsys3Leave();
  16211. }
  16212. /*
  16213. ** Change the size of an existing memory allocation
  16214. */
  16215. static void *memsys3Realloc(void *pPrior, int nBytes){
  16216. int nOld;
  16217. void *p;
  16218. if( pPrior==0 ){
  16219. return sqlite3_malloc(nBytes);
  16220. }
  16221. if( nBytes<=0 ){
  16222. sqlite3_free(pPrior);
  16223. return 0;
  16224. }
  16225. nOld = memsys3Size(pPrior);
  16226. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16227. return pPrior;
  16228. }
  16229. memsys3Enter();
  16230. p = memsys3MallocUnsafe(nBytes);
  16231. if( p ){
  16232. if( nOld<nBytes ){
  16233. memcpy(p, pPrior, nOld);
  16234. }else{
  16235. memcpy(p, pPrior, nBytes);
  16236. }
  16237. memsys3FreeUnsafe(pPrior);
  16238. }
  16239. memsys3Leave();
  16240. return p;
  16241. }
  16242. /*
  16243. ** Initialize this module.
  16244. */
  16245. static int memsys3Init(void *NotUsed){
  16246. UNUSED_PARAMETER(NotUsed);
  16247. if( !sqlite3GlobalConfig.pHeap ){
  16248. return SQLITE_ERROR;
  16249. }
  16250. /* Store a pointer to the memory block in global structure mem3. */
  16251. assert( sizeof(Mem3Block)==8 );
  16252. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16253. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16254. /* Initialize the master block. */
  16255. mem3.szMaster = mem3.nPool;
  16256. mem3.mnMaster = mem3.szMaster;
  16257. mem3.iMaster = 1;
  16258. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16259. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16260. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16261. return SQLITE_OK;
  16262. }
  16263. /*
  16264. ** Deinitialize this module.
  16265. */
  16266. static void memsys3Shutdown(void *NotUsed){
  16267. UNUSED_PARAMETER(NotUsed);
  16268. mem3.mutex = 0;
  16269. return;
  16270. }
  16271. /*
  16272. ** Open the file indicated and write a log of all unfreed memory
  16273. ** allocations into that log.
  16274. */
  16275. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16276. #ifdef SQLITE_DEBUG
  16277. FILE *out;
  16278. u32 i, j;
  16279. u32 size;
  16280. if( zFilename==0 || zFilename[0]==0 ){
  16281. out = stdout;
  16282. }else{
  16283. out = fopen(zFilename, "w");
  16284. if( out==0 ){
  16285. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16286. zFilename);
  16287. return;
  16288. }
  16289. }
  16290. memsys3Enter();
  16291. fprintf(out, "CHUNKS:\n");
  16292. for(i=1; i<=mem3.nPool; i+=size/4){
  16293. size = mem3.aPool[i-1].u.hdr.size4x;
  16294. if( size/4<=1 ){
  16295. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16296. assert( 0 );
  16297. break;
  16298. }
  16299. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16300. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16301. assert( 0 );
  16302. break;
  16303. }
  16304. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16305. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16306. assert( 0 );
  16307. break;
  16308. }
  16309. if( size&1 ){
  16310. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16311. }else{
  16312. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16313. i==mem3.iMaster ? " **master**" : "");
  16314. }
  16315. }
  16316. for(i=0; i<MX_SMALL-1; i++){
  16317. if( mem3.aiSmall[i]==0 ) continue;
  16318. fprintf(out, "small(%2d):", i);
  16319. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16320. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16321. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16322. }
  16323. fprintf(out, "\n");
  16324. }
  16325. for(i=0; i<N_HASH; i++){
  16326. if( mem3.aiHash[i]==0 ) continue;
  16327. fprintf(out, "hash(%2d):", i);
  16328. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16329. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16330. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16331. }
  16332. fprintf(out, "\n");
  16333. }
  16334. fprintf(out, "master=%d\n", mem3.iMaster);
  16335. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16336. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16337. sqlite3_mutex_leave(mem3.mutex);
  16338. if( out==stdout ){
  16339. fflush(stdout);
  16340. }else{
  16341. fclose(out);
  16342. }
  16343. #else
  16344. UNUSED_PARAMETER(zFilename);
  16345. #endif
  16346. }
  16347. /*
  16348. ** This routine is the only routine in this file with external
  16349. ** linkage.
  16350. **
  16351. ** Populate the low-level memory allocation function pointers in
  16352. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16353. ** arguments specify the block of memory to manage.
  16354. **
  16355. ** This routine is only called by sqlite3_config(), and therefore
  16356. ** is not required to be threadsafe (it is not).
  16357. */
  16358. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16359. static const sqlite3_mem_methods mempoolMethods = {
  16360. memsys3Malloc,
  16361. memsys3Free,
  16362. memsys3Realloc,
  16363. memsys3Size,
  16364. memsys3Roundup,
  16365. memsys3Init,
  16366. memsys3Shutdown,
  16367. 0
  16368. };
  16369. return &mempoolMethods;
  16370. }
  16371. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16372. /************** End of mem3.c ************************************************/
  16373. /************** Begin file mem5.c ********************************************/
  16374. /*
  16375. ** 2007 October 14
  16376. **
  16377. ** The author disclaims copyright to this source code. In place of
  16378. ** a legal notice, here is a blessing:
  16379. **
  16380. ** May you do good and not evil.
  16381. ** May you find forgiveness for yourself and forgive others.
  16382. ** May you share freely, never taking more than you give.
  16383. **
  16384. *************************************************************************
  16385. ** This file contains the C functions that implement a memory
  16386. ** allocation subsystem for use by SQLite.
  16387. **
  16388. ** This version of the memory allocation subsystem omits all
  16389. ** use of malloc(). The application gives SQLite a block of memory
  16390. ** before calling sqlite3_initialize() from which allocations
  16391. ** are made and returned by the xMalloc() and xRealloc()
  16392. ** implementations. Once sqlite3_initialize() has been called,
  16393. ** the amount of memory available to SQLite is fixed and cannot
  16394. ** be changed.
  16395. **
  16396. ** This version of the memory allocation subsystem is included
  16397. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16398. **
  16399. ** This memory allocator uses the following algorithm:
  16400. **
  16401. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16402. **
  16403. ** 2. If two adjacent free blocks are the halves of a larger block,
  16404. ** then the two blocks are coalesed into the single larger block.
  16405. **
  16406. ** 3. New memory is allocated from the first available free block.
  16407. **
  16408. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16409. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16410. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16411. **
  16412. ** Let n be the size of the largest allocation divided by the minimum
  16413. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16414. ** be the maximum amount of memory ever outstanding at one time. Let
  16415. ** N be the total amount of memory available for allocation. Robson
  16416. ** proved that this memory allocator will never breakdown due to
  16417. ** fragmentation as long as the following constraint holds:
  16418. **
  16419. ** N >= M*(1 + log2(n)/2) - n + 1
  16420. **
  16421. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16422. ** that an application can, at any time, verify this constraint.
  16423. */
  16424. /*
  16425. ** This version of the memory allocator is used only when
  16426. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16427. */
  16428. #ifdef SQLITE_ENABLE_MEMSYS5
  16429. /*
  16430. ** A minimum allocation is an instance of the following structure.
  16431. ** Larger allocations are an array of these structures where the
  16432. ** size of the array is a power of 2.
  16433. **
  16434. ** The size of this object must be a power of two. That fact is
  16435. ** verified in memsys5Init().
  16436. */
  16437. typedef struct Mem5Link Mem5Link;
  16438. struct Mem5Link {
  16439. int next; /* Index of next free chunk */
  16440. int prev; /* Index of previous free chunk */
  16441. };
  16442. /*
  16443. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16444. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16445. ** it is not actually possible to reach this limit.
  16446. */
  16447. #define LOGMAX 30
  16448. /*
  16449. ** Masks used for mem5.aCtrl[] elements.
  16450. */
  16451. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16452. #define CTRL_FREE 0x20 /* True if not checked out */
  16453. /*
  16454. ** All of the static variables used by this module are collected
  16455. ** into a single structure named "mem5". This is to keep the
  16456. ** static variables organized and to reduce namespace pollution
  16457. ** when this module is combined with other in the amalgamation.
  16458. */
  16459. static SQLITE_WSD struct Mem5Global {
  16460. /*
  16461. ** Memory available for allocation
  16462. */
  16463. int szAtom; /* Smallest possible allocation in bytes */
  16464. int nBlock; /* Number of szAtom sized blocks in zPool */
  16465. u8 *zPool; /* Memory available to be allocated */
  16466. /*
  16467. ** Mutex to control access to the memory allocation subsystem.
  16468. */
  16469. sqlite3_mutex *mutex;
  16470. /*
  16471. ** Performance statistics
  16472. */
  16473. u64 nAlloc; /* Total number of calls to malloc */
  16474. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16475. u64 totalExcess; /* Total internal fragmentation */
  16476. u32 currentOut; /* Current checkout, including internal fragmentation */
  16477. u32 currentCount; /* Current number of distinct checkouts */
  16478. u32 maxOut; /* Maximum instantaneous currentOut */
  16479. u32 maxCount; /* Maximum instantaneous currentCount */
  16480. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16481. /*
  16482. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16483. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16484. ** and so forth.
  16485. */
  16486. int aiFreelist[LOGMAX+1];
  16487. /*
  16488. ** Space for tracking which blocks are checked out and the size
  16489. ** of each block. One byte per block.
  16490. */
  16491. u8 *aCtrl;
  16492. } mem5;
  16493. /*
  16494. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  16495. */
  16496. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16497. /*
  16498. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16499. ** structures, return a pointer to the idx-th such link.
  16500. */
  16501. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16502. /*
  16503. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16504. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16505. */
  16506. static void memsys5Unlink(int i, int iLogsize){
  16507. int next, prev;
  16508. assert( i>=0 && i<mem5.nBlock );
  16509. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16510. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16511. next = MEM5LINK(i)->next;
  16512. prev = MEM5LINK(i)->prev;
  16513. if( prev<0 ){
  16514. mem5.aiFreelist[iLogsize] = next;
  16515. }else{
  16516. MEM5LINK(prev)->next = next;
  16517. }
  16518. if( next>=0 ){
  16519. MEM5LINK(next)->prev = prev;
  16520. }
  16521. }
  16522. /*
  16523. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16524. ** free list.
  16525. */
  16526. static void memsys5Link(int i, int iLogsize){
  16527. int x;
  16528. assert( sqlite3_mutex_held(mem5.mutex) );
  16529. assert( i>=0 && i<mem5.nBlock );
  16530. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16531. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16532. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16533. MEM5LINK(i)->prev = -1;
  16534. if( x>=0 ){
  16535. assert( x<mem5.nBlock );
  16536. MEM5LINK(x)->prev = i;
  16537. }
  16538. mem5.aiFreelist[iLogsize] = i;
  16539. }
  16540. /*
  16541. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16542. ** will already be held (obtained by code in malloc.c) if
  16543. ** sqlite3GlobalConfig.bMemStat is true.
  16544. */
  16545. static void memsys5Enter(void){
  16546. sqlite3_mutex_enter(mem5.mutex);
  16547. }
  16548. static void memsys5Leave(void){
  16549. sqlite3_mutex_leave(mem5.mutex);
  16550. }
  16551. /*
  16552. ** Return the size of an outstanding allocation, in bytes. The
  16553. ** size returned omits the 8-byte header overhead. This only
  16554. ** works for chunks that are currently checked out.
  16555. */
  16556. static int memsys5Size(void *p){
  16557. int iSize = 0;
  16558. if( p ){
  16559. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16560. assert( i>=0 && i<mem5.nBlock );
  16561. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16562. }
  16563. return iSize;
  16564. }
  16565. /*
  16566. ** Find the first entry on the freelist iLogsize. Unlink that
  16567. ** entry and return its index.
  16568. */
  16569. static int memsys5UnlinkFirst(int iLogsize){
  16570. int i;
  16571. int iFirst;
  16572. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16573. i = iFirst = mem5.aiFreelist[iLogsize];
  16574. assert( iFirst>=0 );
  16575. while( i>0 ){
  16576. if( i<iFirst ) iFirst = i;
  16577. i = MEM5LINK(i)->next;
  16578. }
  16579. memsys5Unlink(iFirst, iLogsize);
  16580. return iFirst;
  16581. }
  16582. /*
  16583. ** Return a block of memory of at least nBytes in size.
  16584. ** Return NULL if unable. Return NULL if nBytes==0.
  16585. **
  16586. ** The caller guarantees that nByte is positive.
  16587. **
  16588. ** The caller has obtained a mutex prior to invoking this
  16589. ** routine so there is never any chance that two or more
  16590. ** threads can be in this routine at the same time.
  16591. */
  16592. static void *memsys5MallocUnsafe(int nByte){
  16593. int i; /* Index of a mem5.aPool[] slot */
  16594. int iBin; /* Index into mem5.aiFreelist[] */
  16595. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16596. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16597. /* nByte must be a positive */
  16598. assert( nByte>0 );
  16599. /* Keep track of the maximum allocation request. Even unfulfilled
  16600. ** requests are counted */
  16601. if( (u32)nByte>mem5.maxRequest ){
  16602. mem5.maxRequest = nByte;
  16603. }
  16604. /* Abort if the requested allocation size is larger than the largest
  16605. ** power of two that we can represent using 32-bit signed integers.
  16606. */
  16607. if( nByte > 0x40000000 ){
  16608. return 0;
  16609. }
  16610. /* Round nByte up to the next valid power of two */
  16611. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16612. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16613. ** block. If not, then split a block of the next larger power of
  16614. ** two in order to create a new free block of size iLogsize.
  16615. */
  16616. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16617. if( iBin>LOGMAX ){
  16618. testcase( sqlite3GlobalConfig.xLog!=0 );
  16619. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16620. return 0;
  16621. }
  16622. i = memsys5UnlinkFirst(iBin);
  16623. while( iBin>iLogsize ){
  16624. int newSize;
  16625. iBin--;
  16626. newSize = 1 << iBin;
  16627. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16628. memsys5Link(i+newSize, iBin);
  16629. }
  16630. mem5.aCtrl[i] = iLogsize;
  16631. /* Update allocator performance statistics. */
  16632. mem5.nAlloc++;
  16633. mem5.totalAlloc += iFullSz;
  16634. mem5.totalExcess += iFullSz - nByte;
  16635. mem5.currentCount++;
  16636. mem5.currentOut += iFullSz;
  16637. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16638. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16639. /* Return a pointer to the allocated memory. */
  16640. return (void*)&mem5.zPool[i*mem5.szAtom];
  16641. }
  16642. /*
  16643. ** Free an outstanding memory allocation.
  16644. */
  16645. static void memsys5FreeUnsafe(void *pOld){
  16646. u32 size, iLogsize;
  16647. int iBlock;
  16648. /* Set iBlock to the index of the block pointed to by pOld in
  16649. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16650. */
  16651. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16652. /* Check that the pointer pOld points to a valid, non-free block. */
  16653. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16654. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16655. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16656. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16657. size = 1<<iLogsize;
  16658. assert( iBlock+size-1<(u32)mem5.nBlock );
  16659. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16660. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16661. assert( mem5.currentCount>0 );
  16662. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16663. mem5.currentCount--;
  16664. mem5.currentOut -= size*mem5.szAtom;
  16665. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16666. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16667. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16668. while( ALWAYS(iLogsize<LOGMAX) ){
  16669. int iBuddy;
  16670. if( (iBlock>>iLogsize) & 1 ){
  16671. iBuddy = iBlock - size;
  16672. }else{
  16673. iBuddy = iBlock + size;
  16674. }
  16675. assert( iBuddy>=0 );
  16676. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16677. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16678. memsys5Unlink(iBuddy, iLogsize);
  16679. iLogsize++;
  16680. if( iBuddy<iBlock ){
  16681. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16682. mem5.aCtrl[iBlock] = 0;
  16683. iBlock = iBuddy;
  16684. }else{
  16685. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16686. mem5.aCtrl[iBuddy] = 0;
  16687. }
  16688. size *= 2;
  16689. }
  16690. memsys5Link(iBlock, iLogsize);
  16691. }
  16692. /*
  16693. ** Allocate nBytes of memory.
  16694. */
  16695. static void *memsys5Malloc(int nBytes){
  16696. sqlite3_int64 *p = 0;
  16697. if( nBytes>0 ){
  16698. memsys5Enter();
  16699. p = memsys5MallocUnsafe(nBytes);
  16700. memsys5Leave();
  16701. }
  16702. return (void*)p;
  16703. }
  16704. /*
  16705. ** Free memory.
  16706. **
  16707. ** The outer layer memory allocator prevents this routine from
  16708. ** being called with pPrior==0.
  16709. */
  16710. static void memsys5Free(void *pPrior){
  16711. assert( pPrior!=0 );
  16712. memsys5Enter();
  16713. memsys5FreeUnsafe(pPrior);
  16714. memsys5Leave();
  16715. }
  16716. /*
  16717. ** Change the size of an existing memory allocation.
  16718. **
  16719. ** The outer layer memory allocator prevents this routine from
  16720. ** being called with pPrior==0.
  16721. **
  16722. ** nBytes is always a value obtained from a prior call to
  16723. ** memsys5Round(). Hence nBytes is always a non-negative power
  16724. ** of two. If nBytes==0 that means that an oversize allocation
  16725. ** (an allocation larger than 0x40000000) was requested and this
  16726. ** routine should return 0 without freeing pPrior.
  16727. */
  16728. static void *memsys5Realloc(void *pPrior, int nBytes){
  16729. int nOld;
  16730. void *p;
  16731. assert( pPrior!=0 );
  16732. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16733. assert( nBytes>=0 );
  16734. if( nBytes==0 ){
  16735. return 0;
  16736. }
  16737. nOld = memsys5Size(pPrior);
  16738. if( nBytes<=nOld ){
  16739. return pPrior;
  16740. }
  16741. memsys5Enter();
  16742. p = memsys5MallocUnsafe(nBytes);
  16743. if( p ){
  16744. memcpy(p, pPrior, nOld);
  16745. memsys5FreeUnsafe(pPrior);
  16746. }
  16747. memsys5Leave();
  16748. return p;
  16749. }
  16750. /*
  16751. ** Round up a request size to the next valid allocation size. If
  16752. ** the allocation is too large to be handled by this allocation system,
  16753. ** return 0.
  16754. **
  16755. ** All allocations must be a power of two and must be expressed by a
  16756. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16757. ** or 1073741824 bytes.
  16758. */
  16759. static int memsys5Roundup(int n){
  16760. int iFullSz;
  16761. if( n > 0x40000000 ) return 0;
  16762. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16763. return iFullSz;
  16764. }
  16765. /*
  16766. ** Return the ceiling of the logarithm base 2 of iValue.
  16767. **
  16768. ** Examples: memsys5Log(1) -> 0
  16769. ** memsys5Log(2) -> 1
  16770. ** memsys5Log(4) -> 2
  16771. ** memsys5Log(5) -> 3
  16772. ** memsys5Log(8) -> 3
  16773. ** memsys5Log(9) -> 4
  16774. */
  16775. static int memsys5Log(int iValue){
  16776. int iLog;
  16777. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16778. return iLog;
  16779. }
  16780. /*
  16781. ** Initialize the memory allocator.
  16782. **
  16783. ** This routine is not threadsafe. The caller must be holding a mutex
  16784. ** to prevent multiple threads from entering at the same time.
  16785. */
  16786. static int memsys5Init(void *NotUsed){
  16787. int ii; /* Loop counter */
  16788. int nByte; /* Number of bytes of memory available to this allocator */
  16789. u8 *zByte; /* Memory usable by this allocator */
  16790. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16791. int iOffset; /* An offset into mem5.aCtrl[] */
  16792. UNUSED_PARAMETER(NotUsed);
  16793. /* For the purposes of this routine, disable the mutex */
  16794. mem5.mutex = 0;
  16795. /* The size of a Mem5Link object must be a power of two. Verify that
  16796. ** this is case.
  16797. */
  16798. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16799. nByte = sqlite3GlobalConfig.nHeap;
  16800. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16801. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16802. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16803. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16804. mem5.szAtom = (1<<nMinLog);
  16805. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16806. mem5.szAtom = mem5.szAtom << 1;
  16807. }
  16808. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16809. mem5.zPool = zByte;
  16810. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16811. for(ii=0; ii<=LOGMAX; ii++){
  16812. mem5.aiFreelist[ii] = -1;
  16813. }
  16814. iOffset = 0;
  16815. for(ii=LOGMAX; ii>=0; ii--){
  16816. int nAlloc = (1<<ii);
  16817. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16818. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16819. memsys5Link(iOffset, ii);
  16820. iOffset += nAlloc;
  16821. }
  16822. assert((iOffset+nAlloc)>mem5.nBlock);
  16823. }
  16824. /* If a mutex is required for normal operation, allocate one */
  16825. if( sqlite3GlobalConfig.bMemstat==0 ){
  16826. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16827. }
  16828. return SQLITE_OK;
  16829. }
  16830. /*
  16831. ** Deinitialize this module.
  16832. */
  16833. static void memsys5Shutdown(void *NotUsed){
  16834. UNUSED_PARAMETER(NotUsed);
  16835. mem5.mutex = 0;
  16836. return;
  16837. }
  16838. #ifdef SQLITE_TEST
  16839. /*
  16840. ** Open the file indicated and write a log of all unfreed memory
  16841. ** allocations into that log.
  16842. */
  16843. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16844. FILE *out;
  16845. int i, j, n;
  16846. int nMinLog;
  16847. if( zFilename==0 || zFilename[0]==0 ){
  16848. out = stdout;
  16849. }else{
  16850. out = fopen(zFilename, "w");
  16851. if( out==0 ){
  16852. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16853. zFilename);
  16854. return;
  16855. }
  16856. }
  16857. memsys5Enter();
  16858. nMinLog = memsys5Log(mem5.szAtom);
  16859. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16860. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16861. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16862. }
  16863. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16864. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16865. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16866. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16867. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16868. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16869. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16870. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16871. memsys5Leave();
  16872. if( out==stdout ){
  16873. fflush(stdout);
  16874. }else{
  16875. fclose(out);
  16876. }
  16877. }
  16878. #endif
  16879. /*
  16880. ** This routine is the only routine in this file with external
  16881. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16882. ** struct populated with the memsys5 methods.
  16883. */
  16884. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16885. static const sqlite3_mem_methods memsys5Methods = {
  16886. memsys5Malloc,
  16887. memsys5Free,
  16888. memsys5Realloc,
  16889. memsys5Size,
  16890. memsys5Roundup,
  16891. memsys5Init,
  16892. memsys5Shutdown,
  16893. 0
  16894. };
  16895. return &memsys5Methods;
  16896. }
  16897. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16898. /************** End of mem5.c ************************************************/
  16899. /************** Begin file mutex.c *******************************************/
  16900. /*
  16901. ** 2007 August 14
  16902. **
  16903. ** The author disclaims copyright to this source code. In place of
  16904. ** a legal notice, here is a blessing:
  16905. **
  16906. ** May you do good and not evil.
  16907. ** May you find forgiveness for yourself and forgive others.
  16908. ** May you share freely, never taking more than you give.
  16909. **
  16910. *************************************************************************
  16911. ** This file contains the C functions that implement mutexes.
  16912. **
  16913. ** This file contains code that is common across all mutex implementations.
  16914. */
  16915. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16916. /*
  16917. ** For debugging purposes, record when the mutex subsystem is initialized
  16918. ** and uninitialized so that we can assert() if there is an attempt to
  16919. ** allocate a mutex while the system is uninitialized.
  16920. */
  16921. static SQLITE_WSD int mutexIsInit = 0;
  16922. #endif /* SQLITE_DEBUG */
  16923. #ifndef SQLITE_MUTEX_OMIT
  16924. /*
  16925. ** Initialize the mutex system.
  16926. */
  16927. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16928. int rc = SQLITE_OK;
  16929. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16930. /* If the xMutexAlloc method has not been set, then the user did not
  16931. ** install a mutex implementation via sqlite3_config() prior to
  16932. ** sqlite3_initialize() being called. This block copies pointers to
  16933. ** the default implementation into the sqlite3GlobalConfig structure.
  16934. */
  16935. sqlite3_mutex_methods const *pFrom;
  16936. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16937. if( sqlite3GlobalConfig.bCoreMutex ){
  16938. pFrom = sqlite3DefaultMutex();
  16939. }else{
  16940. pFrom = sqlite3NoopMutex();
  16941. }
  16942. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16943. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16944. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16945. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16946. }
  16947. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16948. #ifdef SQLITE_DEBUG
  16949. GLOBAL(int, mutexIsInit) = 1;
  16950. #endif
  16951. return rc;
  16952. }
  16953. /*
  16954. ** Shutdown the mutex system. This call frees resources allocated by
  16955. ** sqlite3MutexInit().
  16956. */
  16957. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16958. int rc = SQLITE_OK;
  16959. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16960. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16961. }
  16962. #ifdef SQLITE_DEBUG
  16963. GLOBAL(int, mutexIsInit) = 0;
  16964. #endif
  16965. return rc;
  16966. }
  16967. /*
  16968. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16969. */
  16970. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16971. #ifndef SQLITE_OMIT_AUTOINIT
  16972. if( sqlite3_initialize() ) return 0;
  16973. #endif
  16974. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16975. }
  16976. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16977. if( !sqlite3GlobalConfig.bCoreMutex ){
  16978. return 0;
  16979. }
  16980. assert( GLOBAL(int, mutexIsInit) );
  16981. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16982. }
  16983. /*
  16984. ** Free a dynamic mutex.
  16985. */
  16986. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16987. if( p ){
  16988. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16989. }
  16990. }
  16991. /*
  16992. ** Obtain the mutex p. If some other thread already has the mutex, block
  16993. ** until it can be obtained.
  16994. */
  16995. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16996. if( p ){
  16997. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16998. }
  16999. }
  17000. /*
  17001. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  17002. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  17003. */
  17004. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  17005. int rc = SQLITE_OK;
  17006. if( p ){
  17007. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  17008. }
  17009. return rc;
  17010. }
  17011. /*
  17012. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  17013. ** entered by the same thread. The behavior is undefined if the mutex
  17014. ** is not currently entered. If a NULL pointer is passed as an argument
  17015. ** this function is a no-op.
  17016. */
  17017. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  17018. if( p ){
  17019. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  17020. }
  17021. }
  17022. #ifndef NDEBUG
  17023. /*
  17024. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17025. ** intended for use inside assert() statements.
  17026. */
  17027. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17028. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17029. }
  17030. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17031. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17032. }
  17033. #endif
  17034. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17035. /************** End of mutex.c ***********************************************/
  17036. /************** Begin file mutex_noop.c **************************************/
  17037. /*
  17038. ** 2008 October 07
  17039. **
  17040. ** The author disclaims copyright to this source code. In place of
  17041. ** a legal notice, here is a blessing:
  17042. **
  17043. ** May you do good and not evil.
  17044. ** May you find forgiveness for yourself and forgive others.
  17045. ** May you share freely, never taking more than you give.
  17046. **
  17047. *************************************************************************
  17048. ** This file contains the C functions that implement mutexes.
  17049. **
  17050. ** This implementation in this file does not provide any mutual
  17051. ** exclusion and is thus suitable for use only in applications
  17052. ** that use SQLite in a single thread. The routines defined
  17053. ** here are place-holders. Applications can substitute working
  17054. ** mutex routines at start-time using the
  17055. **
  17056. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17057. **
  17058. ** interface.
  17059. **
  17060. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17061. ** that does error checking on mutexes to make sure they are being
  17062. ** called correctly.
  17063. */
  17064. #ifndef SQLITE_MUTEX_OMIT
  17065. #ifndef SQLITE_DEBUG
  17066. /*
  17067. ** Stub routines for all mutex methods.
  17068. **
  17069. ** This routines provide no mutual exclusion or error checking.
  17070. */
  17071. static int noopMutexInit(void){ return SQLITE_OK; }
  17072. static int noopMutexEnd(void){ return SQLITE_OK; }
  17073. static sqlite3_mutex *noopMutexAlloc(int id){
  17074. UNUSED_PARAMETER(id);
  17075. return (sqlite3_mutex*)8;
  17076. }
  17077. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17078. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17079. static int noopMutexTry(sqlite3_mutex *p){
  17080. UNUSED_PARAMETER(p);
  17081. return SQLITE_OK;
  17082. }
  17083. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17084. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17085. static const sqlite3_mutex_methods sMutex = {
  17086. noopMutexInit,
  17087. noopMutexEnd,
  17088. noopMutexAlloc,
  17089. noopMutexFree,
  17090. noopMutexEnter,
  17091. noopMutexTry,
  17092. noopMutexLeave,
  17093. 0,
  17094. 0,
  17095. };
  17096. return &sMutex;
  17097. }
  17098. #endif /* !SQLITE_DEBUG */
  17099. #ifdef SQLITE_DEBUG
  17100. /*
  17101. ** In this implementation, error checking is provided for testing
  17102. ** and debugging purposes. The mutexes still do not provide any
  17103. ** mutual exclusion.
  17104. */
  17105. /*
  17106. ** The mutex object
  17107. */
  17108. typedef struct sqlite3_debug_mutex {
  17109. int id; /* The mutex type */
  17110. int cnt; /* Number of entries without a matching leave */
  17111. } sqlite3_debug_mutex;
  17112. /*
  17113. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17114. ** intended for use inside assert() statements.
  17115. */
  17116. static int debugMutexHeld(sqlite3_mutex *pX){
  17117. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17118. return p==0 || p->cnt>0;
  17119. }
  17120. static int debugMutexNotheld(sqlite3_mutex *pX){
  17121. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17122. return p==0 || p->cnt==0;
  17123. }
  17124. /*
  17125. ** Initialize and deinitialize the mutex subsystem.
  17126. */
  17127. static int debugMutexInit(void){ return SQLITE_OK; }
  17128. static int debugMutexEnd(void){ return SQLITE_OK; }
  17129. /*
  17130. ** The sqlite3_mutex_alloc() routine allocates a new
  17131. ** mutex and returns a pointer to it. If it returns NULL
  17132. ** that means that a mutex could not be allocated.
  17133. */
  17134. static sqlite3_mutex *debugMutexAlloc(int id){
  17135. static sqlite3_debug_mutex aStatic[6];
  17136. sqlite3_debug_mutex *pNew = 0;
  17137. switch( id ){
  17138. case SQLITE_MUTEX_FAST:
  17139. case SQLITE_MUTEX_RECURSIVE: {
  17140. pNew = sqlite3Malloc(sizeof(*pNew));
  17141. if( pNew ){
  17142. pNew->id = id;
  17143. pNew->cnt = 0;
  17144. }
  17145. break;
  17146. }
  17147. default: {
  17148. assert( id-2 >= 0 );
  17149. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17150. pNew = &aStatic[id-2];
  17151. pNew->id = id;
  17152. break;
  17153. }
  17154. }
  17155. return (sqlite3_mutex*)pNew;
  17156. }
  17157. /*
  17158. ** This routine deallocates a previously allocated mutex.
  17159. */
  17160. static void debugMutexFree(sqlite3_mutex *pX){
  17161. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17162. assert( p->cnt==0 );
  17163. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17164. sqlite3_free(p);
  17165. }
  17166. /*
  17167. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17168. ** to enter a mutex. If another thread is already within the mutex,
  17169. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17170. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17171. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17172. ** be entered multiple times by the same thread. In such cases the,
  17173. ** mutex must be exited an equal number of times before another thread
  17174. ** can enter. If the same thread tries to enter any other kind of mutex
  17175. ** more than once, the behavior is undefined.
  17176. */
  17177. static void debugMutexEnter(sqlite3_mutex *pX){
  17178. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17179. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17180. p->cnt++;
  17181. }
  17182. static int debugMutexTry(sqlite3_mutex *pX){
  17183. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17184. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17185. p->cnt++;
  17186. return SQLITE_OK;
  17187. }
  17188. /*
  17189. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17190. ** previously entered by the same thread. The behavior
  17191. ** is undefined if the mutex is not currently entered or
  17192. ** is not currently allocated. SQLite will never do either.
  17193. */
  17194. static void debugMutexLeave(sqlite3_mutex *pX){
  17195. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17196. assert( debugMutexHeld(pX) );
  17197. p->cnt--;
  17198. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17199. }
  17200. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17201. static const sqlite3_mutex_methods sMutex = {
  17202. debugMutexInit,
  17203. debugMutexEnd,
  17204. debugMutexAlloc,
  17205. debugMutexFree,
  17206. debugMutexEnter,
  17207. debugMutexTry,
  17208. debugMutexLeave,
  17209. debugMutexHeld,
  17210. debugMutexNotheld
  17211. };
  17212. return &sMutex;
  17213. }
  17214. #endif /* SQLITE_DEBUG */
  17215. /*
  17216. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17217. ** is used regardless of the run-time threadsafety setting.
  17218. */
  17219. #ifdef SQLITE_MUTEX_NOOP
  17220. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17221. return sqlite3NoopMutex();
  17222. }
  17223. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17224. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17225. /************** End of mutex_noop.c ******************************************/
  17226. /************** Begin file mutex_unix.c **************************************/
  17227. /*
  17228. ** 2007 August 28
  17229. **
  17230. ** The author disclaims copyright to this source code. In place of
  17231. ** a legal notice, here is a blessing:
  17232. **
  17233. ** May you do good and not evil.
  17234. ** May you find forgiveness for yourself and forgive others.
  17235. ** May you share freely, never taking more than you give.
  17236. **
  17237. *************************************************************************
  17238. ** This file contains the C functions that implement mutexes for pthreads
  17239. */
  17240. /*
  17241. ** The code in this file is only used if we are compiling threadsafe
  17242. ** under unix with pthreads.
  17243. **
  17244. ** Note that this implementation requires a version of pthreads that
  17245. ** supports recursive mutexes.
  17246. */
  17247. #ifdef SQLITE_MUTEX_PTHREADS
  17248. #include <pthread.h>
  17249. /*
  17250. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17251. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17252. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17253. */
  17254. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17255. # define SQLITE_MUTEX_NREF 1
  17256. #else
  17257. # define SQLITE_MUTEX_NREF 0
  17258. #endif
  17259. /*
  17260. ** Each recursive mutex is an instance of the following structure.
  17261. */
  17262. struct sqlite3_mutex {
  17263. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17264. #if SQLITE_MUTEX_NREF
  17265. int id; /* Mutex type */
  17266. volatile int nRef; /* Number of entrances */
  17267. volatile pthread_t owner; /* Thread that is within this mutex */
  17268. int trace; /* True to trace changes */
  17269. #endif
  17270. };
  17271. #if SQLITE_MUTEX_NREF
  17272. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17273. #else
  17274. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  17275. #endif
  17276. /*
  17277. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17278. ** intended for use only inside assert() statements. On some platforms,
  17279. ** there might be race conditions that can cause these routines to
  17280. ** deliver incorrect results. In particular, if pthread_equal() is
  17281. ** not an atomic operation, then these routines might delivery
  17282. ** incorrect results. On most platforms, pthread_equal() is a
  17283. ** comparison of two integers and is therefore atomic. But we are
  17284. ** told that HPUX is not such a platform. If so, then these routines
  17285. ** will not always work correctly on HPUX.
  17286. **
  17287. ** On those platforms where pthread_equal() is not atomic, SQLite
  17288. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17289. ** make sure no assert() statements are evaluated and hence these
  17290. ** routines are never called.
  17291. */
  17292. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17293. static int pthreadMutexHeld(sqlite3_mutex *p){
  17294. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  17295. }
  17296. static int pthreadMutexNotheld(sqlite3_mutex *p){
  17297. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  17298. }
  17299. #endif
  17300. /*
  17301. ** Initialize and deinitialize the mutex subsystem.
  17302. */
  17303. static int pthreadMutexInit(void){ return SQLITE_OK; }
  17304. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  17305. /*
  17306. ** The sqlite3_mutex_alloc() routine allocates a new
  17307. ** mutex and returns a pointer to it. If it returns NULL
  17308. ** that means that a mutex could not be allocated. SQLite
  17309. ** will unwind its stack and return an error. The argument
  17310. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17311. **
  17312. ** <ul>
  17313. ** <li> SQLITE_MUTEX_FAST
  17314. ** <li> SQLITE_MUTEX_RECURSIVE
  17315. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17316. ** <li> SQLITE_MUTEX_STATIC_MEM
  17317. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17318. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17319. ** <li> SQLITE_MUTEX_STATIC_LRU
  17320. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17321. ** </ul>
  17322. **
  17323. ** The first two constants cause sqlite3_mutex_alloc() to create
  17324. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17325. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17326. ** The mutex implementation does not need to make a distinction
  17327. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17328. ** not want to. But SQLite will only request a recursive mutex in
  17329. ** cases where it really needs one. If a faster non-recursive mutex
  17330. ** implementation is available on the host platform, the mutex subsystem
  17331. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17332. **
  17333. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17334. ** a pointer to a static preexisting mutex. Six static mutexes are
  17335. ** used by the current version of SQLite. Future versions of SQLite
  17336. ** may add additional static mutexes. Static mutexes are for internal
  17337. ** use by SQLite only. Applications that use SQLite mutexes should
  17338. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17339. ** SQLITE_MUTEX_RECURSIVE.
  17340. **
  17341. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17342. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17343. ** returns a different mutex on every call. But for the static
  17344. ** mutex types, the same mutex is returned on every call that has
  17345. ** the same type number.
  17346. */
  17347. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17348. static sqlite3_mutex staticMutexes[] = {
  17349. SQLITE3_MUTEX_INITIALIZER,
  17350. SQLITE3_MUTEX_INITIALIZER,
  17351. SQLITE3_MUTEX_INITIALIZER,
  17352. SQLITE3_MUTEX_INITIALIZER,
  17353. SQLITE3_MUTEX_INITIALIZER,
  17354. SQLITE3_MUTEX_INITIALIZER
  17355. };
  17356. sqlite3_mutex *p;
  17357. switch( iType ){
  17358. case SQLITE_MUTEX_RECURSIVE: {
  17359. p = sqlite3MallocZero( sizeof(*p) );
  17360. if( p ){
  17361. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17362. /* If recursive mutexes are not available, we will have to
  17363. ** build our own. See below. */
  17364. pthread_mutex_init(&p->mutex, 0);
  17365. #else
  17366. /* Use a recursive mutex if it is available */
  17367. pthread_mutexattr_t recursiveAttr;
  17368. pthread_mutexattr_init(&recursiveAttr);
  17369. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17370. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17371. pthread_mutexattr_destroy(&recursiveAttr);
  17372. #endif
  17373. #if SQLITE_MUTEX_NREF
  17374. p->id = iType;
  17375. #endif
  17376. }
  17377. break;
  17378. }
  17379. case SQLITE_MUTEX_FAST: {
  17380. p = sqlite3MallocZero( sizeof(*p) );
  17381. if( p ){
  17382. #if SQLITE_MUTEX_NREF
  17383. p->id = iType;
  17384. #endif
  17385. pthread_mutex_init(&p->mutex, 0);
  17386. }
  17387. break;
  17388. }
  17389. default: {
  17390. assert( iType-2 >= 0 );
  17391. assert( iType-2 < ArraySize(staticMutexes) );
  17392. p = &staticMutexes[iType-2];
  17393. #if SQLITE_MUTEX_NREF
  17394. p->id = iType;
  17395. #endif
  17396. break;
  17397. }
  17398. }
  17399. return p;
  17400. }
  17401. /*
  17402. ** This routine deallocates a previously
  17403. ** allocated mutex. SQLite is careful to deallocate every
  17404. ** mutex that it allocates.
  17405. */
  17406. static void pthreadMutexFree(sqlite3_mutex *p){
  17407. assert( p->nRef==0 );
  17408. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17409. pthread_mutex_destroy(&p->mutex);
  17410. sqlite3_free(p);
  17411. }
  17412. /*
  17413. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17414. ** to enter a mutex. If another thread is already within the mutex,
  17415. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17416. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17417. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17418. ** be entered multiple times by the same thread. In such cases the,
  17419. ** mutex must be exited an equal number of times before another thread
  17420. ** can enter. If the same thread tries to enter any other kind of mutex
  17421. ** more than once, the behavior is undefined.
  17422. */
  17423. static void pthreadMutexEnter(sqlite3_mutex *p){
  17424. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17425. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17426. /* If recursive mutexes are not available, then we have to grow
  17427. ** our own. This implementation assumes that pthread_equal()
  17428. ** is atomic - that it cannot be deceived into thinking self
  17429. ** and p->owner are equal if p->owner changes between two values
  17430. ** that are not equal to self while the comparison is taking place.
  17431. ** This implementation also assumes a coherent cache - that
  17432. ** separate processes cannot read different values from the same
  17433. ** address at the same time. If either of these two conditions
  17434. ** are not met, then the mutexes will fail and problems will result.
  17435. */
  17436. {
  17437. pthread_t self = pthread_self();
  17438. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17439. p->nRef++;
  17440. }else{
  17441. pthread_mutex_lock(&p->mutex);
  17442. assert( p->nRef==0 );
  17443. p->owner = self;
  17444. p->nRef = 1;
  17445. }
  17446. }
  17447. #else
  17448. /* Use the built-in recursive mutexes if they are available.
  17449. */
  17450. pthread_mutex_lock(&p->mutex);
  17451. #if SQLITE_MUTEX_NREF
  17452. assert( p->nRef>0 || p->owner==0 );
  17453. p->owner = pthread_self();
  17454. p->nRef++;
  17455. #endif
  17456. #endif
  17457. #ifdef SQLITE_DEBUG
  17458. if( p->trace ){
  17459. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17460. }
  17461. #endif
  17462. }
  17463. static int pthreadMutexTry(sqlite3_mutex *p){
  17464. int rc;
  17465. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17466. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17467. /* If recursive mutexes are not available, then we have to grow
  17468. ** our own. This implementation assumes that pthread_equal()
  17469. ** is atomic - that it cannot be deceived into thinking self
  17470. ** and p->owner are equal if p->owner changes between two values
  17471. ** that are not equal to self while the comparison is taking place.
  17472. ** This implementation also assumes a coherent cache - that
  17473. ** separate processes cannot read different values from the same
  17474. ** address at the same time. If either of these two conditions
  17475. ** are not met, then the mutexes will fail and problems will result.
  17476. */
  17477. {
  17478. pthread_t self = pthread_self();
  17479. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17480. p->nRef++;
  17481. rc = SQLITE_OK;
  17482. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17483. assert( p->nRef==0 );
  17484. p->owner = self;
  17485. p->nRef = 1;
  17486. rc = SQLITE_OK;
  17487. }else{
  17488. rc = SQLITE_BUSY;
  17489. }
  17490. }
  17491. #else
  17492. /* Use the built-in recursive mutexes if they are available.
  17493. */
  17494. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17495. #if SQLITE_MUTEX_NREF
  17496. p->owner = pthread_self();
  17497. p->nRef++;
  17498. #endif
  17499. rc = SQLITE_OK;
  17500. }else{
  17501. rc = SQLITE_BUSY;
  17502. }
  17503. #endif
  17504. #ifdef SQLITE_DEBUG
  17505. if( rc==SQLITE_OK && p->trace ){
  17506. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17507. }
  17508. #endif
  17509. return rc;
  17510. }
  17511. /*
  17512. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17513. ** previously entered by the same thread. The behavior
  17514. ** is undefined if the mutex is not currently entered or
  17515. ** is not currently allocated. SQLite will never do either.
  17516. */
  17517. static void pthreadMutexLeave(sqlite3_mutex *p){
  17518. assert( pthreadMutexHeld(p) );
  17519. #if SQLITE_MUTEX_NREF
  17520. p->nRef--;
  17521. if( p->nRef==0 ) p->owner = 0;
  17522. #endif
  17523. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17524. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17525. if( p->nRef==0 ){
  17526. pthread_mutex_unlock(&p->mutex);
  17527. }
  17528. #else
  17529. pthread_mutex_unlock(&p->mutex);
  17530. #endif
  17531. #ifdef SQLITE_DEBUG
  17532. if( p->trace ){
  17533. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17534. }
  17535. #endif
  17536. }
  17537. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17538. static const sqlite3_mutex_methods sMutex = {
  17539. pthreadMutexInit,
  17540. pthreadMutexEnd,
  17541. pthreadMutexAlloc,
  17542. pthreadMutexFree,
  17543. pthreadMutexEnter,
  17544. pthreadMutexTry,
  17545. pthreadMutexLeave,
  17546. #ifdef SQLITE_DEBUG
  17547. pthreadMutexHeld,
  17548. pthreadMutexNotheld
  17549. #else
  17550. 0,
  17551. 0
  17552. #endif
  17553. };
  17554. return &sMutex;
  17555. }
  17556. #endif /* SQLITE_MUTEX_PTHREADS */
  17557. /************** End of mutex_unix.c ******************************************/
  17558. /************** Begin file mutex_w32.c ***************************************/
  17559. /*
  17560. ** 2007 August 14
  17561. **
  17562. ** The author disclaims copyright to this source code. In place of
  17563. ** a legal notice, here is a blessing:
  17564. **
  17565. ** May you do good and not evil.
  17566. ** May you find forgiveness for yourself and forgive others.
  17567. ** May you share freely, never taking more than you give.
  17568. **
  17569. *************************************************************************
  17570. ** This file contains the C functions that implement mutexes for win32
  17571. */
  17572. /*
  17573. ** The code in this file is only used if we are compiling multithreaded
  17574. ** on a win32 system.
  17575. */
  17576. #ifdef SQLITE_MUTEX_W32
  17577. /*
  17578. ** Each recursive mutex is an instance of the following structure.
  17579. */
  17580. struct sqlite3_mutex {
  17581. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17582. int id; /* Mutex type */
  17583. #ifdef SQLITE_DEBUG
  17584. volatile int nRef; /* Number of enterances */
  17585. volatile DWORD owner; /* Thread holding this mutex */
  17586. int trace; /* True to trace changes */
  17587. #endif
  17588. };
  17589. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17590. #ifdef SQLITE_DEBUG
  17591. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17592. #else
  17593. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17594. #endif
  17595. /*
  17596. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17597. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17598. **
  17599. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17600. ** the LockFileEx() API. But we can still statically link against that
  17601. ** API as long as we don't call it win running Win95/98/ME. A call to
  17602. ** this routine is used to determine if the host is Win95/98/ME or
  17603. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17604. ** the LockFileEx() API.
  17605. **
  17606. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17607. ** which is only available if your application was compiled with
  17608. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17609. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17610. ** this out as well.
  17611. */
  17612. #if 0
  17613. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  17614. # define mutexIsNT() (1)
  17615. #else
  17616. static int mutexIsNT(void){
  17617. static int osType = 0;
  17618. if( osType==0 ){
  17619. OSVERSIONINFO sInfo;
  17620. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17621. GetVersionEx(&sInfo);
  17622. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17623. }
  17624. return osType==2;
  17625. }
  17626. #endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
  17627. #endif
  17628. #ifdef SQLITE_DEBUG
  17629. /*
  17630. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17631. ** intended for use only inside assert() statements.
  17632. */
  17633. static int winMutexHeld(sqlite3_mutex *p){
  17634. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17635. }
  17636. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17637. return p->nRef==0 || p->owner!=tid;
  17638. }
  17639. static int winMutexNotheld(sqlite3_mutex *p){
  17640. DWORD tid = GetCurrentThreadId();
  17641. return winMutexNotheld2(p, tid);
  17642. }
  17643. #endif
  17644. /*
  17645. ** Initialize and deinitialize the mutex subsystem.
  17646. */
  17647. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17648. SQLITE3_MUTEX_INITIALIZER,
  17649. SQLITE3_MUTEX_INITIALIZER,
  17650. SQLITE3_MUTEX_INITIALIZER,
  17651. SQLITE3_MUTEX_INITIALIZER,
  17652. SQLITE3_MUTEX_INITIALIZER,
  17653. SQLITE3_MUTEX_INITIALIZER
  17654. };
  17655. static int winMutex_isInit = 0;
  17656. /* As winMutexInit() and winMutexEnd() are called as part
  17657. ** of the sqlite3_initialize and sqlite3_shutdown()
  17658. ** processing, the "interlocked" magic is probably not
  17659. ** strictly necessary.
  17660. */
  17661. static LONG winMutex_lock = 0;
  17662. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  17663. static int winMutexInit(void){
  17664. /* The first to increment to 1 does actual initialization */
  17665. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17666. int i;
  17667. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17668. #if SQLITE_OS_WINRT
  17669. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  17670. #else
  17671. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17672. #endif
  17673. }
  17674. winMutex_isInit = 1;
  17675. }else{
  17676. /* Someone else is in the process of initing the static mutexes */
  17677. while( !winMutex_isInit ){
  17678. sqlite3_win32_sleep(1);
  17679. }
  17680. }
  17681. return SQLITE_OK;
  17682. }
  17683. static int winMutexEnd(void){
  17684. /* The first to decrement to 0 does actual shutdown
  17685. ** (which should be the last to shutdown.) */
  17686. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17687. if( winMutex_isInit==1 ){
  17688. int i;
  17689. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17690. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17691. }
  17692. winMutex_isInit = 0;
  17693. }
  17694. }
  17695. return SQLITE_OK;
  17696. }
  17697. /*
  17698. ** The sqlite3_mutex_alloc() routine allocates a new
  17699. ** mutex and returns a pointer to it. If it returns NULL
  17700. ** that means that a mutex could not be allocated. SQLite
  17701. ** will unwind its stack and return an error. The argument
  17702. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17703. **
  17704. ** <ul>
  17705. ** <li> SQLITE_MUTEX_FAST
  17706. ** <li> SQLITE_MUTEX_RECURSIVE
  17707. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17708. ** <li> SQLITE_MUTEX_STATIC_MEM
  17709. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17710. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17711. ** <li> SQLITE_MUTEX_STATIC_LRU
  17712. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17713. ** </ul>
  17714. **
  17715. ** The first two constants cause sqlite3_mutex_alloc() to create
  17716. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17717. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17718. ** The mutex implementation does not need to make a distinction
  17719. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17720. ** not want to. But SQLite will only request a recursive mutex in
  17721. ** cases where it really needs one. If a faster non-recursive mutex
  17722. ** implementation is available on the host platform, the mutex subsystem
  17723. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17724. **
  17725. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17726. ** a pointer to a static preexisting mutex. Six static mutexes are
  17727. ** used by the current version of SQLite. Future versions of SQLite
  17728. ** may add additional static mutexes. Static mutexes are for internal
  17729. ** use by SQLite only. Applications that use SQLite mutexes should
  17730. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17731. ** SQLITE_MUTEX_RECURSIVE.
  17732. **
  17733. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17734. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17735. ** returns a different mutex on every call. But for the static
  17736. ** mutex types, the same mutex is returned on every call that has
  17737. ** the same type number.
  17738. */
  17739. static sqlite3_mutex *winMutexAlloc(int iType){
  17740. sqlite3_mutex *p;
  17741. switch( iType ){
  17742. case SQLITE_MUTEX_FAST:
  17743. case SQLITE_MUTEX_RECURSIVE: {
  17744. p = sqlite3MallocZero( sizeof(*p) );
  17745. if( p ){
  17746. #ifdef SQLITE_DEBUG
  17747. p->id = iType;
  17748. #endif
  17749. #if SQLITE_OS_WINRT
  17750. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  17751. #else
  17752. InitializeCriticalSection(&p->mutex);
  17753. #endif
  17754. }
  17755. break;
  17756. }
  17757. default: {
  17758. assert( winMutex_isInit==1 );
  17759. assert( iType-2 >= 0 );
  17760. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17761. p = &winMutex_staticMutexes[iType-2];
  17762. #ifdef SQLITE_DEBUG
  17763. p->id = iType;
  17764. #endif
  17765. break;
  17766. }
  17767. }
  17768. return p;
  17769. }
  17770. /*
  17771. ** This routine deallocates a previously
  17772. ** allocated mutex. SQLite is careful to deallocate every
  17773. ** mutex that it allocates.
  17774. */
  17775. static void winMutexFree(sqlite3_mutex *p){
  17776. assert( p );
  17777. assert( p->nRef==0 && p->owner==0 );
  17778. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17779. DeleteCriticalSection(&p->mutex);
  17780. sqlite3_free(p);
  17781. }
  17782. /*
  17783. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17784. ** to enter a mutex. If another thread is already within the mutex,
  17785. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17786. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17787. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17788. ** be entered multiple times by the same thread. In such cases the,
  17789. ** mutex must be exited an equal number of times before another thread
  17790. ** can enter. If the same thread tries to enter any other kind of mutex
  17791. ** more than once, the behavior is undefined.
  17792. */
  17793. static void winMutexEnter(sqlite3_mutex *p){
  17794. #ifdef SQLITE_DEBUG
  17795. DWORD tid = GetCurrentThreadId();
  17796. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17797. #endif
  17798. EnterCriticalSection(&p->mutex);
  17799. #ifdef SQLITE_DEBUG
  17800. assert( p->nRef>0 || p->owner==0 );
  17801. p->owner = tid;
  17802. p->nRef++;
  17803. if( p->trace ){
  17804. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17805. }
  17806. #endif
  17807. }
  17808. static int winMutexTry(sqlite3_mutex *p){
  17809. #ifndef NDEBUG
  17810. DWORD tid = GetCurrentThreadId();
  17811. #endif
  17812. int rc = SQLITE_BUSY;
  17813. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17814. /*
  17815. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17816. ** is used it is merely an optimization. So it is OK for it to always
  17817. ** fail.
  17818. **
  17819. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17820. ** And some windows compilers complain if you try to use it without
  17821. ** first doing some #defines that prevent SQLite from building on Win98.
  17822. ** For that reason, we will omit this optimization for now. See
  17823. ** ticket #2685.
  17824. */
  17825. #if 0
  17826. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17827. p->owner = tid;
  17828. p->nRef++;
  17829. rc = SQLITE_OK;
  17830. }
  17831. #else
  17832. UNUSED_PARAMETER(p);
  17833. #endif
  17834. #ifdef SQLITE_DEBUG
  17835. if( rc==SQLITE_OK && p->trace ){
  17836. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17837. }
  17838. #endif
  17839. return rc;
  17840. }
  17841. /*
  17842. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17843. ** previously entered by the same thread. The behavior
  17844. ** is undefined if the mutex is not currently entered or
  17845. ** is not currently allocated. SQLite will never do either.
  17846. */
  17847. static void winMutexLeave(sqlite3_mutex *p){
  17848. #ifndef NDEBUG
  17849. DWORD tid = GetCurrentThreadId();
  17850. assert( p->nRef>0 );
  17851. assert( p->owner==tid );
  17852. p->nRef--;
  17853. if( p->nRef==0 ) p->owner = 0;
  17854. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17855. #endif
  17856. LeaveCriticalSection(&p->mutex);
  17857. #ifdef SQLITE_DEBUG
  17858. if( p->trace ){
  17859. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17860. }
  17861. #endif
  17862. }
  17863. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17864. static const sqlite3_mutex_methods sMutex = {
  17865. winMutexInit,
  17866. winMutexEnd,
  17867. winMutexAlloc,
  17868. winMutexFree,
  17869. winMutexEnter,
  17870. winMutexTry,
  17871. winMutexLeave,
  17872. #ifdef SQLITE_DEBUG
  17873. winMutexHeld,
  17874. winMutexNotheld
  17875. #else
  17876. 0,
  17877. 0
  17878. #endif
  17879. };
  17880. return &sMutex;
  17881. }
  17882. #endif /* SQLITE_MUTEX_W32 */
  17883. /************** End of mutex_w32.c *******************************************/
  17884. /************** Begin file mutex_rtt.c ***************************************/
  17885. /*
  17886. ** 2007 August 28
  17887. **
  17888. ** The author disclaims copyright to this source code. In place of
  17889. ** a legal notice, here is a blessing:
  17890. **
  17891. ** May you do good and not evil.
  17892. ** May you find forgiveness for yourself and forgive others.
  17893. ** May you share freely, never taking more than you give.
  17894. **
  17895. *************************************************************************
  17896. ** This file contains the C functions that implement mutexes for rtthread
  17897. */
  17898. /*
  17899. ** The code in this file is only used if we are compiling threadsafe
  17900. ** under rt-thread with rt_mutex.
  17901. **
  17902. ** Note that this implementation requires a version of rt-thread that
  17903. ** supports recursive mutexes.
  17904. */
  17905. #ifdef SQLITE_MUTEX_RTT
  17906. /* #include <rtthread.h> */
  17907. /*
  17908. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17909. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17910. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17911. */
  17912. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17913. # define SQLITE_MUTEX_NREF 1
  17914. #else
  17915. # define SQLITE_MUTEX_NREF 0
  17916. #endif
  17917. /*
  17918. ** Each recursive mutex is an instance of the following structure.
  17919. */
  17920. struct sqlite3_mutex {
  17921. struct rt_mutex mutex; /* Mutex controlling the lock */
  17922. #if SQLITE_MUTEX_NREF
  17923. int id; /* Mutex type */
  17924. volatile int nRef; /* Number of entrances */
  17925. volatile rt_thread_t owner; /* Thread that is within this mutex */
  17926. int trace; /* True to trace changes */
  17927. #endif
  17928. };
  17929. #define RTT_MUTEX_INITIALIZER { 0 }
  17930. #if SQLITE_MUTEX_NREF
  17931. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER, 0, 0, (rt_thread_t)0, 0 }
  17932. #else
  17933. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER }
  17934. #endif
  17935. /*
  17936. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17937. ** intended for use only inside assert() statements. On some platforms,
  17938. ** there might be race conditions that can cause these routines to
  17939. ** deliver incorrect results. In particular, if rtt_equal() is
  17940. ** not an atomic operation, then these routines might delivery
  17941. ** incorrect results. On most platforms, rtt_equal() is a
  17942. ** comparison of two integers and is therefore atomic. But we are
  17943. ** told that HPUX is not such a platform. If so, then these routines
  17944. ** will not always work correctly on HPUX.
  17945. **
  17946. ** On those platforms where rtt_equal() is not atomic, SQLite
  17947. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17948. ** make sure no assert() statements are evaluated and hence these
  17949. ** routines are never called.
  17950. */
  17951. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17952. static int rttMutexHeld(sqlite3_mutex *p){
  17953. return (p->nRef != 0 && p->owner == rt_thread_self());
  17954. }
  17955. static int rttMutexNotheld(sqlite3_mutex *p){
  17956. return (p->nRef == 0 || p->owner != rt_thread_self());
  17957. }
  17958. #endif
  17959. /*
  17960. ** Initialize and deinitialize the mutex subsystem.
  17961. */
  17962. static int rttMutexInit(void){ return SQLITE_OK; }
  17963. static int rttMutexEnd(void){ return SQLITE_OK; }
  17964. /*
  17965. ** The sqlite3_mutex_alloc() routine allocates a new
  17966. ** mutex and returns a pointer to it. If it returns NULL
  17967. ** that means that a mutex could not be allocated. SQLite
  17968. ** will unwind its stack and return an error. The argument
  17969. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17970. **
  17971. ** <ul>
  17972. ** <li> SQLITE_MUTEX_FAST
  17973. ** <li> SQLITE_MUTEX_RECURSIVE
  17974. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17975. ** <li> SQLITE_MUTEX_STATIC_MEM
  17976. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17977. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17978. ** <li> SQLITE_MUTEX_STATIC_LRU
  17979. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17980. ** </ul>
  17981. **
  17982. ** The first two constants cause sqlite3_mutex_alloc() to create
  17983. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17984. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17985. ** The mutex implementation does not need to make a distinction
  17986. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17987. ** not want to. But SQLite will only request a recursive mutex in
  17988. ** cases where it really needs one. If a faster non-recursive mutex
  17989. ** implementation is available on the host platform, the mutex subsystem
  17990. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17991. **
  17992. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17993. ** a pointer to a static preexisting mutex. Six static mutexes are
  17994. ** used by the current version of SQLite. Future versions of SQLite
  17995. ** may add additional static mutexes. Static mutexes are for internal
  17996. ** use by SQLite only. Applications that use SQLite mutexes should
  17997. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17998. ** SQLITE_MUTEX_RECURSIVE.
  17999. **
  18000. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18001. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18002. ** returns a different mutex on every call. But for the static
  18003. ** mutex types, the same mutex is returned on every call that has
  18004. ** the same type number.
  18005. */
  18006. static sqlite3_mutex *rttMutexAlloc(int iType){
  18007. static sqlite3_mutex staticMutexes[] = {
  18008. SQLITE3_MUTEX_INITIALIZER,
  18009. SQLITE3_MUTEX_INITIALIZER,
  18010. SQLITE3_MUTEX_INITIALIZER,
  18011. SQLITE3_MUTEX_INITIALIZER,
  18012. SQLITE3_MUTEX_INITIALIZER,
  18013. SQLITE3_MUTEX_INITIALIZER
  18014. };
  18015. sqlite3_mutex *p;
  18016. switch( iType ){
  18017. case SQLITE_MUTEX_RECURSIVE: {
  18018. p = sqlite3MallocZero( sizeof(*p) );
  18019. if( p ){
  18020. /* Use a recursive mutex if it is available */
  18021. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  18022. #if SQLITE_MUTEX_NREF
  18023. p->id = iType;
  18024. #endif
  18025. }
  18026. break;
  18027. }
  18028. case SQLITE_MUTEX_FAST: {
  18029. p = sqlite3MallocZero( sizeof(*p) );
  18030. if( p ){
  18031. #if SQLITE_MUTEX_NREF
  18032. p->id = iType;
  18033. #endif
  18034. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  18035. }
  18036. break;
  18037. }
  18038. default: {
  18039. assert( iType-2 >= 0 );
  18040. assert( iType-2 < ArraySize(staticMutexes) );
  18041. p = &staticMutexes[iType-2];
  18042. #if SQLITE_MUTEX_NREF
  18043. p->id = iType;
  18044. #endif
  18045. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  18046. break;
  18047. }
  18048. }
  18049. return p;
  18050. }
  18051. /*
  18052. ** This routine deallocates a previously
  18053. ** allocated mutex. SQLite is careful to deallocate every
  18054. ** mutex that it allocates.
  18055. */
  18056. static void rttMutexFree(sqlite3_mutex *p){
  18057. assert( p->nRef==0 );
  18058. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18059. rt_mutex_delete(&p->mutex);
  18060. sqlite3_free(p);
  18061. }
  18062. /*
  18063. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18064. ** to enter a mutex. If another thread is already within the mutex,
  18065. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18066. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18067. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18068. ** be entered multiple times by the same thread. In such cases the,
  18069. ** mutex must be exited an equal number of times before another thread
  18070. ** can enter. If the same thread tries to enter any other kind of mutex
  18071. ** more than once, the behavior is undefined.
  18072. */
  18073. static void rttMutexEnter(sqlite3_mutex *p){
  18074. assert( p->id==SQLITE_MUTEX_RECURSIVE || rttMutexNotheld(p) );
  18075. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18076. /* If recursive mutexes are not available, then we have to grow
  18077. ** our own. This implementation assumes that rtt_equal()
  18078. ** is atomic - that it cannot be deceived into thinking self
  18079. ** and p->owner are equal if p->owner changes between two values
  18080. ** that are not equal to self while the comparison is taking place.
  18081. ** This implementation also assumes a coherent cache - that
  18082. ** separate processes cannot read different values from the same
  18083. ** address at the same time. If either of these two conditions
  18084. ** are not met, then the mutexes will fail and problems will result.
  18085. */
  18086. {
  18087. rt_thread_t self = rt_thread_self();
  18088. if( p->nRef>0 && (p->owner == self) ){
  18089. p->nRef++;
  18090. }else{
  18091. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  18092. assert( p->nRef==0 );
  18093. p->owner = self;
  18094. p->nRef = 1;
  18095. }
  18096. }
  18097. #else
  18098. /* Use the built-in recursive mutexes if they are available.
  18099. */
  18100. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  18101. #if SQLITE_MUTEX_NREF
  18102. assert( p->nRef>0 || p->owner==0 );
  18103. p->owner = rt_thread_self();
  18104. p->nRef++;
  18105. #endif
  18106. #endif
  18107. #ifdef SQLITE_DEBUG
  18108. if( p->trace ){
  18109. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18110. }
  18111. #endif
  18112. }
  18113. static int rttMutexTry(sqlite3_mutex *p){
  18114. int rc;
  18115. assert( p->id==SQLITE_MUTEX_RECURSIVE || rttMutexNotheld(p) );
  18116. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18117. /* If recursive mutexes are not available, then we have to grow
  18118. ** our own. This implementation assumes that rtt_equal()
  18119. ** is atomic - that it cannot be deceived into thinking self
  18120. ** and p->owner are equal if p->owner changes between two values
  18121. ** that are not equal to self while the comparison is taking place.
  18122. ** This implementation also assumes a coherent cache - that
  18123. ** separate processes cannot read different values from the same
  18124. ** address at the same time. If either of these two conditions
  18125. ** are not met, then the mutexes will fail and problems will result.
  18126. */
  18127. {
  18128. rt_thread_t self = rt_thread_self();
  18129. if( p->nRef>0 && (p->owner == self) ){
  18130. p->nRef++;
  18131. rc = SQLITE_OK;
  18132. }else if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  18133. assert( p->nRef==0 );
  18134. p->owner = self;
  18135. p->nRef = 1;
  18136. rc = SQLITE_OK;
  18137. }else{
  18138. rc = SQLITE_BUSY;
  18139. }
  18140. }
  18141. #else
  18142. /* Use the built-in recursive mutexes if they are available.
  18143. */
  18144. if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  18145. #if SQLITE_MUTEX_NREF
  18146. p->owner = rt_thread_self();
  18147. p->nRef++;
  18148. #endif
  18149. rc = SQLITE_OK;
  18150. }else{
  18151. rc = SQLITE_BUSY;
  18152. }
  18153. #endif
  18154. #ifdef SQLITE_DEBUG
  18155. if( rc==SQLITE_OK && p->trace ){
  18156. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18157. }
  18158. #endif
  18159. return rc;
  18160. }
  18161. /*
  18162. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18163. ** previously entered by the same thread. The behavior
  18164. ** is undefined if the mutex is not currently entered or
  18165. ** is not currently allocated. SQLite will never do either.
  18166. */
  18167. static void rttMutexLeave(sqlite3_mutex *p){
  18168. assert( rttMutexHeld(p) );
  18169. #if SQLITE_MUTEX_NREF
  18170. p->nRef--;
  18171. if( p->nRef==0 ) p->owner = 0;
  18172. #endif
  18173. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18174. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18175. if( p->nRef==0 ){
  18176. rt_mutex_release(&p->mutex);
  18177. }
  18178. #else
  18179. rt_mutex_release(&p->mutex);
  18180. #endif
  18181. #ifdef SQLITE_DEBUG
  18182. if( p->trace ){
  18183. rt_kprintf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18184. }
  18185. #endif
  18186. }
  18187. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18188. static const sqlite3_mutex_methods sMutex = {
  18189. rttMutexInit,
  18190. rttMutexEnd,
  18191. rttMutexAlloc,
  18192. rttMutexFree,
  18193. rttMutexEnter,
  18194. rttMutexTry,
  18195. rttMutexLeave,
  18196. #ifdef SQLITE_DEBUG
  18197. rttMutexHeld,
  18198. rttMutexNotheld
  18199. #else
  18200. 0,
  18201. 0
  18202. #endif
  18203. };
  18204. return &sMutex;
  18205. }
  18206. #endif /* SQLITE_MUTEX_RTT */
  18207. /************** End of mutex_rtt.c *******************************************/
  18208. /************** Begin file malloc.c ******************************************/
  18209. /*
  18210. ** 2001 September 15
  18211. **
  18212. ** The author disclaims copyright to this source code. In place of
  18213. ** a legal notice, here is a blessing:
  18214. **
  18215. ** May you do good and not evil.
  18216. ** May you find forgiveness for yourself and forgive others.
  18217. ** May you share freely, never taking more than you give.
  18218. **
  18219. *************************************************************************
  18220. **
  18221. ** Memory allocation functions used throughout sqlite.
  18222. */
  18223. /* #include <stdarg.h> */
  18224. /*
  18225. ** Attempt to release up to n bytes of non-essential memory currently
  18226. ** held by SQLite. An example of non-essential memory is memory used to
  18227. ** cache database pages that are not currently in use.
  18228. */
  18229. SQLITE_API int sqlite3_release_memory(int n){
  18230. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18231. return sqlite3PcacheReleaseMemory(n);
  18232. #else
  18233. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  18234. ** is a no-op returning zero if SQLite is not compiled with
  18235. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  18236. UNUSED_PARAMETER(n);
  18237. return 0;
  18238. #endif
  18239. }
  18240. /*
  18241. ** An instance of the following object records the location of
  18242. ** each unused scratch buffer.
  18243. */
  18244. typedef struct ScratchFreeslot {
  18245. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  18246. } ScratchFreeslot;
  18247. /*
  18248. ** State information local to the memory allocation subsystem.
  18249. */
  18250. static SQLITE_WSD struct Mem0Global {
  18251. sqlite3_mutex *mutex; /* Mutex to serialize access */
  18252. /*
  18253. ** The alarm callback and its arguments. The mem0.mutex lock will
  18254. ** be held while the callback is running. Recursive calls into
  18255. ** the memory subsystem are allowed, but no new callbacks will be
  18256. ** issued.
  18257. */
  18258. sqlite3_int64 alarmThreshold;
  18259. void (*alarmCallback)(void*, sqlite3_int64,int);
  18260. void *alarmArg;
  18261. /*
  18262. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  18263. ** (so that a range test can be used to determine if an allocation
  18264. ** being freed came from pScratch) and a pointer to the list of
  18265. ** unused scratch allocations.
  18266. */
  18267. void *pScratchEnd;
  18268. ScratchFreeslot *pScratchFree;
  18269. u32 nScratchFree;
  18270. /*
  18271. ** True if heap is nearly "full" where "full" is defined by the
  18272. ** sqlite3_soft_heap_limit() setting.
  18273. */
  18274. int nearlyFull;
  18275. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  18276. #define mem0 GLOBAL(struct Mem0Global, mem0)
  18277. /*
  18278. ** This routine runs when the memory allocator sees that the
  18279. ** total memory allocation is about to exceed the soft heap
  18280. ** limit.
  18281. */
  18282. static void softHeapLimitEnforcer(
  18283. void *NotUsed,
  18284. sqlite3_int64 NotUsed2,
  18285. int allocSize
  18286. ){
  18287. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  18288. sqlite3_release_memory(allocSize);
  18289. }
  18290. /*
  18291. ** Change the alarm callback
  18292. */
  18293. static int sqlite3MemoryAlarm(
  18294. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  18295. void *pArg,
  18296. sqlite3_int64 iThreshold
  18297. ){
  18298. int nUsed;
  18299. sqlite3_mutex_enter(mem0.mutex);
  18300. mem0.alarmCallback = xCallback;
  18301. mem0.alarmArg = pArg;
  18302. mem0.alarmThreshold = iThreshold;
  18303. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18304. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  18305. sqlite3_mutex_leave(mem0.mutex);
  18306. return SQLITE_OK;
  18307. }
  18308. #ifndef SQLITE_OMIT_DEPRECATED
  18309. /*
  18310. ** Deprecated external interface. Internal/core SQLite code
  18311. ** should call sqlite3MemoryAlarm.
  18312. */
  18313. SQLITE_API int sqlite3_memory_alarm(
  18314. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  18315. void *pArg,
  18316. sqlite3_int64 iThreshold
  18317. ){
  18318. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  18319. }
  18320. #endif
  18321. /*
  18322. ** Set the soft heap-size limit for the library. Passing a zero or
  18323. ** negative value indicates no limit.
  18324. */
  18325. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  18326. sqlite3_int64 priorLimit;
  18327. sqlite3_int64 excess;
  18328. #ifndef SQLITE_OMIT_AUTOINIT
  18329. int rc = sqlite3_initialize();
  18330. if( rc ) return -1;
  18331. #endif
  18332. sqlite3_mutex_enter(mem0.mutex);
  18333. priorLimit = mem0.alarmThreshold;
  18334. sqlite3_mutex_leave(mem0.mutex);
  18335. if( n<0 ) return priorLimit;
  18336. if( n>0 ){
  18337. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  18338. }else{
  18339. sqlite3MemoryAlarm(0, 0, 0);
  18340. }
  18341. excess = sqlite3_memory_used() - n;
  18342. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  18343. return priorLimit;
  18344. }
  18345. SQLITE_API void sqlite3_soft_heap_limit(int n){
  18346. if( n<0 ) n = 0;
  18347. sqlite3_soft_heap_limit64(n);
  18348. }
  18349. /*
  18350. ** Initialize the memory allocation subsystem.
  18351. */
  18352. SQLITE_PRIVATE int sqlite3MallocInit(void){
  18353. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  18354. sqlite3MemSetDefault();
  18355. }
  18356. memset(&mem0, 0, sizeof(mem0));
  18357. if( sqlite3GlobalConfig.bCoreMutex ){
  18358. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18359. }
  18360. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  18361. && sqlite3GlobalConfig.nScratch>0 ){
  18362. int i, n, sz;
  18363. ScratchFreeslot *pSlot;
  18364. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  18365. sqlite3GlobalConfig.szScratch = sz;
  18366. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  18367. n = sqlite3GlobalConfig.nScratch;
  18368. mem0.pScratchFree = pSlot;
  18369. mem0.nScratchFree = n;
  18370. for(i=0; i<n-1; i++){
  18371. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  18372. pSlot = pSlot->pNext;
  18373. }
  18374. pSlot->pNext = 0;
  18375. mem0.pScratchEnd = (void*)&pSlot[1];
  18376. }else{
  18377. mem0.pScratchEnd = 0;
  18378. sqlite3GlobalConfig.pScratch = 0;
  18379. sqlite3GlobalConfig.szScratch = 0;
  18380. sqlite3GlobalConfig.nScratch = 0;
  18381. }
  18382. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  18383. || sqlite3GlobalConfig.nPage<1 ){
  18384. sqlite3GlobalConfig.pPage = 0;
  18385. sqlite3GlobalConfig.szPage = 0;
  18386. sqlite3GlobalConfig.nPage = 0;
  18387. }
  18388. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  18389. }
  18390. /*
  18391. ** Return true if the heap is currently under memory pressure - in other
  18392. ** words if the amount of heap used is close to the limit set by
  18393. ** sqlite3_soft_heap_limit().
  18394. */
  18395. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  18396. return mem0.nearlyFull;
  18397. }
  18398. /*
  18399. ** Deinitialize the memory allocation subsystem.
  18400. */
  18401. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  18402. if( sqlite3GlobalConfig.m.xShutdown ){
  18403. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  18404. }
  18405. memset(&mem0, 0, sizeof(mem0));
  18406. }
  18407. /*
  18408. ** Return the amount of memory currently checked out.
  18409. */
  18410. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  18411. int n, mx;
  18412. sqlite3_int64 res;
  18413. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  18414. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  18415. return res;
  18416. }
  18417. /*
  18418. ** Return the maximum amount of memory that has ever been
  18419. ** checked out since either the beginning of this process
  18420. ** or since the most recent reset.
  18421. */
  18422. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  18423. int n, mx;
  18424. sqlite3_int64 res;
  18425. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  18426. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  18427. return res;
  18428. }
  18429. /*
  18430. ** Trigger the alarm
  18431. */
  18432. static void sqlite3MallocAlarm(int nByte){
  18433. void (*xCallback)(void*,sqlite3_int64,int);
  18434. sqlite3_int64 nowUsed;
  18435. void *pArg;
  18436. if( mem0.alarmCallback==0 ) return;
  18437. xCallback = mem0.alarmCallback;
  18438. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18439. pArg = mem0.alarmArg;
  18440. mem0.alarmCallback = 0;
  18441. sqlite3_mutex_leave(mem0.mutex);
  18442. xCallback(pArg, nowUsed, nByte);
  18443. sqlite3_mutex_enter(mem0.mutex);
  18444. mem0.alarmCallback = xCallback;
  18445. mem0.alarmArg = pArg;
  18446. }
  18447. /*
  18448. ** Do a memory allocation with statistics and alarms. Assume the
  18449. ** lock is already held.
  18450. */
  18451. static int mallocWithAlarm(int n, void **pp){
  18452. int nFull;
  18453. void *p;
  18454. assert( sqlite3_mutex_held(mem0.mutex) );
  18455. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  18456. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  18457. if( mem0.alarmCallback!=0 ){
  18458. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18459. if( nUsed >= mem0.alarmThreshold - nFull ){
  18460. mem0.nearlyFull = 1;
  18461. sqlite3MallocAlarm(nFull);
  18462. }else{
  18463. mem0.nearlyFull = 0;
  18464. }
  18465. }
  18466. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18467. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18468. if( p==0 && mem0.alarmCallback ){
  18469. sqlite3MallocAlarm(nFull);
  18470. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18471. }
  18472. #endif
  18473. if( p ){
  18474. nFull = sqlite3MallocSize(p);
  18475. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  18476. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  18477. }
  18478. *pp = p;
  18479. return nFull;
  18480. }
  18481. /*
  18482. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  18483. ** assumes the memory subsystem has already been initialized.
  18484. */
  18485. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  18486. void *p;
  18487. if( n<=0 /* IMP: R-65312-04917 */
  18488. || n>=0x7fffff00
  18489. ){
  18490. /* A memory allocation of a number of bytes which is near the maximum
  18491. ** signed integer value might cause an integer overflow inside of the
  18492. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  18493. ** 255 bytes of overhead. SQLite itself will never use anything near
  18494. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  18495. p = 0;
  18496. }else if( sqlite3GlobalConfig.bMemstat ){
  18497. sqlite3_mutex_enter(mem0.mutex);
  18498. mallocWithAlarm(n, &p);
  18499. sqlite3_mutex_leave(mem0.mutex);
  18500. }else{
  18501. p = sqlite3GlobalConfig.m.xMalloc(n);
  18502. }
  18503. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  18504. return p;
  18505. }
  18506. /*
  18507. ** This version of the memory allocation is for use by the application.
  18508. ** First make sure the memory subsystem is initialized, then do the
  18509. ** allocation.
  18510. */
  18511. SQLITE_API void *sqlite3_malloc(int n){
  18512. #ifndef SQLITE_OMIT_AUTOINIT
  18513. if( sqlite3_initialize() ) return 0;
  18514. #endif
  18515. return sqlite3Malloc(n);
  18516. }
  18517. /*
  18518. ** Each thread may only have a single outstanding allocation from
  18519. ** xScratchMalloc(). We verify this constraint in the single-threaded
  18520. ** case by setting scratchAllocOut to 1 when an allocation
  18521. ** is outstanding clearing it when the allocation is freed.
  18522. */
  18523. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18524. static int scratchAllocOut = 0;
  18525. #endif
  18526. /*
  18527. ** Allocate memory that is to be used and released right away.
  18528. ** This routine is similar to alloca() in that it is not intended
  18529. ** for situations where the memory might be held long-term. This
  18530. ** routine is intended to get memory to old large transient data
  18531. ** structures that would not normally fit on the stack of an
  18532. ** embedded processor.
  18533. */
  18534. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  18535. void *p;
  18536. assert( n>0 );
  18537. sqlite3_mutex_enter(mem0.mutex);
  18538. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  18539. p = mem0.pScratchFree;
  18540. mem0.pScratchFree = mem0.pScratchFree->pNext;
  18541. mem0.nScratchFree--;
  18542. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  18543. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18544. sqlite3_mutex_leave(mem0.mutex);
  18545. }else{
  18546. if( sqlite3GlobalConfig.bMemstat ){
  18547. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18548. n = mallocWithAlarm(n, &p);
  18549. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  18550. sqlite3_mutex_leave(mem0.mutex);
  18551. }else{
  18552. sqlite3_mutex_leave(mem0.mutex);
  18553. p = sqlite3GlobalConfig.m.xMalloc(n);
  18554. }
  18555. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  18556. }
  18557. assert( sqlite3_mutex_notheld(mem0.mutex) );
  18558. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18559. /* Verify that no more than two scratch allocations per thread
  18560. ** are outstanding at one time. (This is only checked in the
  18561. ** single-threaded case since checking in the multi-threaded case
  18562. ** would be much more complicated.) */
  18563. assert( scratchAllocOut<=1 );
  18564. if( p ) scratchAllocOut++;
  18565. #endif
  18566. return p;
  18567. }
  18568. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  18569. if( p ){
  18570. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18571. /* Verify that no more than two scratch allocation per thread
  18572. ** is outstanding at one time. (This is only checked in the
  18573. ** single-threaded case since checking in the multi-threaded case
  18574. ** would be much more complicated.) */
  18575. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  18576. scratchAllocOut--;
  18577. #endif
  18578. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  18579. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  18580. ScratchFreeslot *pSlot;
  18581. pSlot = (ScratchFreeslot*)p;
  18582. sqlite3_mutex_enter(mem0.mutex);
  18583. pSlot->pNext = mem0.pScratchFree;
  18584. mem0.pScratchFree = pSlot;
  18585. mem0.nScratchFree++;
  18586. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  18587. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  18588. sqlite3_mutex_leave(mem0.mutex);
  18589. }else{
  18590. /* Release memory back to the heap */
  18591. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  18592. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  18593. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18594. if( sqlite3GlobalConfig.bMemstat ){
  18595. int iSize = sqlite3MallocSize(p);
  18596. sqlite3_mutex_enter(mem0.mutex);
  18597. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  18598. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  18599. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18600. sqlite3GlobalConfig.m.xFree(p);
  18601. sqlite3_mutex_leave(mem0.mutex);
  18602. }else{
  18603. sqlite3GlobalConfig.m.xFree(p);
  18604. }
  18605. }
  18606. }
  18607. }
  18608. /*
  18609. ** TRUE if p is a lookaside memory allocation from db
  18610. */
  18611. #ifndef SQLITE_OMIT_LOOKASIDE
  18612. static int isLookaside(sqlite3 *db, void *p){
  18613. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18614. }
  18615. #else
  18616. #define isLookaside(A,B) 0
  18617. #endif
  18618. /*
  18619. ** Return the size of a memory allocation previously obtained from
  18620. ** sqlite3Malloc() or sqlite3_malloc().
  18621. */
  18622. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18623. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18624. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18625. return sqlite3GlobalConfig.m.xSize(p);
  18626. }
  18627. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18628. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18629. if( db && isLookaside(db, p) ){
  18630. return db->lookaside.sz;
  18631. }else{
  18632. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18633. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18634. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18635. return sqlite3GlobalConfig.m.xSize(p);
  18636. }
  18637. }
  18638. /*
  18639. ** Free memory previously obtained from sqlite3Malloc().
  18640. */
  18641. SQLITE_API void sqlite3_free(void *p){
  18642. if( p==0 ) return; /* IMP: R-49053-54554 */
  18643. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18644. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18645. if( sqlite3GlobalConfig.bMemstat ){
  18646. sqlite3_mutex_enter(mem0.mutex);
  18647. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18648. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18649. sqlite3GlobalConfig.m.xFree(p);
  18650. sqlite3_mutex_leave(mem0.mutex);
  18651. }else{
  18652. sqlite3GlobalConfig.m.xFree(p);
  18653. }
  18654. }
  18655. /*
  18656. ** Free memory that might be associated with a particular database
  18657. ** connection.
  18658. */
  18659. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18660. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18661. if( p==0 ) return;
  18662. if( db ){
  18663. if( db->pnBytesFreed ){
  18664. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18665. return;
  18666. }
  18667. if( isLookaside(db, p) ){
  18668. LookasideSlot *pBuf = (LookasideSlot*)p;
  18669. #if SQLITE_DEBUG
  18670. /* Trash all content in the buffer being freed */
  18671. memset(p, 0xaa, db->lookaside.sz);
  18672. #endif
  18673. pBuf->pNext = db->lookaside.pFree;
  18674. db->lookaside.pFree = pBuf;
  18675. db->lookaside.nOut--;
  18676. return;
  18677. }
  18678. }
  18679. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18680. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18681. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18682. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18683. sqlite3_free(p);
  18684. }
  18685. /*
  18686. ** Change the size of an existing memory allocation
  18687. */
  18688. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18689. int nOld, nNew, nDiff;
  18690. void *pNew;
  18691. if( pOld==0 ){
  18692. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18693. }
  18694. if( nBytes<=0 ){
  18695. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18696. return 0;
  18697. }
  18698. if( nBytes>=0x7fffff00 ){
  18699. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18700. return 0;
  18701. }
  18702. nOld = sqlite3MallocSize(pOld);
  18703. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18704. ** argument to xRealloc is always a value returned by a prior call to
  18705. ** xRoundup. */
  18706. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18707. if( nOld==nNew ){
  18708. pNew = pOld;
  18709. }else if( sqlite3GlobalConfig.bMemstat ){
  18710. sqlite3_mutex_enter(mem0.mutex);
  18711. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18712. nDiff = nNew - nOld;
  18713. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18714. mem0.alarmThreshold-nDiff ){
  18715. sqlite3MallocAlarm(nDiff);
  18716. }
  18717. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18718. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18719. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18720. if( pNew==0 && mem0.alarmCallback ){
  18721. sqlite3MallocAlarm(nBytes);
  18722. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18723. }
  18724. if( pNew ){
  18725. nNew = sqlite3MallocSize(pNew);
  18726. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18727. }
  18728. sqlite3_mutex_leave(mem0.mutex);
  18729. }else{
  18730. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18731. }
  18732. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18733. return pNew;
  18734. }
  18735. /*
  18736. ** The public interface to sqlite3Realloc. Make sure that the memory
  18737. ** subsystem is initialized prior to invoking sqliteRealloc.
  18738. */
  18739. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18740. #ifndef SQLITE_OMIT_AUTOINIT
  18741. if( sqlite3_initialize() ) return 0;
  18742. #endif
  18743. return sqlite3Realloc(pOld, n);
  18744. }
  18745. /*
  18746. ** Allocate and zero memory.
  18747. */
  18748. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18749. void *p = sqlite3Malloc(n);
  18750. if( p ){
  18751. memset(p, 0, n);
  18752. }
  18753. return p;
  18754. }
  18755. /*
  18756. ** Allocate and zero memory. If the allocation fails, make
  18757. ** the mallocFailed flag in the connection pointer.
  18758. */
  18759. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18760. void *p = sqlite3DbMallocRaw(db, n);
  18761. if( p ){
  18762. memset(p, 0, n);
  18763. }
  18764. return p;
  18765. }
  18766. /*
  18767. ** Allocate and zero memory. If the allocation fails, make
  18768. ** the mallocFailed flag in the connection pointer.
  18769. **
  18770. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18771. ** failure on the same database connection) then always return 0.
  18772. ** Hence for a particular database connection, once malloc starts
  18773. ** failing, it fails consistently until mallocFailed is reset.
  18774. ** This is an important assumption. There are many places in the
  18775. ** code that do things like this:
  18776. **
  18777. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18778. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18779. ** if( b ) a[10] = 9;
  18780. **
  18781. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18782. ** that all prior mallocs (ex: "a") worked too.
  18783. */
  18784. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18785. void *p;
  18786. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18787. assert( db==0 || db->pnBytesFreed==0 );
  18788. #ifndef SQLITE_OMIT_LOOKASIDE
  18789. if( db ){
  18790. LookasideSlot *pBuf;
  18791. if( db->mallocFailed ){
  18792. return 0;
  18793. }
  18794. if( db->lookaside.bEnabled ){
  18795. if( n>db->lookaside.sz ){
  18796. db->lookaside.anStat[1]++;
  18797. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18798. db->lookaside.anStat[2]++;
  18799. }else{
  18800. db->lookaside.pFree = pBuf->pNext;
  18801. db->lookaside.nOut++;
  18802. db->lookaside.anStat[0]++;
  18803. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18804. db->lookaside.mxOut = db->lookaside.nOut;
  18805. }
  18806. return (void*)pBuf;
  18807. }
  18808. }
  18809. }
  18810. #else
  18811. if( db && db->mallocFailed ){
  18812. return 0;
  18813. }
  18814. #endif
  18815. p = sqlite3Malloc(n);
  18816. if( !p && db ){
  18817. db->mallocFailed = 1;
  18818. }
  18819. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18820. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18821. return p;
  18822. }
  18823. /*
  18824. ** Resize the block of memory pointed to by p to n bytes. If the
  18825. ** resize fails, set the mallocFailed flag in the connection object.
  18826. */
  18827. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18828. void *pNew = 0;
  18829. assert( db!=0 );
  18830. assert( sqlite3_mutex_held(db->mutex) );
  18831. if( db->mallocFailed==0 ){
  18832. if( p==0 ){
  18833. return sqlite3DbMallocRaw(db, n);
  18834. }
  18835. if( isLookaside(db, p) ){
  18836. if( n<=db->lookaside.sz ){
  18837. return p;
  18838. }
  18839. pNew = sqlite3DbMallocRaw(db, n);
  18840. if( pNew ){
  18841. memcpy(pNew, p, db->lookaside.sz);
  18842. sqlite3DbFree(db, p);
  18843. }
  18844. }else{
  18845. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18846. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18847. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18848. pNew = sqlite3_realloc(p, n);
  18849. if( !pNew ){
  18850. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18851. db->mallocFailed = 1;
  18852. }
  18853. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18854. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18855. }
  18856. }
  18857. return pNew;
  18858. }
  18859. /*
  18860. ** Attempt to reallocate p. If the reallocation fails, then free p
  18861. ** and set the mallocFailed flag in the database connection.
  18862. */
  18863. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18864. void *pNew;
  18865. pNew = sqlite3DbRealloc(db, p, n);
  18866. if( !pNew ){
  18867. sqlite3DbFree(db, p);
  18868. }
  18869. return pNew;
  18870. }
  18871. /*
  18872. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18873. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18874. ** is because when memory debugging is turned on, these two functions are
  18875. ** called via macros that record the current file and line number in the
  18876. ** ThreadData structure.
  18877. */
  18878. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18879. char *zNew;
  18880. size_t n;
  18881. if( z==0 ){
  18882. return 0;
  18883. }
  18884. n = sqlite3Strlen30(z) + 1;
  18885. assert( (n&0x7fffffff)==n );
  18886. zNew = sqlite3DbMallocRaw(db, (int)n);
  18887. if( zNew ){
  18888. memcpy(zNew, z, n);
  18889. }
  18890. return zNew;
  18891. }
  18892. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18893. char *zNew;
  18894. if( z==0 ){
  18895. return 0;
  18896. }
  18897. assert( (n&0x7fffffff)==n );
  18898. zNew = sqlite3DbMallocRaw(db, n+1);
  18899. if( zNew ){
  18900. memcpy(zNew, z, n);
  18901. zNew[n] = 0;
  18902. }
  18903. return zNew;
  18904. }
  18905. /*
  18906. ** Create a string from the zFromat argument and the va_list that follows.
  18907. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18908. ** point to that string.
  18909. */
  18910. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18911. va_list ap;
  18912. char *z;
  18913. va_start(ap, zFormat);
  18914. z = sqlite3VMPrintf(db, zFormat, ap);
  18915. va_end(ap);
  18916. sqlite3DbFree(db, *pz);
  18917. *pz = z;
  18918. }
  18919. /*
  18920. ** This function must be called before exiting any API function (i.e.
  18921. ** returning control to the user) that has called sqlite3_malloc or
  18922. ** sqlite3_realloc.
  18923. **
  18924. ** The returned value is normally a copy of the second argument to this
  18925. ** function. However, if a malloc() failure has occurred since the previous
  18926. ** invocation SQLITE_NOMEM is returned instead.
  18927. **
  18928. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18929. ** then the connection error-code (the value returned by sqlite3_errcode())
  18930. ** is set to SQLITE_NOMEM.
  18931. */
  18932. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18933. /* If the db handle is not NULL, then we must hold the connection handle
  18934. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18935. ** is unsafe, as is the call to sqlite3Error().
  18936. */
  18937. assert( !db || sqlite3_mutex_held(db->mutex) );
  18938. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18939. sqlite3Error(db, SQLITE_NOMEM, 0);
  18940. db->mallocFailed = 0;
  18941. rc = SQLITE_NOMEM;
  18942. }
  18943. return rc & (db ? db->errMask : 0xff);
  18944. }
  18945. /************** End of malloc.c **********************************************/
  18946. /************** Begin file printf.c ******************************************/
  18947. /*
  18948. ** The "printf" code that follows dates from the 1980's. It is in
  18949. ** the public domain. The original comments are included here for
  18950. ** completeness. They are very out-of-date but might be useful as
  18951. ** an historical reference. Most of the "enhancements" have been backed
  18952. ** out so that the functionality is now the same as standard printf().
  18953. **
  18954. **************************************************************************
  18955. **
  18956. ** This file contains code for a set of "printf"-like routines. These
  18957. ** routines format strings much like the printf() from the standard C
  18958. ** library, though the implementation here has enhancements to support
  18959. ** SQLlite.
  18960. */
  18961. /*
  18962. ** Conversion types fall into various categories as defined by the
  18963. ** following enumeration.
  18964. */
  18965. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18966. #define etFLOAT 2 /* Floating point. %f */
  18967. #define etEXP 3 /* Exponentional notation. %e and %E */
  18968. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18969. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18970. #define etSTRING 6 /* Strings. %s */
  18971. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18972. #define etPERCENT 8 /* Percent symbol. %% */
  18973. #define etCHARX 9 /* Characters. %c */
  18974. /* The rest are extensions, not normally found in printf() */
  18975. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18976. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18977. NULL pointers replaced by SQL NULL. %Q */
  18978. #define etTOKEN 12 /* a pointer to a Token structure */
  18979. #define etSRCLIST 13 /* a pointer to a SrcList */
  18980. #define etPOINTER 14 /* The %p conversion */
  18981. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18982. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18983. #define etINVALID 0 /* Any unrecognized conversion type */
  18984. /*
  18985. ** An "etByte" is an 8-bit unsigned value.
  18986. */
  18987. typedef unsigned char etByte;
  18988. /*
  18989. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18990. ** by an instance of the following structure
  18991. */
  18992. typedef struct et_info { /* Information about each format field */
  18993. char fmttype; /* The format field code letter */
  18994. etByte base; /* The base for radix conversion */
  18995. etByte flags; /* One or more of FLAG_ constants below */
  18996. etByte type; /* Conversion paradigm */
  18997. etByte charset; /* Offset into aDigits[] of the digits string */
  18998. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18999. } et_info;
  19000. /*
  19001. ** Allowed values for et_info.flags
  19002. */
  19003. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  19004. #define FLAG_INTERN 2 /* True if for internal use only */
  19005. #define FLAG_STRING 4 /* Allow infinity precision */
  19006. /*
  19007. ** The following table is searched linearly, so it is good to put the
  19008. ** most frequently used conversion types first.
  19009. */
  19010. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  19011. static const char aPrefix[] = "-x0\000X0";
  19012. static const et_info fmtinfo[] = {
  19013. { 'd', 10, 1, etRADIX, 0, 0 },
  19014. { 's', 0, 4, etSTRING, 0, 0 },
  19015. { 'g', 0, 1, etGENERIC, 30, 0 },
  19016. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  19017. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  19018. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  19019. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  19020. { 'c', 0, 0, etCHARX, 0, 0 },
  19021. { 'o', 8, 0, etRADIX, 0, 2 },
  19022. { 'u', 10, 0, etRADIX, 0, 0 },
  19023. { 'x', 16, 0, etRADIX, 16, 1 },
  19024. { 'X', 16, 0, etRADIX, 0, 4 },
  19025. #ifndef SQLITE_OMIT_FLOATING_POINT
  19026. { 'f', 0, 1, etFLOAT, 0, 0 },
  19027. { 'e', 0, 1, etEXP, 30, 0 },
  19028. { 'E', 0, 1, etEXP, 14, 0 },
  19029. { 'G', 0, 1, etGENERIC, 14, 0 },
  19030. #endif
  19031. { 'i', 10, 1, etRADIX, 0, 0 },
  19032. { 'n', 0, 0, etSIZE, 0, 0 },
  19033. { '%', 0, 0, etPERCENT, 0, 0 },
  19034. { 'p', 16, 0, etPOINTER, 0, 1 },
  19035. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  19036. ** use only */
  19037. { 'T', 0, 2, etTOKEN, 0, 0 },
  19038. { 'S', 0, 2, etSRCLIST, 0, 0 },
  19039. { 'r', 10, 3, etORDINAL, 0, 0 },
  19040. };
  19041. /*
  19042. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  19043. ** conversions will work.
  19044. */
  19045. #ifndef SQLITE_OMIT_FLOATING_POINT
  19046. /*
  19047. ** "*val" is a double such that 0.1 <= *val < 10.0
  19048. ** Return the ascii code for the leading digit of *val, then
  19049. ** multiply "*val" by 10.0 to renormalize.
  19050. **
  19051. ** Example:
  19052. ** input: *val = 3.14159
  19053. ** output: *val = 1.4159 function return = '3'
  19054. **
  19055. ** The counter *cnt is incremented each time. After counter exceeds
  19056. ** 16 (the number of significant digits in a 64-bit float) '0' is
  19057. ** always returned.
  19058. */
  19059. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  19060. int digit;
  19061. LONGDOUBLE_TYPE d;
  19062. if( (*cnt)<=0 ) return '0';
  19063. (*cnt)--;
  19064. digit = (int)*val;
  19065. d = digit;
  19066. digit += '0';
  19067. *val = (*val - d)*10.0;
  19068. return (char)digit;
  19069. }
  19070. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19071. /*
  19072. ** Append N space characters to the given string buffer.
  19073. */
  19074. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  19075. static const char zSpaces[] = " ";
  19076. while( N>=(int)sizeof(zSpaces)-1 ){
  19077. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  19078. N -= sizeof(zSpaces)-1;
  19079. }
  19080. if( N>0 ){
  19081. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  19082. }
  19083. }
  19084. /*
  19085. ** On machines with a small stack size, you can redefine the
  19086. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  19087. */
  19088. #ifndef SQLITE_PRINT_BUF_SIZE
  19089. # define SQLITE_PRINT_BUF_SIZE 70
  19090. #endif
  19091. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  19092. /*
  19093. ** Render a string given by "fmt" into the StrAccum object.
  19094. */
  19095. SQLITE_PRIVATE void sqlite3VXPrintf(
  19096. StrAccum *pAccum, /* Accumulate results here */
  19097. int useExtended, /* Allow extended %-conversions */
  19098. const char *fmt, /* Format string */
  19099. va_list ap /* arguments */
  19100. ){
  19101. int c; /* Next character in the format string */
  19102. char *bufpt; /* Pointer to the conversion buffer */
  19103. int precision; /* Precision of the current field */
  19104. int length; /* Length of the field */
  19105. int idx; /* A general purpose loop counter */
  19106. int width; /* Width of the current field */
  19107. etByte flag_leftjustify; /* True if "-" flag is present */
  19108. etByte flag_plussign; /* True if "+" flag is present */
  19109. etByte flag_blanksign; /* True if " " flag is present */
  19110. etByte flag_alternateform; /* True if "#" flag is present */
  19111. etByte flag_altform2; /* True if "!" flag is present */
  19112. etByte flag_zeropad; /* True if field width constant starts with zero */
  19113. etByte flag_long; /* True if "l" flag is present */
  19114. etByte flag_longlong; /* True if the "ll" flag is present */
  19115. etByte done; /* Loop termination flag */
  19116. etByte xtype = 0; /* Conversion paradigm */
  19117. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  19118. sqlite_uint64 longvalue; /* Value for integer types */
  19119. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  19120. const et_info *infop; /* Pointer to the appropriate info structure */
  19121. char *zOut; /* Rendering buffer */
  19122. int nOut; /* Size of the rendering buffer */
  19123. char *zExtra; /* Malloced memory used by some conversion */
  19124. #ifndef SQLITE_OMIT_FLOATING_POINT
  19125. int exp, e2; /* exponent of real numbers */
  19126. int nsd; /* Number of significant digits returned */
  19127. double rounder; /* Used for rounding floating point values */
  19128. etByte flag_dp; /* True if decimal point should be shown */
  19129. etByte flag_rtz; /* True if trailing zeros should be removed */
  19130. #endif
  19131. char buf[etBUFSIZE]; /* Conversion buffer */
  19132. bufpt = 0;
  19133. for(; (c=(*fmt))!=0; ++fmt){
  19134. if( c!='%' ){
  19135. int amt;
  19136. bufpt = (char *)fmt;
  19137. amt = 1;
  19138. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  19139. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  19140. if( c==0 ) break;
  19141. }
  19142. if( (c=(*++fmt))==0 ){
  19143. sqlite3StrAccumAppend(pAccum, "%", 1);
  19144. break;
  19145. }
  19146. /* Find out what flags are present */
  19147. flag_leftjustify = flag_plussign = flag_blanksign =
  19148. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  19149. done = 0;
  19150. do{
  19151. switch( c ){
  19152. case '-': flag_leftjustify = 1; break;
  19153. case '+': flag_plussign = 1; break;
  19154. case ' ': flag_blanksign = 1; break;
  19155. case '#': flag_alternateform = 1; break;
  19156. case '!': flag_altform2 = 1; break;
  19157. case '0': flag_zeropad = 1; break;
  19158. default: done = 1; break;
  19159. }
  19160. }while( !done && (c=(*++fmt))!=0 );
  19161. /* Get the field width */
  19162. width = 0;
  19163. if( c=='*' ){
  19164. width = va_arg(ap,int);
  19165. if( width<0 ){
  19166. flag_leftjustify = 1;
  19167. width = -width;
  19168. }
  19169. c = *++fmt;
  19170. }else{
  19171. while( c>='0' && c<='9' ){
  19172. width = width*10 + c - '0';
  19173. c = *++fmt;
  19174. }
  19175. }
  19176. /* Get the precision */
  19177. if( c=='.' ){
  19178. precision = 0;
  19179. c = *++fmt;
  19180. if( c=='*' ){
  19181. precision = va_arg(ap,int);
  19182. if( precision<0 ) precision = -precision;
  19183. c = *++fmt;
  19184. }else{
  19185. while( c>='0' && c<='9' ){
  19186. precision = precision*10 + c - '0';
  19187. c = *++fmt;
  19188. }
  19189. }
  19190. }else{
  19191. precision = -1;
  19192. }
  19193. /* Get the conversion type modifier */
  19194. if( c=='l' ){
  19195. flag_long = 1;
  19196. c = *++fmt;
  19197. if( c=='l' ){
  19198. flag_longlong = 1;
  19199. c = *++fmt;
  19200. }else{
  19201. flag_longlong = 0;
  19202. }
  19203. }else{
  19204. flag_long = flag_longlong = 0;
  19205. }
  19206. /* Fetch the info entry for the field */
  19207. infop = &fmtinfo[0];
  19208. xtype = etINVALID;
  19209. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  19210. if( c==fmtinfo[idx].fmttype ){
  19211. infop = &fmtinfo[idx];
  19212. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  19213. xtype = infop->type;
  19214. }else{
  19215. return;
  19216. }
  19217. break;
  19218. }
  19219. }
  19220. zExtra = 0;
  19221. /*
  19222. ** At this point, variables are initialized as follows:
  19223. **
  19224. ** flag_alternateform TRUE if a '#' is present.
  19225. ** flag_altform2 TRUE if a '!' is present.
  19226. ** flag_plussign TRUE if a '+' is present.
  19227. ** flag_leftjustify TRUE if a '-' is present or if the
  19228. ** field width was negative.
  19229. ** flag_zeropad TRUE if the width began with 0.
  19230. ** flag_long TRUE if the letter 'l' (ell) prefixed
  19231. ** the conversion character.
  19232. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  19233. ** the conversion character.
  19234. ** flag_blanksign TRUE if a ' ' is present.
  19235. ** width The specified field width. This is
  19236. ** always non-negative. Zero is the default.
  19237. ** precision The specified precision. The default
  19238. ** is -1.
  19239. ** xtype The class of the conversion.
  19240. ** infop Pointer to the appropriate info struct.
  19241. */
  19242. switch( xtype ){
  19243. case etPOINTER:
  19244. flag_longlong = sizeof(char*)==sizeof(i64);
  19245. flag_long = sizeof(char*)==sizeof(long int);
  19246. /* Fall through into the next case */
  19247. case etORDINAL:
  19248. case etRADIX:
  19249. if( infop->flags & FLAG_SIGNED ){
  19250. i64 v;
  19251. if( flag_longlong ){
  19252. v = va_arg(ap,i64);
  19253. }else if( flag_long ){
  19254. v = va_arg(ap,long int);
  19255. }else{
  19256. v = va_arg(ap,int);
  19257. }
  19258. if( v<0 ){
  19259. if( v==SMALLEST_INT64 ){
  19260. longvalue = ((u64)1)<<63;
  19261. }else{
  19262. longvalue = -v;
  19263. }
  19264. prefix = '-';
  19265. }else{
  19266. longvalue = v;
  19267. if( flag_plussign ) prefix = '+';
  19268. else if( flag_blanksign ) prefix = ' ';
  19269. else prefix = 0;
  19270. }
  19271. }else{
  19272. if( flag_longlong ){
  19273. longvalue = va_arg(ap,u64);
  19274. }else if( flag_long ){
  19275. longvalue = va_arg(ap,unsigned long int);
  19276. }else{
  19277. longvalue = va_arg(ap,unsigned int);
  19278. }
  19279. prefix = 0;
  19280. }
  19281. if( longvalue==0 ) flag_alternateform = 0;
  19282. if( flag_zeropad && precision<width-(prefix!=0) ){
  19283. precision = width-(prefix!=0);
  19284. }
  19285. if( precision<etBUFSIZE-10 ){
  19286. nOut = etBUFSIZE;
  19287. zOut = buf;
  19288. }else{
  19289. nOut = precision + 10;
  19290. zOut = zExtra = sqlite3Malloc( nOut );
  19291. if( zOut==0 ){
  19292. pAccum->accError = STRACCUM_NOMEM;
  19293. return;
  19294. }
  19295. }
  19296. bufpt = &zOut[nOut-1];
  19297. if( xtype==etORDINAL ){
  19298. static const char zOrd[] = "thstndrd";
  19299. int x = (int)(longvalue % 10);
  19300. if( x>=4 || (longvalue/10)%10==1 ){
  19301. x = 0;
  19302. }
  19303. *(--bufpt) = zOrd[x*2+1];
  19304. *(--bufpt) = zOrd[x*2];
  19305. }
  19306. {
  19307. register const char *cset; /* Use registers for speed */
  19308. register int base;
  19309. cset = &aDigits[infop->charset];
  19310. base = infop->base;
  19311. do{ /* Convert to ascii */
  19312. *(--bufpt) = cset[longvalue%base];
  19313. longvalue = longvalue/base;
  19314. }while( longvalue>0 );
  19315. }
  19316. length = (int)(&zOut[nOut-1]-bufpt);
  19317. for(idx=precision-length; idx>0; idx--){
  19318. *(--bufpt) = '0'; /* Zero pad */
  19319. }
  19320. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  19321. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  19322. const char *pre;
  19323. char x;
  19324. pre = &aPrefix[infop->prefix];
  19325. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  19326. }
  19327. length = (int)(&zOut[nOut-1]-bufpt);
  19328. break;
  19329. case etFLOAT:
  19330. case etEXP:
  19331. case etGENERIC:
  19332. realvalue = va_arg(ap,double);
  19333. #ifdef SQLITE_OMIT_FLOATING_POINT
  19334. length = 0;
  19335. #else
  19336. if( precision<0 ) precision = 6; /* Set default precision */
  19337. if( realvalue<0.0 ){
  19338. realvalue = -realvalue;
  19339. prefix = '-';
  19340. }else{
  19341. if( flag_plussign ) prefix = '+';
  19342. else if( flag_blanksign ) prefix = ' ';
  19343. else prefix = 0;
  19344. }
  19345. if( xtype==etGENERIC && precision>0 ) precision--;
  19346. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  19347. if( xtype==etFLOAT ) realvalue += rounder;
  19348. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  19349. exp = 0;
  19350. if( sqlite3IsNaN((double)realvalue) ){
  19351. bufpt = "NaN";
  19352. length = 3;
  19353. break;
  19354. }
  19355. if( realvalue>0.0 ){
  19356. LONGDOUBLE_TYPE scale = 1.0;
  19357. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  19358. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  19359. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  19360. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  19361. realvalue /= scale;
  19362. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  19363. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  19364. if( exp>350 ){
  19365. if( prefix=='-' ){
  19366. bufpt = "-Inf";
  19367. }else if( prefix=='+' ){
  19368. bufpt = "+Inf";
  19369. }else{
  19370. bufpt = "Inf";
  19371. }
  19372. length = sqlite3Strlen30(bufpt);
  19373. break;
  19374. }
  19375. }
  19376. bufpt = buf;
  19377. /*
  19378. ** If the field type is etGENERIC, then convert to either etEXP
  19379. ** or etFLOAT, as appropriate.
  19380. */
  19381. if( xtype!=etFLOAT ){
  19382. realvalue += rounder;
  19383. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  19384. }
  19385. if( xtype==etGENERIC ){
  19386. flag_rtz = !flag_alternateform;
  19387. if( exp<-4 || exp>precision ){
  19388. xtype = etEXP;
  19389. }else{
  19390. precision = precision - exp;
  19391. xtype = etFLOAT;
  19392. }
  19393. }else{
  19394. flag_rtz = flag_altform2;
  19395. }
  19396. if( xtype==etEXP ){
  19397. e2 = 0;
  19398. }else{
  19399. e2 = exp;
  19400. }
  19401. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  19402. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  19403. if( bufpt==0 ){
  19404. pAccum->accError = STRACCUM_NOMEM;
  19405. return;
  19406. }
  19407. }
  19408. zOut = bufpt;
  19409. nsd = 16 + flag_altform2*10;
  19410. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  19411. /* The sign in front of the number */
  19412. if( prefix ){
  19413. *(bufpt++) = prefix;
  19414. }
  19415. /* Digits prior to the decimal point */
  19416. if( e2<0 ){
  19417. *(bufpt++) = '0';
  19418. }else{
  19419. for(; e2>=0; e2--){
  19420. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19421. }
  19422. }
  19423. /* The decimal point */
  19424. if( flag_dp ){
  19425. *(bufpt++) = '.';
  19426. }
  19427. /* "0" digits after the decimal point but before the first
  19428. ** significant digit of the number */
  19429. for(e2++; e2<0; precision--, e2++){
  19430. assert( precision>0 );
  19431. *(bufpt++) = '0';
  19432. }
  19433. /* Significant digits after the decimal point */
  19434. while( (precision--)>0 ){
  19435. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19436. }
  19437. /* Remove trailing zeros and the "." if no digits follow the "." */
  19438. if( flag_rtz && flag_dp ){
  19439. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  19440. assert( bufpt>zOut );
  19441. if( bufpt[-1]=='.' ){
  19442. if( flag_altform2 ){
  19443. *(bufpt++) = '0';
  19444. }else{
  19445. *(--bufpt) = 0;
  19446. }
  19447. }
  19448. }
  19449. /* Add the "eNNN" suffix */
  19450. if( xtype==etEXP ){
  19451. *(bufpt++) = aDigits[infop->charset];
  19452. if( exp<0 ){
  19453. *(bufpt++) = '-'; exp = -exp;
  19454. }else{
  19455. *(bufpt++) = '+';
  19456. }
  19457. if( exp>=100 ){
  19458. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  19459. exp %= 100;
  19460. }
  19461. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  19462. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  19463. }
  19464. *bufpt = 0;
  19465. /* The converted number is in buf[] and zero terminated. Output it.
  19466. ** Note that the number is in the usual order, not reversed as with
  19467. ** integer conversions. */
  19468. length = (int)(bufpt-zOut);
  19469. bufpt = zOut;
  19470. /* Special case: Add leading zeros if the flag_zeropad flag is
  19471. ** set and we are not left justified */
  19472. if( flag_zeropad && !flag_leftjustify && length < width){
  19473. int i;
  19474. int nPad = width - length;
  19475. for(i=width; i>=nPad; i--){
  19476. bufpt[i] = bufpt[i-nPad];
  19477. }
  19478. i = prefix!=0;
  19479. while( nPad-- ) bufpt[i++] = '0';
  19480. length = width;
  19481. }
  19482. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  19483. break;
  19484. case etSIZE:
  19485. *(va_arg(ap,int*)) = pAccum->nChar;
  19486. length = width = 0;
  19487. break;
  19488. case etPERCENT:
  19489. buf[0] = '%';
  19490. bufpt = buf;
  19491. length = 1;
  19492. break;
  19493. case etCHARX:
  19494. c = va_arg(ap,int);
  19495. buf[0] = (char)c;
  19496. if( precision>=0 ){
  19497. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  19498. length = precision;
  19499. }else{
  19500. length =1;
  19501. }
  19502. bufpt = buf;
  19503. break;
  19504. case etSTRING:
  19505. case etDYNSTRING:
  19506. bufpt = va_arg(ap,char*);
  19507. if( bufpt==0 ){
  19508. bufpt = "";
  19509. }else if( xtype==etDYNSTRING ){
  19510. zExtra = bufpt;
  19511. }
  19512. if( precision>=0 ){
  19513. for(length=0; length<precision && bufpt[length]; length++){}
  19514. }else{
  19515. length = sqlite3Strlen30(bufpt);
  19516. }
  19517. break;
  19518. case etSQLESCAPE:
  19519. case etSQLESCAPE2:
  19520. case etSQLESCAPE3: {
  19521. int i, j, k, n, isnull;
  19522. int needQuote;
  19523. char ch;
  19524. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  19525. char *escarg = va_arg(ap,char*);
  19526. isnull = escarg==0;
  19527. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  19528. k = precision;
  19529. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  19530. if( ch==q ) n++;
  19531. }
  19532. needQuote = !isnull && xtype==etSQLESCAPE2;
  19533. n += i + 1 + needQuote*2;
  19534. if( n>etBUFSIZE ){
  19535. bufpt = zExtra = sqlite3Malloc( n );
  19536. if( bufpt==0 ){
  19537. pAccum->accError = STRACCUM_NOMEM;
  19538. return;
  19539. }
  19540. }else{
  19541. bufpt = buf;
  19542. }
  19543. j = 0;
  19544. if( needQuote ) bufpt[j++] = q;
  19545. k = i;
  19546. for(i=0; i<k; i++){
  19547. bufpt[j++] = ch = escarg[i];
  19548. if( ch==q ) bufpt[j++] = ch;
  19549. }
  19550. if( needQuote ) bufpt[j++] = q;
  19551. bufpt[j] = 0;
  19552. length = j;
  19553. /* The precision in %q and %Q means how many input characters to
  19554. ** consume, not the length of the output...
  19555. ** if( precision>=0 && precision<length ) length = precision; */
  19556. break;
  19557. }
  19558. case etTOKEN: {
  19559. Token *pToken = va_arg(ap, Token*);
  19560. if( pToken ){
  19561. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  19562. }
  19563. length = width = 0;
  19564. break;
  19565. }
  19566. case etSRCLIST: {
  19567. SrcList *pSrc = va_arg(ap, SrcList*);
  19568. int k = va_arg(ap, int);
  19569. struct SrcList_item *pItem = &pSrc->a[k];
  19570. assert( k>=0 && k<pSrc->nSrc );
  19571. if( pItem->zDatabase ){
  19572. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  19573. sqlite3StrAccumAppend(pAccum, ".", 1);
  19574. }
  19575. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  19576. length = width = 0;
  19577. break;
  19578. }
  19579. default: {
  19580. assert( xtype==etINVALID );
  19581. return;
  19582. }
  19583. }/* End switch over the format type */
  19584. /*
  19585. ** The text of the conversion is pointed to by "bufpt" and is
  19586. ** "length" characters long. The field width is "width". Do
  19587. ** the output.
  19588. */
  19589. if( !flag_leftjustify ){
  19590. register int nspace;
  19591. nspace = width-length;
  19592. if( nspace>0 ){
  19593. sqlite3AppendSpace(pAccum, nspace);
  19594. }
  19595. }
  19596. if( length>0 ){
  19597. sqlite3StrAccumAppend(pAccum, bufpt, length);
  19598. }
  19599. if( flag_leftjustify ){
  19600. register int nspace;
  19601. nspace = width-length;
  19602. if( nspace>0 ){
  19603. sqlite3AppendSpace(pAccum, nspace);
  19604. }
  19605. }
  19606. sqlite3_free(zExtra);
  19607. }/* End for loop over the format string */
  19608. } /* End of function */
  19609. /*
  19610. ** Append N bytes of text from z to the StrAccum object.
  19611. */
  19612. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19613. assert( z!=0 || N==0 );
  19614. if( p->accError ){
  19615. testcase(p->accError==STRACCUM_TOOBIG);
  19616. testcase(p->accError==STRACCUM_NOMEM);
  19617. return;
  19618. }
  19619. assert( p->zText!=0 || p->nChar==0 );
  19620. if( N<=0 ){
  19621. if( N==0 || z[0]==0 ) return;
  19622. N = sqlite3Strlen30(z);
  19623. }
  19624. if( p->nChar+N >= p->nAlloc ){
  19625. char *zNew;
  19626. if( !p->useMalloc ){
  19627. p->accError = STRACCUM_TOOBIG;
  19628. N = p->nAlloc - p->nChar - 1;
  19629. if( N<=0 ){
  19630. return;
  19631. }
  19632. }else{
  19633. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19634. i64 szNew = p->nChar;
  19635. szNew += N + 1;
  19636. if( szNew > p->mxAlloc ){
  19637. sqlite3StrAccumReset(p);
  19638. p->accError = STRACCUM_TOOBIG;
  19639. return;
  19640. }else{
  19641. p->nAlloc = (int)szNew;
  19642. }
  19643. if( p->useMalloc==1 ){
  19644. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19645. }else{
  19646. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19647. }
  19648. if( zNew ){
  19649. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19650. p->zText = zNew;
  19651. }else{
  19652. p->accError = STRACCUM_NOMEM;
  19653. sqlite3StrAccumReset(p);
  19654. return;
  19655. }
  19656. }
  19657. }
  19658. assert( p->zText );
  19659. memcpy(&p->zText[p->nChar], z, N);
  19660. p->nChar += N;
  19661. }
  19662. /*
  19663. ** Finish off a string by making sure it is zero-terminated.
  19664. ** Return a pointer to the resulting string. Return a NULL
  19665. ** pointer if any kind of error was encountered.
  19666. */
  19667. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19668. if( p->zText ){
  19669. p->zText[p->nChar] = 0;
  19670. if( p->useMalloc && p->zText==p->zBase ){
  19671. if( p->useMalloc==1 ){
  19672. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19673. }else{
  19674. p->zText = sqlite3_malloc(p->nChar+1);
  19675. }
  19676. if( p->zText ){
  19677. memcpy(p->zText, p->zBase, p->nChar+1);
  19678. }else{
  19679. p->accError = STRACCUM_NOMEM;
  19680. }
  19681. }
  19682. }
  19683. return p->zText;
  19684. }
  19685. /*
  19686. ** Reset an StrAccum string. Reclaim all malloced memory.
  19687. */
  19688. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19689. if( p->zText!=p->zBase ){
  19690. if( p->useMalloc==1 ){
  19691. sqlite3DbFree(p->db, p->zText);
  19692. }else{
  19693. sqlite3_free(p->zText);
  19694. }
  19695. }
  19696. p->zText = 0;
  19697. }
  19698. /*
  19699. ** Initialize a string accumulator
  19700. */
  19701. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19702. p->zText = p->zBase = zBase;
  19703. p->db = 0;
  19704. p->nChar = 0;
  19705. p->nAlloc = n;
  19706. p->mxAlloc = mx;
  19707. p->useMalloc = 1;
  19708. p->accError = 0;
  19709. }
  19710. /*
  19711. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19712. ** %-conversion extensions.
  19713. */
  19714. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19715. char *z;
  19716. char zBase[SQLITE_PRINT_BUF_SIZE];
  19717. StrAccum acc;
  19718. assert( db!=0 );
  19719. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19720. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19721. acc.db = db;
  19722. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19723. z = sqlite3StrAccumFinish(&acc);
  19724. if( acc.accError==STRACCUM_NOMEM ){
  19725. db->mallocFailed = 1;
  19726. }
  19727. return z;
  19728. }
  19729. /*
  19730. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19731. ** %-conversion extensions.
  19732. */
  19733. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19734. va_list ap;
  19735. char *z;
  19736. va_start(ap, zFormat);
  19737. z = sqlite3VMPrintf(db, zFormat, ap);
  19738. va_end(ap);
  19739. return z;
  19740. }
  19741. /*
  19742. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19743. ** the string and before returnning. This routine is intended to be used
  19744. ** to modify an existing string. For example:
  19745. **
  19746. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19747. **
  19748. */
  19749. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19750. va_list ap;
  19751. char *z;
  19752. va_start(ap, zFormat);
  19753. z = sqlite3VMPrintf(db, zFormat, ap);
  19754. va_end(ap);
  19755. sqlite3DbFree(db, zStr);
  19756. return z;
  19757. }
  19758. /*
  19759. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19760. ** %-conversion extensions.
  19761. */
  19762. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19763. char *z;
  19764. char zBase[SQLITE_PRINT_BUF_SIZE];
  19765. StrAccum acc;
  19766. #ifndef SQLITE_OMIT_AUTOINIT
  19767. if( sqlite3_initialize() ) return 0;
  19768. #endif
  19769. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19770. acc.useMalloc = 2;
  19771. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19772. z = sqlite3StrAccumFinish(&acc);
  19773. return z;
  19774. }
  19775. /*
  19776. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19777. ** %-conversion extensions.
  19778. */
  19779. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19780. va_list ap;
  19781. char *z;
  19782. #ifndef SQLITE_OMIT_AUTOINIT
  19783. if( sqlite3_initialize() ) return 0;
  19784. #endif
  19785. va_start(ap, zFormat);
  19786. z = sqlite3_vmprintf(zFormat, ap);
  19787. va_end(ap);
  19788. return z;
  19789. }
  19790. /*
  19791. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19792. ** current locale settings. This is important for SQLite because we
  19793. ** are not able to use a "," as the decimal point in place of "." as
  19794. ** specified by some locales.
  19795. **
  19796. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19797. ** from the snprintf() standard. Unfortunately, it is too late to change
  19798. ** this without breaking compatibility, so we just have to live with the
  19799. ** mistake.
  19800. **
  19801. ** sqlite3_vsnprintf() is the varargs version.
  19802. */
  19803. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19804. StrAccum acc;
  19805. if( n<=0 ) return zBuf;
  19806. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19807. acc.useMalloc = 0;
  19808. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19809. return sqlite3StrAccumFinish(&acc);
  19810. }
  19811. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19812. char *z;
  19813. va_list ap;
  19814. va_start(ap,zFormat);
  19815. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19816. va_end(ap);
  19817. return z;
  19818. }
  19819. /*
  19820. ** This is the routine that actually formats the sqlite3_log() message.
  19821. ** We house it in a separate routine from sqlite3_log() to avoid using
  19822. ** stack space on small-stack systems when logging is disabled.
  19823. **
  19824. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19825. ** allocate memory because it might be called while the memory allocator
  19826. ** mutex is held.
  19827. */
  19828. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19829. StrAccum acc; /* String accumulator */
  19830. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19831. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19832. acc.useMalloc = 0;
  19833. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19834. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19835. sqlite3StrAccumFinish(&acc));
  19836. }
  19837. /*
  19838. ** Format and write a message to the log if logging is enabled.
  19839. */
  19840. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19841. va_list ap; /* Vararg list */
  19842. if( sqlite3GlobalConfig.xLog ){
  19843. va_start(ap, zFormat);
  19844. renderLogMsg(iErrCode, zFormat, ap);
  19845. va_end(ap);
  19846. }
  19847. }
  19848. #if defined(SQLITE_DEBUG)
  19849. /*
  19850. ** A version of printf() that understands %lld. Used for debugging.
  19851. ** The printf() built into some versions of windows does not understand %lld
  19852. ** and segfaults if you give it a long long int.
  19853. */
  19854. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19855. va_list ap;
  19856. StrAccum acc;
  19857. char zBuf[500];
  19858. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19859. acc.useMalloc = 0;
  19860. va_start(ap,zFormat);
  19861. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19862. va_end(ap);
  19863. sqlite3StrAccumFinish(&acc);
  19864. fprintf(stdout,"%s", zBuf);
  19865. fflush(stdout);
  19866. }
  19867. #endif
  19868. #ifndef SQLITE_OMIT_TRACE
  19869. /*
  19870. ** variable-argument wrapper around sqlite3VXPrintf().
  19871. */
  19872. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19873. va_list ap;
  19874. va_start(ap,zFormat);
  19875. sqlite3VXPrintf(p, 1, zFormat, ap);
  19876. va_end(ap);
  19877. }
  19878. #endif
  19879. /************** End of printf.c **********************************************/
  19880. /************** Begin file random.c ******************************************/
  19881. /*
  19882. ** 2001 September 15
  19883. **
  19884. ** The author disclaims copyright to this source code. In place of
  19885. ** a legal notice, here is a blessing:
  19886. **
  19887. ** May you do good and not evil.
  19888. ** May you find forgiveness for yourself and forgive others.
  19889. ** May you share freely, never taking more than you give.
  19890. **
  19891. *************************************************************************
  19892. ** This file contains code to implement a pseudo-random number
  19893. ** generator (PRNG) for SQLite.
  19894. **
  19895. ** Random numbers are used by some of the database backends in order
  19896. ** to generate random integer keys for tables or random filenames.
  19897. */
  19898. /* All threads share a single random number generator.
  19899. ** This structure is the current state of the generator.
  19900. */
  19901. static SQLITE_WSD struct sqlite3PrngType {
  19902. unsigned char isInit; /* True if initialized */
  19903. unsigned char i, j; /* State variables */
  19904. unsigned char s[256]; /* State variables */
  19905. } sqlite3Prng;
  19906. /*
  19907. ** Return N random bytes.
  19908. */
  19909. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19910. unsigned char t;
  19911. unsigned char *zBuf = pBuf;
  19912. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19913. ** state vector. If writable static data is unsupported on the target,
  19914. ** we have to locate the state vector at run-time. In the more common
  19915. ** case where writable static data is supported, wsdPrng can refer directly
  19916. ** to the "sqlite3Prng" state vector declared above.
  19917. */
  19918. #ifdef SQLITE_OMIT_WSD
  19919. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19920. # define wsdPrng p[0]
  19921. #else
  19922. # define wsdPrng sqlite3Prng
  19923. #endif
  19924. #if SQLITE_THREADSAFE
  19925. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19926. sqlite3_mutex_enter(mutex);
  19927. #endif
  19928. /* Initialize the state of the random number generator once,
  19929. ** the first time this routine is called. The seed value does
  19930. ** not need to contain a lot of randomness since we are not
  19931. ** trying to do secure encryption or anything like that...
  19932. **
  19933. ** Nothing in this file or anywhere else in SQLite does any kind of
  19934. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19935. ** number generator) not as an encryption device.
  19936. */
  19937. if( !wsdPrng.isInit ){
  19938. int i;
  19939. char k[256];
  19940. wsdPrng.j = 0;
  19941. wsdPrng.i = 0;
  19942. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19943. for(i=0; i<256; i++){
  19944. wsdPrng.s[i] = (u8)i;
  19945. }
  19946. for(i=0; i<256; i++){
  19947. wsdPrng.j += wsdPrng.s[i] + k[i];
  19948. t = wsdPrng.s[wsdPrng.j];
  19949. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19950. wsdPrng.s[i] = t;
  19951. }
  19952. wsdPrng.isInit = 1;
  19953. }
  19954. while( N-- ){
  19955. wsdPrng.i++;
  19956. t = wsdPrng.s[wsdPrng.i];
  19957. wsdPrng.j += t;
  19958. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19959. wsdPrng.s[wsdPrng.j] = t;
  19960. t += wsdPrng.s[wsdPrng.i];
  19961. *(zBuf++) = wsdPrng.s[t];
  19962. }
  19963. sqlite3_mutex_leave(mutex);
  19964. }
  19965. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19966. /*
  19967. ** For testing purposes, we sometimes want to preserve the state of
  19968. ** PRNG and restore the PRNG to its saved state at a later time, or
  19969. ** to reset the PRNG to its initial state. These routines accomplish
  19970. ** those tasks.
  19971. **
  19972. ** The sqlite3_test_control() interface calls these routines to
  19973. ** control the PRNG.
  19974. */
  19975. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19976. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19977. memcpy(
  19978. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19979. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19980. sizeof(sqlite3Prng)
  19981. );
  19982. }
  19983. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19984. memcpy(
  19985. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19986. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19987. sizeof(sqlite3Prng)
  19988. );
  19989. }
  19990. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19991. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19992. }
  19993. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19994. /************** End of random.c **********************************************/
  19995. /************** Begin file utf.c *********************************************/
  19996. /*
  19997. ** 2004 April 13
  19998. **
  19999. ** The author disclaims copyright to this source code. In place of
  20000. ** a legal notice, here is a blessing:
  20001. **
  20002. ** May you do good and not evil.
  20003. ** May you find forgiveness for yourself and forgive others.
  20004. ** May you share freely, never taking more than you give.
  20005. **
  20006. *************************************************************************
  20007. ** This file contains routines used to translate between UTF-8,
  20008. ** UTF-16, UTF-16BE, and UTF-16LE.
  20009. **
  20010. ** Notes on UTF-8:
  20011. **
  20012. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  20013. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  20014. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  20015. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  20016. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  20017. **
  20018. **
  20019. ** Notes on UTF-16: (with wwww+1==uuuuu)
  20020. **
  20021. ** Word-0 Word-1 Value
  20022. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  20023. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  20024. **
  20025. **
  20026. ** BOM or Byte Order Mark:
  20027. ** 0xff 0xfe little-endian utf-16 follows
  20028. ** 0xfe 0xff big-endian utf-16 follows
  20029. **
  20030. */
  20031. /* #include <assert.h> */
  20032. #ifndef SQLITE_AMALGAMATION
  20033. /*
  20034. ** The following constant value is used by the SQLITE_BIGENDIAN and
  20035. ** SQLITE_LITTLEENDIAN macros.
  20036. */
  20037. SQLITE_PRIVATE const int sqlite3one = 1;
  20038. #endif /* SQLITE_AMALGAMATION */
  20039. /*
  20040. ** This lookup table is used to help decode the first byte of
  20041. ** a multi-byte UTF8 character.
  20042. */
  20043. static const unsigned char sqlite3Utf8Trans1[] = {
  20044. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20045. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  20046. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  20047. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  20048. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20049. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  20050. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20051. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  20052. };
  20053. #define WRITE_UTF8(zOut, c) { \
  20054. if( c<0x00080 ){ \
  20055. *zOut++ = (u8)(c&0xFF); \
  20056. } \
  20057. else if( c<0x00800 ){ \
  20058. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  20059. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20060. } \
  20061. else if( c<0x10000 ){ \
  20062. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  20063. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  20064. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20065. }else{ \
  20066. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  20067. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  20068. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  20069. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20070. } \
  20071. }
  20072. #define WRITE_UTF16LE(zOut, c) { \
  20073. if( c<=0xFFFF ){ \
  20074. *zOut++ = (u8)(c&0x00FF); \
  20075. *zOut++ = (u8)((c>>8)&0x00FF); \
  20076. }else{ \
  20077. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  20078. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  20079. *zOut++ = (u8)(c&0x00FF); \
  20080. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  20081. } \
  20082. }
  20083. #define WRITE_UTF16BE(zOut, c) { \
  20084. if( c<=0xFFFF ){ \
  20085. *zOut++ = (u8)((c>>8)&0x00FF); \
  20086. *zOut++ = (u8)(c&0x00FF); \
  20087. }else{ \
  20088. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  20089. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  20090. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  20091. *zOut++ = (u8)(c&0x00FF); \
  20092. } \
  20093. }
  20094. #define READ_UTF16LE(zIn, TERM, c){ \
  20095. c = (*zIn++); \
  20096. c += ((*zIn++)<<8); \
  20097. if( c>=0xD800 && c<0xE000 && TERM ){ \
  20098. int c2 = (*zIn++); \
  20099. c2 += ((*zIn++)<<8); \
  20100. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  20101. } \
  20102. }
  20103. #define READ_UTF16BE(zIn, TERM, c){ \
  20104. c = ((*zIn++)<<8); \
  20105. c += (*zIn++); \
  20106. if( c>=0xD800 && c<0xE000 && TERM ){ \
  20107. int c2 = ((*zIn++)<<8); \
  20108. c2 += (*zIn++); \
  20109. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  20110. } \
  20111. }
  20112. /*
  20113. ** Translate a single UTF-8 character. Return the unicode value.
  20114. **
  20115. ** During translation, assume that the byte that zTerm points
  20116. ** is a 0x00.
  20117. **
  20118. ** Write a pointer to the next unread byte back into *pzNext.
  20119. **
  20120. ** Notes On Invalid UTF-8:
  20121. **
  20122. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  20123. ** be encoded as a multi-byte character. Any multi-byte character that
  20124. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  20125. **
  20126. ** * This routine never allows a UTF16 surrogate value to be encoded.
  20127. ** If a multi-byte character attempts to encode a value between
  20128. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  20129. **
  20130. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  20131. ** byte of a character are interpreted as single-byte characters
  20132. ** and rendered as themselves even though they are technically
  20133. ** invalid characters.
  20134. **
  20135. ** * This routine accepts an infinite number of different UTF8 encodings
  20136. ** for unicode values 0x80 and greater. It do not change over-length
  20137. ** encodings to 0xfffd as some systems recommend.
  20138. */
  20139. #define READ_UTF8(zIn, zTerm, c) \
  20140. c = *(zIn++); \
  20141. if( c>=0xc0 ){ \
  20142. c = sqlite3Utf8Trans1[c-0xc0]; \
  20143. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  20144. c = (c<<6) + (0x3f & *(zIn++)); \
  20145. } \
  20146. if( c<0x80 \
  20147. || (c&0xFFFFF800)==0xD800 \
  20148. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  20149. }
  20150. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  20151. const unsigned char **pz /* Pointer to string from which to read char */
  20152. ){
  20153. unsigned int c;
  20154. /* Same as READ_UTF8() above but without the zTerm parameter.
  20155. ** For this routine, we assume the UTF8 string is always zero-terminated.
  20156. */
  20157. c = *((*pz)++);
  20158. if( c>=0xc0 ){
  20159. c = sqlite3Utf8Trans1[c-0xc0];
  20160. while( (*(*pz) & 0xc0)==0x80 ){
  20161. c = (c<<6) + (0x3f & *((*pz)++));
  20162. }
  20163. if( c<0x80
  20164. || (c&0xFFFFF800)==0xD800
  20165. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  20166. }
  20167. return c;
  20168. }
  20169. /*
  20170. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  20171. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  20172. */
  20173. /* #define TRANSLATE_TRACE 1 */
  20174. #ifndef SQLITE_OMIT_UTF16
  20175. /*
  20176. ** This routine transforms the internal text encoding used by pMem to
  20177. ** desiredEnc. It is an error if the string is already of the desired
  20178. ** encoding, or if *pMem does not contain a string value.
  20179. */
  20180. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  20181. int len; /* Maximum length of output string in bytes */
  20182. unsigned char *zOut; /* Output buffer */
  20183. unsigned char *zIn; /* Input iterator */
  20184. unsigned char *zTerm; /* End of input */
  20185. unsigned char *z; /* Output iterator */
  20186. unsigned int c;
  20187. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  20188. assert( pMem->flags&MEM_Str );
  20189. assert( pMem->enc!=desiredEnc );
  20190. assert( pMem->enc!=0 );
  20191. assert( pMem->n>=0 );
  20192. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  20193. {
  20194. char zBuf[100];
  20195. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  20196. fprintf(stderr, "INPUT: %s\n", zBuf);
  20197. }
  20198. #endif
  20199. /* If the translation is between UTF-16 little and big endian, then
  20200. ** all that is required is to swap the byte order. This case is handled
  20201. ** differently from the others.
  20202. */
  20203. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  20204. u8 temp;
  20205. int rc;
  20206. rc = sqlite3VdbeMemMakeWriteable(pMem);
  20207. if( rc!=SQLITE_OK ){
  20208. assert( rc==SQLITE_NOMEM );
  20209. return SQLITE_NOMEM;
  20210. }
  20211. zIn = (u8*)pMem->z;
  20212. zTerm = &zIn[pMem->n&~1];
  20213. while( zIn<zTerm ){
  20214. temp = *zIn;
  20215. *zIn = *(zIn+1);
  20216. zIn++;
  20217. *zIn++ = temp;
  20218. }
  20219. pMem->enc = desiredEnc;
  20220. goto translate_out;
  20221. }
  20222. /* Set len to the maximum number of bytes required in the output buffer. */
  20223. if( desiredEnc==SQLITE_UTF8 ){
  20224. /* When converting from UTF-16, the maximum growth results from
  20225. ** translating a 2-byte character to a 4-byte UTF-8 character.
  20226. ** A single byte is required for the output string
  20227. ** nul-terminator.
  20228. */
  20229. pMem->n &= ~1;
  20230. len = pMem->n * 2 + 1;
  20231. }else{
  20232. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  20233. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  20234. ** character. Two bytes are required in the output buffer for the
  20235. ** nul-terminator.
  20236. */
  20237. len = pMem->n * 2 + 2;
  20238. }
  20239. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  20240. ** byte past the end.
  20241. **
  20242. ** Variable zOut is set to point at the output buffer, space obtained
  20243. ** from sqlite3_malloc().
  20244. */
  20245. zIn = (u8*)pMem->z;
  20246. zTerm = &zIn[pMem->n];
  20247. zOut = sqlite3DbMallocRaw(pMem->db, len);
  20248. if( !zOut ){
  20249. return SQLITE_NOMEM;
  20250. }
  20251. z = zOut;
  20252. if( pMem->enc==SQLITE_UTF8 ){
  20253. if( desiredEnc==SQLITE_UTF16LE ){
  20254. /* UTF-8 -> UTF-16 Little-endian */
  20255. while( zIn<zTerm ){
  20256. READ_UTF8(zIn, zTerm, c);
  20257. WRITE_UTF16LE(z, c);
  20258. }
  20259. }else{
  20260. assert( desiredEnc==SQLITE_UTF16BE );
  20261. /* UTF-8 -> UTF-16 Big-endian */
  20262. while( zIn<zTerm ){
  20263. READ_UTF8(zIn, zTerm, c);
  20264. WRITE_UTF16BE(z, c);
  20265. }
  20266. }
  20267. pMem->n = (int)(z - zOut);
  20268. *z++ = 0;
  20269. }else{
  20270. assert( desiredEnc==SQLITE_UTF8 );
  20271. if( pMem->enc==SQLITE_UTF16LE ){
  20272. /* UTF-16 Little-endian -> UTF-8 */
  20273. while( zIn<zTerm ){
  20274. READ_UTF16LE(zIn, zIn<zTerm, c);
  20275. WRITE_UTF8(z, c);
  20276. }
  20277. }else{
  20278. /* UTF-16 Big-endian -> UTF-8 */
  20279. while( zIn<zTerm ){
  20280. READ_UTF16BE(zIn, zIn<zTerm, c);
  20281. WRITE_UTF8(z, c);
  20282. }
  20283. }
  20284. pMem->n = (int)(z - zOut);
  20285. }
  20286. *z = 0;
  20287. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  20288. sqlite3VdbeMemRelease(pMem);
  20289. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  20290. pMem->enc = desiredEnc;
  20291. pMem->flags |= (MEM_Term|MEM_Dyn);
  20292. pMem->z = (char*)zOut;
  20293. pMem->zMalloc = pMem->z;
  20294. translate_out:
  20295. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  20296. {
  20297. char zBuf[100];
  20298. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  20299. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  20300. }
  20301. #endif
  20302. return SQLITE_OK;
  20303. }
  20304. /*
  20305. ** This routine checks for a byte-order mark at the beginning of the
  20306. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  20307. ** the encoding of the Mem adjusted. This routine does not do any
  20308. ** byte-swapping, it just sets Mem.enc appropriately.
  20309. **
  20310. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  20311. ** changed by this function.
  20312. */
  20313. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  20314. int rc = SQLITE_OK;
  20315. u8 bom = 0;
  20316. assert( pMem->n>=0 );
  20317. if( pMem->n>1 ){
  20318. u8 b1 = *(u8 *)pMem->z;
  20319. u8 b2 = *(((u8 *)pMem->z) + 1);
  20320. if( b1==0xFE && b2==0xFF ){
  20321. bom = SQLITE_UTF16BE;
  20322. }
  20323. if( b1==0xFF && b2==0xFE ){
  20324. bom = SQLITE_UTF16LE;
  20325. }
  20326. }
  20327. if( bom ){
  20328. rc = sqlite3VdbeMemMakeWriteable(pMem);
  20329. if( rc==SQLITE_OK ){
  20330. pMem->n -= 2;
  20331. memmove(pMem->z, &pMem->z[2], pMem->n);
  20332. pMem->z[pMem->n] = '\0';
  20333. pMem->z[pMem->n+1] = '\0';
  20334. pMem->flags |= MEM_Term;
  20335. pMem->enc = bom;
  20336. }
  20337. }
  20338. return rc;
  20339. }
  20340. #endif /* SQLITE_OMIT_UTF16 */
  20341. /*
  20342. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  20343. ** return the number of unicode characters in pZ up to (but not including)
  20344. ** the first 0x00 byte. If nByte is not less than zero, return the
  20345. ** number of unicode characters in the first nByte of pZ (or up to
  20346. ** the first 0x00, whichever comes first).
  20347. */
  20348. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  20349. int r = 0;
  20350. const u8 *z = (const u8*)zIn;
  20351. const u8 *zTerm;
  20352. if( nByte>=0 ){
  20353. zTerm = &z[nByte];
  20354. }else{
  20355. zTerm = (const u8*)(-1);
  20356. }
  20357. assert( z<=zTerm );
  20358. while( *z!=0 && z<zTerm ){
  20359. SQLITE_SKIP_UTF8(z);
  20360. r++;
  20361. }
  20362. return r;
  20363. }
  20364. /* This test function is not currently used by the automated test-suite.
  20365. ** Hence it is only available in debug builds.
  20366. */
  20367. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  20368. /*
  20369. ** Translate UTF-8 to UTF-8.
  20370. **
  20371. ** This has the effect of making sure that the string is well-formed
  20372. ** UTF-8. Miscoded characters are removed.
  20373. **
  20374. ** The translation is done in-place and aborted if the output
  20375. ** overruns the input.
  20376. */
  20377. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  20378. unsigned char *zOut = zIn;
  20379. unsigned char *zStart = zIn;
  20380. u32 c;
  20381. while( zIn[0] && zOut<=zIn ){
  20382. c = sqlite3Utf8Read((const u8**)&zIn);
  20383. if( c!=0xfffd ){
  20384. WRITE_UTF8(zOut, c);
  20385. }
  20386. }
  20387. *zOut = 0;
  20388. return (int)(zOut - zStart);
  20389. }
  20390. #endif
  20391. #ifndef SQLITE_OMIT_UTF16
  20392. /*
  20393. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  20394. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  20395. ** be freed by the calling function.
  20396. **
  20397. ** NULL is returned if there is an allocation error.
  20398. */
  20399. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  20400. Mem m;
  20401. memset(&m, 0, sizeof(m));
  20402. m.db = db;
  20403. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  20404. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  20405. if( db->mallocFailed ){
  20406. sqlite3VdbeMemRelease(&m);
  20407. m.z = 0;
  20408. }
  20409. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  20410. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  20411. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  20412. assert( m.z || db->mallocFailed );
  20413. return m.z;
  20414. }
  20415. /*
  20416. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  20417. ** Return the number of bytes in the first nChar unicode characters
  20418. ** in pZ. nChar must be non-negative.
  20419. */
  20420. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  20421. int c;
  20422. unsigned char const *z = zIn;
  20423. int n = 0;
  20424. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  20425. while( n<nChar ){
  20426. READ_UTF16BE(z, 1, c);
  20427. n++;
  20428. }
  20429. }else{
  20430. while( n<nChar ){
  20431. READ_UTF16LE(z, 1, c);
  20432. n++;
  20433. }
  20434. }
  20435. return (int)(z-(unsigned char const *)zIn);
  20436. }
  20437. #if defined(SQLITE_TEST)
  20438. /*
  20439. ** This routine is called from the TCL test function "translate_selftest".
  20440. ** It checks that the primitives for serializing and deserializing
  20441. ** characters in each encoding are inverses of each other.
  20442. */
  20443. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  20444. unsigned int i, t;
  20445. unsigned char zBuf[20];
  20446. unsigned char *z;
  20447. int n;
  20448. unsigned int c;
  20449. for(i=0; i<0x00110000; i++){
  20450. z = zBuf;
  20451. WRITE_UTF8(z, i);
  20452. n = (int)(z-zBuf);
  20453. assert( n>0 && n<=4 );
  20454. z[0] = 0;
  20455. z = zBuf;
  20456. c = sqlite3Utf8Read((const u8**)&z);
  20457. t = i;
  20458. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  20459. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  20460. assert( c==t );
  20461. assert( (z-zBuf)==n );
  20462. }
  20463. for(i=0; i<0x00110000; i++){
  20464. if( i>=0xD800 && i<0xE000 ) continue;
  20465. z = zBuf;
  20466. WRITE_UTF16LE(z, i);
  20467. n = (int)(z-zBuf);
  20468. assert( n>0 && n<=4 );
  20469. z[0] = 0;
  20470. z = zBuf;
  20471. READ_UTF16LE(z, 1, c);
  20472. assert( c==i );
  20473. assert( (z-zBuf)==n );
  20474. }
  20475. for(i=0; i<0x00110000; i++){
  20476. if( i>=0xD800 && i<0xE000 ) continue;
  20477. z = zBuf;
  20478. WRITE_UTF16BE(z, i);
  20479. n = (int)(z-zBuf);
  20480. assert( n>0 && n<=4 );
  20481. z[0] = 0;
  20482. z = zBuf;
  20483. READ_UTF16BE(z, 1, c);
  20484. assert( c==i );
  20485. assert( (z-zBuf)==n );
  20486. }
  20487. }
  20488. #endif /* SQLITE_TEST */
  20489. #endif /* SQLITE_OMIT_UTF16 */
  20490. /************** End of utf.c *************************************************/
  20491. /************** Begin file util.c ********************************************/
  20492. /*
  20493. ** 2001 September 15
  20494. **
  20495. ** The author disclaims copyright to this source code. In place of
  20496. ** a legal notice, here is a blessing:
  20497. **
  20498. ** May you do good and not evil.
  20499. ** May you find forgiveness for yourself and forgive others.
  20500. ** May you share freely, never taking more than you give.
  20501. **
  20502. *************************************************************************
  20503. ** Utility functions used throughout sqlite.
  20504. **
  20505. ** This file contains functions for allocating memory, comparing
  20506. ** strings, and stuff like that.
  20507. **
  20508. */
  20509. /* #include <stdarg.h> */
  20510. #ifdef SQLITE_HAVE_ISNAN
  20511. # include <math.h>
  20512. #endif
  20513. /*
  20514. ** Routine needed to support the testcase() macro.
  20515. */
  20516. #ifdef SQLITE_COVERAGE_TEST
  20517. SQLITE_PRIVATE void sqlite3Coverage(int x){
  20518. static unsigned dummy = 0;
  20519. dummy += (unsigned)x;
  20520. }
  20521. #endif
  20522. #ifndef SQLITE_OMIT_FLOATING_POINT
  20523. /*
  20524. ** Return true if the floating point value is Not a Number (NaN).
  20525. **
  20526. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  20527. ** Otherwise, we have our own implementation that works on most systems.
  20528. */
  20529. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  20530. int rc; /* The value return */
  20531. #if !defined(SQLITE_HAVE_ISNAN)
  20532. /*
  20533. ** Systems that support the isnan() library function should probably
  20534. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  20535. ** found that many systems do not have a working isnan() function so
  20536. ** this implementation is provided as an alternative.
  20537. **
  20538. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  20539. ** On the other hand, the use of -ffast-math comes with the following
  20540. ** warning:
  20541. **
  20542. ** This option [-ffast-math] should never be turned on by any
  20543. ** -O option since it can result in incorrect output for programs
  20544. ** which depend on an exact implementation of IEEE or ISO
  20545. ** rules/specifications for math functions.
  20546. **
  20547. ** Under MSVC, this NaN test may fail if compiled with a floating-
  20548. ** point precision mode other than /fp:precise. From the MSDN
  20549. ** documentation:
  20550. **
  20551. ** The compiler [with /fp:precise] will properly handle comparisons
  20552. ** involving NaN. For example, x != x evaluates to true if x is NaN
  20553. ** ...
  20554. */
  20555. #ifdef __FAST_MATH__
  20556. # error SQLite will not work correctly with the -ffast-math option of GCC.
  20557. #endif
  20558. volatile double y = x;
  20559. volatile double z = y;
  20560. rc = (y!=z);
  20561. #else /* if defined(SQLITE_HAVE_ISNAN) */
  20562. rc = isnan(x);
  20563. #endif /* SQLITE_HAVE_ISNAN */
  20564. testcase( rc );
  20565. return rc;
  20566. }
  20567. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20568. /*
  20569. ** Compute a string length that is limited to what can be stored in
  20570. ** lower 30 bits of a 32-bit signed integer.
  20571. **
  20572. ** The value returned will never be negative. Nor will it ever be greater
  20573. ** than the actual length of the string. For very long strings (greater
  20574. ** than 1GiB) the value returned might be less than the true string length.
  20575. */
  20576. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  20577. const char *z2 = z;
  20578. if( z==0 ) return 0;
  20579. while( *z2 ){ z2++; }
  20580. return 0x3fffffff & (int)(z2 - z);
  20581. }
  20582. /*
  20583. ** Set the most recent error code and error string for the sqlite
  20584. ** handle "db". The error code is set to "err_code".
  20585. **
  20586. ** If it is not NULL, string zFormat specifies the format of the
  20587. ** error string in the style of the printf functions: The following
  20588. ** format characters are allowed:
  20589. **
  20590. ** %s Insert a string
  20591. ** %z A string that should be freed after use
  20592. ** %d Insert an integer
  20593. ** %T Insert a token
  20594. ** %S Insert the first element of a SrcList
  20595. **
  20596. ** zFormat and any string tokens that follow it are assumed to be
  20597. ** encoded in UTF-8.
  20598. **
  20599. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20600. ** should be called with err_code set to SQLITE_OK and zFormat set
  20601. ** to NULL.
  20602. */
  20603. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20604. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20605. db->errCode = err_code;
  20606. if( zFormat ){
  20607. char *z;
  20608. va_list ap;
  20609. va_start(ap, zFormat);
  20610. z = sqlite3VMPrintf(db, zFormat, ap);
  20611. va_end(ap);
  20612. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20613. }else{
  20614. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20615. }
  20616. }
  20617. }
  20618. /*
  20619. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20620. ** The following formatting characters are allowed:
  20621. **
  20622. ** %s Insert a string
  20623. ** %z A string that should be freed after use
  20624. ** %d Insert an integer
  20625. ** %T Insert a token
  20626. ** %S Insert the first element of a SrcList
  20627. **
  20628. ** This function should be used to report any error that occurs whilst
  20629. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20630. ** last thing the sqlite3_prepare() function does is copy the error
  20631. ** stored by this function into the database handle using sqlite3Error().
  20632. ** Function sqlite3Error() should be used during statement execution
  20633. ** (sqlite3_step() etc.).
  20634. */
  20635. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20636. char *zMsg;
  20637. va_list ap;
  20638. sqlite3 *db = pParse->db;
  20639. va_start(ap, zFormat);
  20640. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20641. va_end(ap);
  20642. if( db->suppressErr ){
  20643. sqlite3DbFree(db, zMsg);
  20644. }else{
  20645. pParse->nErr++;
  20646. sqlite3DbFree(db, pParse->zErrMsg);
  20647. pParse->zErrMsg = zMsg;
  20648. pParse->rc = SQLITE_ERROR;
  20649. }
  20650. }
  20651. /*
  20652. ** Convert an SQL-style quoted string into a normal string by removing
  20653. ** the quote characters. The conversion is done in-place. If the
  20654. ** input does not begin with a quote character, then this routine
  20655. ** is a no-op.
  20656. **
  20657. ** The input string must be zero-terminated. A new zero-terminator
  20658. ** is added to the dequoted string.
  20659. **
  20660. ** The return value is -1 if no dequoting occurs or the length of the
  20661. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20662. ** occur.
  20663. **
  20664. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20665. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20666. ** "a-b-c".
  20667. */
  20668. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20669. char quote;
  20670. int i, j;
  20671. if( z==0 ) return -1;
  20672. quote = z[0];
  20673. switch( quote ){
  20674. case '\'': break;
  20675. case '"': break;
  20676. case '`': break; /* For MySQL compatibility */
  20677. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20678. default: return -1;
  20679. }
  20680. for(i=1, j=0;; i++){
  20681. assert( z[i] );
  20682. if( z[i]==quote ){
  20683. if( z[i+1]==quote ){
  20684. z[j++] = quote;
  20685. i++;
  20686. }else{
  20687. break;
  20688. }
  20689. }else{
  20690. z[j++] = z[i];
  20691. }
  20692. }
  20693. z[j] = 0;
  20694. return j;
  20695. }
  20696. /* Convenient short-hand */
  20697. #define UpperToLower sqlite3UpperToLower
  20698. /*
  20699. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20700. ** there is no consistency, we will define our own.
  20701. **
  20702. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20703. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20704. ** the contents of two buffers containing UTF-8 strings in a
  20705. ** case-independent fashion, using the same definition of "case
  20706. ** independence" that SQLite uses internally when comparing identifiers.
  20707. */
  20708. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20709. register unsigned char *a, *b;
  20710. a = (unsigned char *)zLeft;
  20711. b = (unsigned char *)zRight;
  20712. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20713. return UpperToLower[*a] - UpperToLower[*b];
  20714. }
  20715. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20716. register unsigned char *a, *b;
  20717. a = (unsigned char *)zLeft;
  20718. b = (unsigned char *)zRight;
  20719. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20720. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20721. }
  20722. /*
  20723. ** The string z[] is an text representation of a real number.
  20724. ** Convert this string to a double and write it into *pResult.
  20725. **
  20726. ** The string z[] is length bytes in length (bytes, not characters) and
  20727. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20728. **
  20729. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20730. ** if the string is empty or contains extraneous text. Valid numbers
  20731. ** are in one of these formats:
  20732. **
  20733. ** [+-]digits[E[+-]digits]
  20734. ** [+-]digits.[digits][E[+-]digits]
  20735. ** [+-].digits[E[+-]digits]
  20736. **
  20737. ** Leading and trailing whitespace is ignored for the purpose of determining
  20738. ** validity.
  20739. **
  20740. ** If some prefix of the input string is a valid number, this routine
  20741. ** returns FALSE but it still converts the prefix and writes the result
  20742. ** into *pResult.
  20743. */
  20744. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20745. #ifndef SQLITE_OMIT_FLOATING_POINT
  20746. int incr;
  20747. const char *zEnd = z + length;
  20748. /* sign * significand * (10 ^ (esign * exponent)) */
  20749. int sign = 1; /* sign of significand */
  20750. i64 s = 0; /* significand */
  20751. int d = 0; /* adjust exponent for shifting decimal point */
  20752. int esign = 1; /* sign of exponent */
  20753. int e = 0; /* exponent */
  20754. int eValid = 1; /* True exponent is either not used or is well-formed */
  20755. double result;
  20756. int nDigits = 0;
  20757. int nonNum = 0;
  20758. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20759. *pResult = 0.0; /* Default return value, in case of an error */
  20760. if( enc==SQLITE_UTF8 ){
  20761. incr = 1;
  20762. }else{
  20763. int i;
  20764. incr = 2;
  20765. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20766. for(i=3-enc; i<length && z[i]==0; i+=2){}
  20767. nonNum = i<length;
  20768. zEnd = z+i+enc-3;
  20769. z += (enc&1);
  20770. }
  20771. /* skip leading spaces */
  20772. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20773. if( z>=zEnd ) return 0;
  20774. /* get sign of significand */
  20775. if( *z=='-' ){
  20776. sign = -1;
  20777. z+=incr;
  20778. }else if( *z=='+' ){
  20779. z+=incr;
  20780. }
  20781. /* skip leading zeroes */
  20782. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20783. /* copy max significant digits to significand */
  20784. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20785. s = s*10 + (*z - '0');
  20786. z+=incr, nDigits++;
  20787. }
  20788. /* skip non-significant significand digits
  20789. ** (increase exponent by d to shift decimal left) */
  20790. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20791. if( z>=zEnd ) goto do_atof_calc;
  20792. /* if decimal point is present */
  20793. if( *z=='.' ){
  20794. z+=incr;
  20795. /* copy digits from after decimal to significand
  20796. ** (decrease exponent by d to shift decimal right) */
  20797. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20798. s = s*10 + (*z - '0');
  20799. z+=incr, nDigits++, d--;
  20800. }
  20801. /* skip non-significant digits */
  20802. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20803. }
  20804. if( z>=zEnd ) goto do_atof_calc;
  20805. /* if exponent is present */
  20806. if( *z=='e' || *z=='E' ){
  20807. z+=incr;
  20808. eValid = 0;
  20809. if( z>=zEnd ) goto do_atof_calc;
  20810. /* get sign of exponent */
  20811. if( *z=='-' ){
  20812. esign = -1;
  20813. z+=incr;
  20814. }else if( *z=='+' ){
  20815. z+=incr;
  20816. }
  20817. /* copy digits to exponent */
  20818. while( z<zEnd && sqlite3Isdigit(*z) ){
  20819. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20820. z+=incr;
  20821. eValid = 1;
  20822. }
  20823. }
  20824. /* skip trailing spaces */
  20825. if( nDigits && eValid ){
  20826. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20827. }
  20828. do_atof_calc:
  20829. /* adjust exponent by d, and update sign */
  20830. e = (e*esign) + d;
  20831. if( e<0 ) {
  20832. esign = -1;
  20833. e *= -1;
  20834. } else {
  20835. esign = 1;
  20836. }
  20837. /* if 0 significand */
  20838. if( !s ) {
  20839. /* In the IEEE 754 standard, zero is signed.
  20840. ** Add the sign if we've seen at least one digit */
  20841. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20842. } else {
  20843. /* attempt to reduce exponent */
  20844. if( esign>0 ){
  20845. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20846. }else{
  20847. while( !(s%10) && e>0 ) e--,s/=10;
  20848. }
  20849. /* adjust the sign of significand */
  20850. s = sign<0 ? -s : s;
  20851. /* if exponent, scale significand as appropriate
  20852. ** and store in result. */
  20853. if( e ){
  20854. LONGDOUBLE_TYPE scale = 1.0;
  20855. /* attempt to handle extremely small/large numbers better */
  20856. if( e>307 && e<342 ){
  20857. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20858. if( esign<0 ){
  20859. result = s / scale;
  20860. result /= 1.0e+308;
  20861. }else{
  20862. result = s * scale;
  20863. result *= 1.0e+308;
  20864. }
  20865. }else if( e>=342 ){
  20866. if( esign<0 ){
  20867. result = 0.0*s;
  20868. }else{
  20869. result = 1e308*1e308*s; /* Infinity */
  20870. }
  20871. }else{
  20872. /* 1.0e+22 is the largest power of 10 than can be
  20873. ** represented exactly. */
  20874. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20875. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20876. if( esign<0 ){
  20877. result = s / scale;
  20878. }else{
  20879. result = s * scale;
  20880. }
  20881. }
  20882. } else {
  20883. result = (double)s;
  20884. }
  20885. }
  20886. /* store the result */
  20887. *pResult = result;
  20888. /* return true if number and no extra non-whitespace chracters after */
  20889. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  20890. #else
  20891. return !sqlite3Atoi64(z, pResult, length, enc);
  20892. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20893. }
  20894. /*
  20895. ** Compare the 19-character string zNum against the text representation
  20896. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20897. ** if zNum is less than, equal to, or greater than the string.
  20898. ** Note that zNum must contain exactly 19 characters.
  20899. **
  20900. ** Unlike memcmp() this routine is guaranteed to return the difference
  20901. ** in the values of the last digit if the only difference is in the
  20902. ** last digit. So, for example,
  20903. **
  20904. ** compare2pow63("9223372036854775800", 1)
  20905. **
  20906. ** will return -8.
  20907. */
  20908. static int compare2pow63(const char *zNum, int incr){
  20909. int c = 0;
  20910. int i;
  20911. /* 012345678901234567 */
  20912. const char *pow63 = "922337203685477580";
  20913. for(i=0; c==0 && i<18; i++){
  20914. c = (zNum[i*incr]-pow63[i])*10;
  20915. }
  20916. if( c==0 ){
  20917. c = zNum[18*incr] - '8';
  20918. testcase( c==(-1) );
  20919. testcase( c==0 );
  20920. testcase( c==(+1) );
  20921. }
  20922. return c;
  20923. }
  20924. /*
  20925. ** Convert zNum to a 64-bit signed integer.
  20926. **
  20927. ** If the zNum value is representable as a 64-bit twos-complement
  20928. ** integer, then write that value into *pNum and return 0.
  20929. **
  20930. ** If zNum is exactly 9223372036854665808, return 2. This special
  20931. ** case is broken out because while 9223372036854665808 cannot be a
  20932. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20933. **
  20934. ** If zNum is too big for a 64-bit integer and is not
  20935. ** 9223372036854665808 or if zNum contains any non-numeric text,
  20936. ** then return 1.
  20937. **
  20938. ** length is the number of bytes in the string (bytes, not characters).
  20939. ** The string is not necessarily zero-terminated. The encoding is
  20940. ** given by enc.
  20941. */
  20942. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20943. int incr;
  20944. u64 u = 0;
  20945. int neg = 0; /* assume positive */
  20946. int i;
  20947. int c = 0;
  20948. int nonNum = 0;
  20949. const char *zStart;
  20950. const char *zEnd = zNum + length;
  20951. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20952. if( enc==SQLITE_UTF8 ){
  20953. incr = 1;
  20954. }else{
  20955. incr = 2;
  20956. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20957. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  20958. nonNum = i<length;
  20959. zEnd = zNum+i+enc-3;
  20960. zNum += (enc&1);
  20961. }
  20962. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20963. if( zNum<zEnd ){
  20964. if( *zNum=='-' ){
  20965. neg = 1;
  20966. zNum+=incr;
  20967. }else if( *zNum=='+' ){
  20968. zNum+=incr;
  20969. }
  20970. }
  20971. zStart = zNum;
  20972. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20973. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20974. u = u*10 + c - '0';
  20975. }
  20976. if( u>LARGEST_INT64 ){
  20977. *pNum = SMALLEST_INT64;
  20978. }else if( neg ){
  20979. *pNum = -(i64)u;
  20980. }else{
  20981. *pNum = (i64)u;
  20982. }
  20983. testcase( i==18 );
  20984. testcase( i==19 );
  20985. testcase( i==20 );
  20986. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  20987. /* zNum is empty or contains non-numeric text or is longer
  20988. ** than 19 digits (thus guaranteeing that it is too large) */
  20989. return 1;
  20990. }else if( i<19*incr ){
  20991. /* Less than 19 digits, so we know that it fits in 64 bits */
  20992. assert( u<=LARGEST_INT64 );
  20993. return 0;
  20994. }else{
  20995. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20996. c = compare2pow63(zNum, incr);
  20997. if( c<0 ){
  20998. /* zNum is less than 9223372036854775808 so it fits */
  20999. assert( u<=LARGEST_INT64 );
  21000. return 0;
  21001. }else if( c>0 ){
  21002. /* zNum is greater than 9223372036854775808 so it overflows */
  21003. return 1;
  21004. }else{
  21005. /* zNum is exactly 9223372036854775808. Fits if negative. The
  21006. ** special case 2 overflow if positive */
  21007. assert( u-1==LARGEST_INT64 );
  21008. assert( (*pNum)==SMALLEST_INT64 );
  21009. return neg ? 0 : 2;
  21010. }
  21011. }
  21012. }
  21013. /*
  21014. ** If zNum represents an integer that will fit in 32-bits, then set
  21015. ** *pValue to that integer and return true. Otherwise return false.
  21016. **
  21017. ** Any non-numeric characters that following zNum are ignored.
  21018. ** This is different from sqlite3Atoi64() which requires the
  21019. ** input number to be zero-terminated.
  21020. */
  21021. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  21022. sqlite_int64 v = 0;
  21023. int i, c;
  21024. int neg = 0;
  21025. if( zNum[0]=='-' ){
  21026. neg = 1;
  21027. zNum++;
  21028. }else if( zNum[0]=='+' ){
  21029. zNum++;
  21030. }
  21031. while( zNum[0]=='0' ) zNum++;
  21032. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  21033. v = v*10 + c;
  21034. }
  21035. /* The longest decimal representation of a 32 bit integer is 10 digits:
  21036. **
  21037. ** 1234567890
  21038. ** 2^31 -> 2147483648
  21039. */
  21040. testcase( i==10 );
  21041. if( i>10 ){
  21042. return 0;
  21043. }
  21044. testcase( v-neg==2147483647 );
  21045. if( v-neg>2147483647 ){
  21046. return 0;
  21047. }
  21048. if( neg ){
  21049. v = -v;
  21050. }
  21051. *pValue = (int)v;
  21052. return 1;
  21053. }
  21054. /*
  21055. ** Return a 32-bit integer value extracted from a string. If the
  21056. ** string is not an integer, just return 0.
  21057. */
  21058. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  21059. int x = 0;
  21060. if( z ) sqlite3GetInt32(z, &x);
  21061. return x;
  21062. }
  21063. /*
  21064. ** The variable-length integer encoding is as follows:
  21065. **
  21066. ** KEY:
  21067. ** A = 0xxxxxxx 7 bits of data and one flag bit
  21068. ** B = 1xxxxxxx 7 bits of data and one flag bit
  21069. ** C = xxxxxxxx 8 bits of data
  21070. **
  21071. ** 7 bits - A
  21072. ** 14 bits - BA
  21073. ** 21 bits - BBA
  21074. ** 28 bits - BBBA
  21075. ** 35 bits - BBBBA
  21076. ** 42 bits - BBBBBA
  21077. ** 49 bits - BBBBBBA
  21078. ** 56 bits - BBBBBBBA
  21079. ** 64 bits - BBBBBBBBC
  21080. */
  21081. /*
  21082. ** Write a 64-bit variable-length integer to memory starting at p[0].
  21083. ** The length of data write will be between 1 and 9 bytes. The number
  21084. ** of bytes written is returned.
  21085. **
  21086. ** A variable-length integer consists of the lower 7 bits of each byte
  21087. ** for all bytes that have the 8th bit set and one byte with the 8th
  21088. ** bit clear. Except, if we get to the 9th byte, it stores the full
  21089. ** 8 bits and is the last byte.
  21090. */
  21091. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  21092. int i, j, n;
  21093. u8 buf[10];
  21094. if( v & (((u64)0xff000000)<<32) ){
  21095. p[8] = (u8)v;
  21096. v >>= 8;
  21097. for(i=7; i>=0; i--){
  21098. p[i] = (u8)((v & 0x7f) | 0x80);
  21099. v >>= 7;
  21100. }
  21101. return 9;
  21102. }
  21103. n = 0;
  21104. do{
  21105. buf[n++] = (u8)((v & 0x7f) | 0x80);
  21106. v >>= 7;
  21107. }while( v!=0 );
  21108. buf[0] &= 0x7f;
  21109. assert( n<=9 );
  21110. for(i=0, j=n-1; j>=0; j--, i++){
  21111. p[i] = buf[j];
  21112. }
  21113. return n;
  21114. }
  21115. /*
  21116. ** This routine is a faster version of sqlite3PutVarint() that only
  21117. ** works for 32-bit positive integers and which is optimized for
  21118. ** the common case of small integers. A MACRO version, putVarint32,
  21119. ** is provided which inlines the single-byte case. All code should use
  21120. ** the MACRO version as this function assumes the single-byte case has
  21121. ** already been handled.
  21122. */
  21123. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  21124. #ifndef putVarint32
  21125. if( (v & ~0x7f)==0 ){
  21126. p[0] = v;
  21127. return 1;
  21128. }
  21129. #endif
  21130. if( (v & ~0x3fff)==0 ){
  21131. p[0] = (u8)((v>>7) | 0x80);
  21132. p[1] = (u8)(v & 0x7f);
  21133. return 2;
  21134. }
  21135. return sqlite3PutVarint(p, v);
  21136. }
  21137. /*
  21138. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  21139. ** are defined here rather than simply putting the constant expressions
  21140. ** inline in order to work around bugs in the RVT compiler.
  21141. **
  21142. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  21143. **
  21144. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  21145. */
  21146. #define SLOT_2_0 0x001fc07f
  21147. #define SLOT_4_2_0 0xf01fc07f
  21148. /*
  21149. ** Read a 64-bit variable-length integer from memory starting at p[0].
  21150. ** Return the number of bytes read. The value is stored in *v.
  21151. */
  21152. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  21153. u32 a,b,s;
  21154. a = *p;
  21155. /* a: p0 (unmasked) */
  21156. if (!(a&0x80))
  21157. {
  21158. *v = a;
  21159. return 1;
  21160. }
  21161. p++;
  21162. b = *p;
  21163. /* b: p1 (unmasked) */
  21164. if (!(b&0x80))
  21165. {
  21166. a &= 0x7f;
  21167. a = a<<7;
  21168. a |= b;
  21169. *v = a;
  21170. return 2;
  21171. }
  21172. /* Verify that constants are precomputed correctly */
  21173. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  21174. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  21175. p++;
  21176. a = a<<14;
  21177. a |= *p;
  21178. /* a: p0<<14 | p2 (unmasked) */
  21179. if (!(a&0x80))
  21180. {
  21181. a &= SLOT_2_0;
  21182. b &= 0x7f;
  21183. b = b<<7;
  21184. a |= b;
  21185. *v = a;
  21186. return 3;
  21187. }
  21188. /* CSE1 from below */
  21189. a &= SLOT_2_0;
  21190. p++;
  21191. b = b<<14;
  21192. b |= *p;
  21193. /* b: p1<<14 | p3 (unmasked) */
  21194. if (!(b&0x80))
  21195. {
  21196. b &= SLOT_2_0;
  21197. /* moved CSE1 up */
  21198. /* a &= (0x7f<<14)|(0x7f); */
  21199. a = a<<7;
  21200. a |= b;
  21201. *v = a;
  21202. return 4;
  21203. }
  21204. /* a: p0<<14 | p2 (masked) */
  21205. /* b: p1<<14 | p3 (unmasked) */
  21206. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21207. /* moved CSE1 up */
  21208. /* a &= (0x7f<<14)|(0x7f); */
  21209. b &= SLOT_2_0;
  21210. s = a;
  21211. /* s: p0<<14 | p2 (masked) */
  21212. p++;
  21213. a = a<<14;
  21214. a |= *p;
  21215. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21216. if (!(a&0x80))
  21217. {
  21218. /* we can skip these cause they were (effectively) done above in calc'ing s */
  21219. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  21220. /* b &= (0x7f<<14)|(0x7f); */
  21221. b = b<<7;
  21222. a |= b;
  21223. s = s>>18;
  21224. *v = ((u64)s)<<32 | a;
  21225. return 5;
  21226. }
  21227. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21228. s = s<<7;
  21229. s |= b;
  21230. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21231. p++;
  21232. b = b<<14;
  21233. b |= *p;
  21234. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  21235. if (!(b&0x80))
  21236. {
  21237. /* we can skip this cause it was (effectively) done above in calc'ing s */
  21238. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  21239. a &= SLOT_2_0;
  21240. a = a<<7;
  21241. a |= b;
  21242. s = s>>18;
  21243. *v = ((u64)s)<<32 | a;
  21244. return 6;
  21245. }
  21246. p++;
  21247. a = a<<14;
  21248. a |= *p;
  21249. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  21250. if (!(a&0x80))
  21251. {
  21252. a &= SLOT_4_2_0;
  21253. b &= SLOT_2_0;
  21254. b = b<<7;
  21255. a |= b;
  21256. s = s>>11;
  21257. *v = ((u64)s)<<32 | a;
  21258. return 7;
  21259. }
  21260. /* CSE2 from below */
  21261. a &= SLOT_2_0;
  21262. p++;
  21263. b = b<<14;
  21264. b |= *p;
  21265. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  21266. if (!(b&0x80))
  21267. {
  21268. b &= SLOT_4_2_0;
  21269. /* moved CSE2 up */
  21270. /* a &= (0x7f<<14)|(0x7f); */
  21271. a = a<<7;
  21272. a |= b;
  21273. s = s>>4;
  21274. *v = ((u64)s)<<32 | a;
  21275. return 8;
  21276. }
  21277. p++;
  21278. a = a<<15;
  21279. a |= *p;
  21280. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  21281. /* moved CSE2 up */
  21282. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  21283. b &= SLOT_2_0;
  21284. b = b<<8;
  21285. a |= b;
  21286. s = s<<4;
  21287. b = p[-4];
  21288. b &= 0x7f;
  21289. b = b>>3;
  21290. s |= b;
  21291. *v = ((u64)s)<<32 | a;
  21292. return 9;
  21293. }
  21294. /*
  21295. ** Read a 32-bit variable-length integer from memory starting at p[0].
  21296. ** Return the number of bytes read. The value is stored in *v.
  21297. **
  21298. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  21299. ** integer, then set *v to 0xffffffff.
  21300. **
  21301. ** A MACRO version, getVarint32, is provided which inlines the
  21302. ** single-byte case. All code should use the MACRO version as
  21303. ** this function assumes the single-byte case has already been handled.
  21304. */
  21305. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  21306. u32 a,b;
  21307. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  21308. ** by the getVarin32() macro */
  21309. a = *p;
  21310. /* a: p0 (unmasked) */
  21311. #ifndef getVarint32
  21312. if (!(a&0x80))
  21313. {
  21314. /* Values between 0 and 127 */
  21315. *v = a;
  21316. return 1;
  21317. }
  21318. #endif
  21319. /* The 2-byte case */
  21320. p++;
  21321. b = *p;
  21322. /* b: p1 (unmasked) */
  21323. if (!(b&0x80))
  21324. {
  21325. /* Values between 128 and 16383 */
  21326. a &= 0x7f;
  21327. a = a<<7;
  21328. *v = a | b;
  21329. return 2;
  21330. }
  21331. /* The 3-byte case */
  21332. p++;
  21333. a = a<<14;
  21334. a |= *p;
  21335. /* a: p0<<14 | p2 (unmasked) */
  21336. if (!(a&0x80))
  21337. {
  21338. /* Values between 16384 and 2097151 */
  21339. a &= (0x7f<<14)|(0x7f);
  21340. b &= 0x7f;
  21341. b = b<<7;
  21342. *v = a | b;
  21343. return 3;
  21344. }
  21345. /* A 32-bit varint is used to store size information in btrees.
  21346. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  21347. ** A 3-byte varint is sufficient, for example, to record the size
  21348. ** of a 1048569-byte BLOB or string.
  21349. **
  21350. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  21351. ** rare larger cases can be handled by the slower 64-bit varint
  21352. ** routine.
  21353. */
  21354. #if 1
  21355. {
  21356. u64 v64;
  21357. u8 n;
  21358. p -= 2;
  21359. n = sqlite3GetVarint(p, &v64);
  21360. assert( n>3 && n<=9 );
  21361. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  21362. *v = 0xffffffff;
  21363. }else{
  21364. *v = (u32)v64;
  21365. }
  21366. return n;
  21367. }
  21368. #else
  21369. /* For following code (kept for historical record only) shows an
  21370. ** unrolling for the 3- and 4-byte varint cases. This code is
  21371. ** slightly faster, but it is also larger and much harder to test.
  21372. */
  21373. p++;
  21374. b = b<<14;
  21375. b |= *p;
  21376. /* b: p1<<14 | p3 (unmasked) */
  21377. if (!(b&0x80))
  21378. {
  21379. /* Values between 2097152 and 268435455 */
  21380. b &= (0x7f<<14)|(0x7f);
  21381. a &= (0x7f<<14)|(0x7f);
  21382. a = a<<7;
  21383. *v = a | b;
  21384. return 4;
  21385. }
  21386. p++;
  21387. a = a<<14;
  21388. a |= *p;
  21389. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21390. if (!(a&0x80))
  21391. {
  21392. /* Values between 268435456 and 34359738367 */
  21393. a &= SLOT_4_2_0;
  21394. b &= SLOT_4_2_0;
  21395. b = b<<7;
  21396. *v = a | b;
  21397. return 5;
  21398. }
  21399. /* We can only reach this point when reading a corrupt database
  21400. ** file. In that case we are not in any hurry. Use the (relatively
  21401. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  21402. ** value. */
  21403. {
  21404. u64 v64;
  21405. u8 n;
  21406. p -= 4;
  21407. n = sqlite3GetVarint(p, &v64);
  21408. assert( n>5 && n<=9 );
  21409. *v = (u32)v64;
  21410. return n;
  21411. }
  21412. #endif
  21413. }
  21414. /*
  21415. ** Return the number of bytes that will be needed to store the given
  21416. ** 64-bit integer.
  21417. */
  21418. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  21419. int i = 0;
  21420. do{
  21421. i++;
  21422. v >>= 7;
  21423. }while( v!=0 && ALWAYS(i<9) );
  21424. return i;
  21425. }
  21426. /*
  21427. ** Read or write a four-byte big-endian integer value.
  21428. */
  21429. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  21430. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  21431. }
  21432. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  21433. p[0] = (u8)(v>>24);
  21434. p[1] = (u8)(v>>16);
  21435. p[2] = (u8)(v>>8);
  21436. p[3] = (u8)v;
  21437. }
  21438. /*
  21439. ** Translate a single byte of Hex into an integer.
  21440. ** This routine only works if h really is a valid hexadecimal
  21441. ** character: 0..9a..fA..F
  21442. */
  21443. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  21444. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  21445. #ifdef SQLITE_ASCII
  21446. h += 9*(1&(h>>6));
  21447. #endif
  21448. #ifdef SQLITE_EBCDIC
  21449. h += 9*(1&~(h>>4));
  21450. #endif
  21451. return (u8)(h & 0xf);
  21452. }
  21453. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  21454. /*
  21455. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  21456. ** value. Return a pointer to its binary value. Space to hold the
  21457. ** binary value has been obtained from malloc and must be freed by
  21458. ** the calling routine.
  21459. */
  21460. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  21461. char *zBlob;
  21462. int i;
  21463. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  21464. n--;
  21465. if( zBlob ){
  21466. for(i=0; i<n; i+=2){
  21467. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  21468. }
  21469. zBlob[i/2] = 0;
  21470. }
  21471. return zBlob;
  21472. }
  21473. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  21474. /*
  21475. ** Log an error that is an API call on a connection pointer that should
  21476. ** not have been used. The "type" of connection pointer is given as the
  21477. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  21478. */
  21479. static void logBadConnection(const char *zType){
  21480. sqlite3_log(SQLITE_MISUSE,
  21481. "API call with %s database connection pointer",
  21482. zType
  21483. );
  21484. }
  21485. /*
  21486. ** Check to make sure we have a valid db pointer. This test is not
  21487. ** foolproof but it does provide some measure of protection against
  21488. ** misuse of the interface such as passing in db pointers that are
  21489. ** NULL or which have been previously closed. If this routine returns
  21490. ** 1 it means that the db pointer is valid and 0 if it should not be
  21491. ** dereferenced for any reason. The calling function should invoke
  21492. ** SQLITE_MISUSE immediately.
  21493. **
  21494. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  21495. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  21496. ** open properly and is not fit for general use but which can be
  21497. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  21498. */
  21499. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  21500. u32 magic;
  21501. if( db==0 ){
  21502. logBadConnection("NULL");
  21503. return 0;
  21504. }
  21505. magic = db->magic;
  21506. if( magic!=SQLITE_MAGIC_OPEN ){
  21507. if( sqlite3SafetyCheckSickOrOk(db) ){
  21508. testcase( sqlite3GlobalConfig.xLog!=0 );
  21509. logBadConnection("unopened");
  21510. }
  21511. return 0;
  21512. }else{
  21513. return 1;
  21514. }
  21515. }
  21516. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  21517. u32 magic;
  21518. magic = db->magic;
  21519. if( magic!=SQLITE_MAGIC_SICK &&
  21520. magic!=SQLITE_MAGIC_OPEN &&
  21521. magic!=SQLITE_MAGIC_BUSY ){
  21522. testcase( sqlite3GlobalConfig.xLog!=0 );
  21523. logBadConnection("invalid");
  21524. return 0;
  21525. }else{
  21526. return 1;
  21527. }
  21528. }
  21529. /*
  21530. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  21531. ** the other 64-bit signed integer at *pA and store the result in *pA.
  21532. ** Return 0 on success. Or if the operation would have resulted in an
  21533. ** overflow, leave *pA unchanged and return 1.
  21534. */
  21535. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  21536. i64 iA = *pA;
  21537. testcase( iA==0 ); testcase( iA==1 );
  21538. testcase( iB==-1 ); testcase( iB==0 );
  21539. if( iB>=0 ){
  21540. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  21541. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  21542. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  21543. *pA += iB;
  21544. }else{
  21545. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  21546. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  21547. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  21548. *pA += iB;
  21549. }
  21550. return 0;
  21551. }
  21552. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  21553. testcase( iB==SMALLEST_INT64+1 );
  21554. if( iB==SMALLEST_INT64 ){
  21555. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  21556. if( (*pA)>=0 ) return 1;
  21557. *pA -= iB;
  21558. return 0;
  21559. }else{
  21560. return sqlite3AddInt64(pA, -iB);
  21561. }
  21562. }
  21563. #define TWOPOWER32 (((i64)1)<<32)
  21564. #define TWOPOWER31 (((i64)1)<<31)
  21565. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  21566. i64 iA = *pA;
  21567. i64 iA1, iA0, iB1, iB0, r;
  21568. iA1 = iA/TWOPOWER32;
  21569. iA0 = iA % TWOPOWER32;
  21570. iB1 = iB/TWOPOWER32;
  21571. iB0 = iB % TWOPOWER32;
  21572. if( iA1*iB1 != 0 ) return 1;
  21573. assert( iA1*iB0==0 || iA0*iB1==0 );
  21574. r = iA1*iB0 + iA0*iB1;
  21575. testcase( r==(-TWOPOWER31)-1 );
  21576. testcase( r==(-TWOPOWER31) );
  21577. testcase( r==TWOPOWER31 );
  21578. testcase( r==TWOPOWER31-1 );
  21579. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  21580. r *= TWOPOWER32;
  21581. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  21582. *pA = r;
  21583. return 0;
  21584. }
  21585. /*
  21586. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  21587. ** if the integer has a value of -2147483648, return +2147483647
  21588. */
  21589. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  21590. if( x>=0 ) return x;
  21591. if( x==(int)0x80000000 ) return 0x7fffffff;
  21592. return -x;
  21593. }
  21594. #ifdef SQLITE_ENABLE_8_3_NAMES
  21595. /*
  21596. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  21597. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  21598. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  21599. ** three characters, then shorten the suffix on z[] to be the last three
  21600. ** characters of the original suffix.
  21601. **
  21602. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  21603. ** do the suffix shortening regardless of URI parameter.
  21604. **
  21605. ** Examples:
  21606. **
  21607. ** test.db-journal => test.nal
  21608. ** test.db-wal => test.wal
  21609. ** test.db-shm => test.shm
  21610. ** test.db-mj7f3319fa => test.9fa
  21611. */
  21612. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21613. #if SQLITE_ENABLE_8_3_NAMES<2
  21614. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21615. #endif
  21616. {
  21617. int i, sz;
  21618. sz = sqlite3Strlen30(z);
  21619. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21620. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21621. }
  21622. }
  21623. #endif
  21624. /*
  21625. ** Find (an approximate) sum of two LogEst values. This computation is
  21626. ** not a simple "+" operator because LogEst is stored as a logarithmic
  21627. ** value.
  21628. **
  21629. */
  21630. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  21631. static const unsigned char x[] = {
  21632. 10, 10, /* 0,1 */
  21633. 9, 9, /* 2,3 */
  21634. 8, 8, /* 4,5 */
  21635. 7, 7, 7, /* 6,7,8 */
  21636. 6, 6, 6, /* 9,10,11 */
  21637. 5, 5, 5, /* 12-14 */
  21638. 4, 4, 4, 4, /* 15-18 */
  21639. 3, 3, 3, 3, 3, 3, /* 19-24 */
  21640. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  21641. };
  21642. if( a>=b ){
  21643. if( a>b+49 ) return a;
  21644. if( a>b+31 ) return a+1;
  21645. return a+x[a-b];
  21646. }else{
  21647. if( b>a+49 ) return b;
  21648. if( b>a+31 ) return b+1;
  21649. return b+x[b-a];
  21650. }
  21651. }
  21652. /*
  21653. ** Convert an integer into a LogEst. In other words, compute a
  21654. ** good approximatation for 10*log2(x).
  21655. */
  21656. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  21657. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  21658. LogEst y = 40;
  21659. if( x<8 ){
  21660. if( x<2 ) return 0;
  21661. while( x<8 ){ y -= 10; x <<= 1; }
  21662. }else{
  21663. while( x>255 ){ y += 40; x >>= 4; }
  21664. while( x>15 ){ y += 10; x >>= 1; }
  21665. }
  21666. return a[x&7] + y - 10;
  21667. }
  21668. #ifndef SQLITE_OMIT_VIRTUALTABLE
  21669. /*
  21670. ** Convert a double into a LogEst
  21671. ** In other words, compute an approximation for 10*log2(x).
  21672. */
  21673. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  21674. u64 a;
  21675. LogEst e;
  21676. assert( sizeof(x)==8 && sizeof(a)==8 );
  21677. if( x<=1 ) return 0;
  21678. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  21679. memcpy(&a, &x, 8);
  21680. e = (a>>52) - 1022;
  21681. return e*10;
  21682. }
  21683. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  21684. /*
  21685. ** Convert a LogEst into an integer.
  21686. */
  21687. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  21688. u64 n;
  21689. if( x<10 ) return 1;
  21690. n = x%10;
  21691. x /= 10;
  21692. if( n>=5 ) n -= 2;
  21693. else if( n>=1 ) n -= 1;
  21694. if( x>=3 ) return (n+8)<<(x-3);
  21695. return (n+8)>>(3-x);
  21696. }
  21697. /************** End of util.c ************************************************/
  21698. /************** Begin file hash.c ********************************************/
  21699. /*
  21700. ** 2001 September 22
  21701. **
  21702. ** The author disclaims copyright to this source code. In place of
  21703. ** a legal notice, here is a blessing:
  21704. **
  21705. ** May you do good and not evil.
  21706. ** May you find forgiveness for yourself and forgive others.
  21707. ** May you share freely, never taking more than you give.
  21708. **
  21709. *************************************************************************
  21710. ** This is the implementation of generic hash-tables
  21711. ** used in SQLite.
  21712. */
  21713. /* #include <assert.h> */
  21714. /* Turn bulk memory into a hash table object by initializing the
  21715. ** fields of the Hash structure.
  21716. **
  21717. ** "pNew" is a pointer to the hash table that is to be initialized.
  21718. */
  21719. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21720. assert( pNew!=0 );
  21721. pNew->first = 0;
  21722. pNew->count = 0;
  21723. pNew->htsize = 0;
  21724. pNew->ht = 0;
  21725. }
  21726. /* Remove all entries from a hash table. Reclaim all memory.
  21727. ** Call this routine to delete a hash table or to reset a hash table
  21728. ** to the empty state.
  21729. */
  21730. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21731. HashElem *elem; /* For looping over all elements of the table */
  21732. assert( pH!=0 );
  21733. elem = pH->first;
  21734. pH->first = 0;
  21735. sqlite3_free(pH->ht);
  21736. pH->ht = 0;
  21737. pH->htsize = 0;
  21738. while( elem ){
  21739. HashElem *next_elem = elem->next;
  21740. sqlite3_free(elem);
  21741. elem = next_elem;
  21742. }
  21743. pH->count = 0;
  21744. }
  21745. /*
  21746. ** The hashing function.
  21747. */
  21748. static unsigned int strHash(const char *z, int nKey){
  21749. int h = 0;
  21750. assert( nKey>=0 );
  21751. while( nKey > 0 ){
  21752. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21753. nKey--;
  21754. }
  21755. return h;
  21756. }
  21757. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21758. ** insert pNew into the pEntry hash bucket.
  21759. */
  21760. static void insertElement(
  21761. Hash *pH, /* The complete hash table */
  21762. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21763. HashElem *pNew /* The element to be inserted */
  21764. ){
  21765. HashElem *pHead; /* First element already in pEntry */
  21766. if( pEntry ){
  21767. pHead = pEntry->count ? pEntry->chain : 0;
  21768. pEntry->count++;
  21769. pEntry->chain = pNew;
  21770. }else{
  21771. pHead = 0;
  21772. }
  21773. if( pHead ){
  21774. pNew->next = pHead;
  21775. pNew->prev = pHead->prev;
  21776. if( pHead->prev ){ pHead->prev->next = pNew; }
  21777. else { pH->first = pNew; }
  21778. pHead->prev = pNew;
  21779. }else{
  21780. pNew->next = pH->first;
  21781. if( pH->first ){ pH->first->prev = pNew; }
  21782. pNew->prev = 0;
  21783. pH->first = pNew;
  21784. }
  21785. }
  21786. /* Resize the hash table so that it cantains "new_size" buckets.
  21787. **
  21788. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21789. ** if the new size is the same as the prior size.
  21790. ** Return TRUE if the resize occurs and false if not.
  21791. */
  21792. static int rehash(Hash *pH, unsigned int new_size){
  21793. struct _ht *new_ht; /* The new hash table */
  21794. HashElem *elem, *next_elem; /* For looping over existing elements */
  21795. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21796. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21797. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21798. }
  21799. if( new_size==pH->htsize ) return 0;
  21800. #endif
  21801. /* The inability to allocates space for a larger hash table is
  21802. ** a performance hit but it is not a fatal error. So mark the
  21803. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21804. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21805. ** only zeroes the requested number of bytes whereas this module will
  21806. ** use the actual amount of space allocated for the hash table (which
  21807. ** may be larger than the requested amount).
  21808. */
  21809. sqlite3BeginBenignMalloc();
  21810. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21811. sqlite3EndBenignMalloc();
  21812. if( new_ht==0 ) return 0;
  21813. sqlite3_free(pH->ht);
  21814. pH->ht = new_ht;
  21815. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21816. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21817. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21818. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21819. next_elem = elem->next;
  21820. insertElement(pH, &new_ht[h], elem);
  21821. }
  21822. return 1;
  21823. }
  21824. /* This function (for internal use only) locates an element in an
  21825. ** hash table that matches the given key. The hash for this key has
  21826. ** already been computed and is passed as the 4th parameter.
  21827. */
  21828. static HashElem *findElementGivenHash(
  21829. const Hash *pH, /* The pH to be searched */
  21830. const char *pKey, /* The key we are searching for */
  21831. int nKey, /* Bytes in key (not counting zero terminator) */
  21832. unsigned int h /* The hash for this key. */
  21833. ){
  21834. HashElem *elem; /* Used to loop thru the element list */
  21835. int count; /* Number of elements left to test */
  21836. if( pH->ht ){
  21837. struct _ht *pEntry = &pH->ht[h];
  21838. elem = pEntry->chain;
  21839. count = pEntry->count;
  21840. }else{
  21841. elem = pH->first;
  21842. count = pH->count;
  21843. }
  21844. while( count-- && ALWAYS(elem) ){
  21845. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21846. return elem;
  21847. }
  21848. elem = elem->next;
  21849. }
  21850. return 0;
  21851. }
  21852. /* Remove a single entry from the hash table given a pointer to that
  21853. ** element and a hash on the element's key.
  21854. */
  21855. static void removeElementGivenHash(
  21856. Hash *pH, /* The pH containing "elem" */
  21857. HashElem* elem, /* The element to be removed from the pH */
  21858. unsigned int h /* Hash value for the element */
  21859. ){
  21860. struct _ht *pEntry;
  21861. if( elem->prev ){
  21862. elem->prev->next = elem->next;
  21863. }else{
  21864. pH->first = elem->next;
  21865. }
  21866. if( elem->next ){
  21867. elem->next->prev = elem->prev;
  21868. }
  21869. if( pH->ht ){
  21870. pEntry = &pH->ht[h];
  21871. if( pEntry->chain==elem ){
  21872. pEntry->chain = elem->next;
  21873. }
  21874. pEntry->count--;
  21875. assert( pEntry->count>=0 );
  21876. }
  21877. sqlite3_free( elem );
  21878. pH->count--;
  21879. if( pH->count==0 ){
  21880. assert( pH->first==0 );
  21881. assert( pH->count==0 );
  21882. sqlite3HashClear(pH);
  21883. }
  21884. }
  21885. /* Attempt to locate an element of the hash table pH with a key
  21886. ** that matches pKey,nKey. Return the data for this element if it is
  21887. ** found, or NULL if there is no match.
  21888. */
  21889. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21890. HashElem *elem; /* The element that matches key */
  21891. unsigned int h; /* A hash on key */
  21892. assert( pH!=0 );
  21893. assert( pKey!=0 );
  21894. assert( nKey>=0 );
  21895. if( pH->ht ){
  21896. h = strHash(pKey, nKey) % pH->htsize;
  21897. }else{
  21898. h = 0;
  21899. }
  21900. elem = findElementGivenHash(pH, pKey, nKey, h);
  21901. return elem ? elem->data : 0;
  21902. }
  21903. /* Insert an element into the hash table pH. The key is pKey,nKey
  21904. ** and the data is "data".
  21905. **
  21906. ** If no element exists with a matching key, then a new
  21907. ** element is created and NULL is returned.
  21908. **
  21909. ** If another element already exists with the same key, then the
  21910. ** new data replaces the old data and the old data is returned.
  21911. ** The key is not copied in this instance. If a malloc fails, then
  21912. ** the new data is returned and the hash table is unchanged.
  21913. **
  21914. ** If the "data" parameter to this function is NULL, then the
  21915. ** element corresponding to "key" is removed from the hash table.
  21916. */
  21917. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21918. unsigned int h; /* the hash of the key modulo hash table size */
  21919. HashElem *elem; /* Used to loop thru the element list */
  21920. HashElem *new_elem; /* New element added to the pH */
  21921. assert( pH!=0 );
  21922. assert( pKey!=0 );
  21923. assert( nKey>=0 );
  21924. if( pH->htsize ){
  21925. h = strHash(pKey, nKey) % pH->htsize;
  21926. }else{
  21927. h = 0;
  21928. }
  21929. elem = findElementGivenHash(pH,pKey,nKey,h);
  21930. if( elem ){
  21931. void *old_data = elem->data;
  21932. if( data==0 ){
  21933. removeElementGivenHash(pH,elem,h);
  21934. }else{
  21935. elem->data = data;
  21936. elem->pKey = pKey;
  21937. assert(nKey==elem->nKey);
  21938. }
  21939. return old_data;
  21940. }
  21941. if( data==0 ) return 0;
  21942. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21943. if( new_elem==0 ) return data;
  21944. new_elem->pKey = pKey;
  21945. new_elem->nKey = nKey;
  21946. new_elem->data = data;
  21947. pH->count++;
  21948. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21949. if( rehash(pH, pH->count*2) ){
  21950. assert( pH->htsize>0 );
  21951. h = strHash(pKey, nKey) % pH->htsize;
  21952. }
  21953. }
  21954. if( pH->ht ){
  21955. insertElement(pH, &pH->ht[h], new_elem);
  21956. }else{
  21957. insertElement(pH, 0, new_elem);
  21958. }
  21959. return 0;
  21960. }
  21961. /************** End of hash.c ************************************************/
  21962. /************** Begin file opcodes.c *****************************************/
  21963. /* Automatically generated. Do not edit */
  21964. /* See the mkopcodec.awk script for details. */
  21965. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21966. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21967. static const char *const azName[] = { "?",
  21968. /* 1 */ "Function",
  21969. /* 2 */ "Savepoint",
  21970. /* 3 */ "AutoCommit",
  21971. /* 4 */ "Transaction",
  21972. /* 5 */ "SorterNext",
  21973. /* 6 */ "Prev",
  21974. /* 7 */ "Next",
  21975. /* 8 */ "AggStep",
  21976. /* 9 */ "Checkpoint",
  21977. /* 10 */ "JournalMode",
  21978. /* 11 */ "Vacuum",
  21979. /* 12 */ "VFilter",
  21980. /* 13 */ "VUpdate",
  21981. /* 14 */ "Goto",
  21982. /* 15 */ "Gosub",
  21983. /* 16 */ "Return",
  21984. /* 17 */ "Yield",
  21985. /* 18 */ "HaltIfNull",
  21986. /* 19 */ "Not",
  21987. /* 20 */ "Halt",
  21988. /* 21 */ "Integer",
  21989. /* 22 */ "Int64",
  21990. /* 23 */ "String",
  21991. /* 24 */ "Null",
  21992. /* 25 */ "Blob",
  21993. /* 26 */ "Variable",
  21994. /* 27 */ "Move",
  21995. /* 28 */ "Copy",
  21996. /* 29 */ "SCopy",
  21997. /* 30 */ "ResultRow",
  21998. /* 31 */ "CollSeq",
  21999. /* 32 */ "AddImm",
  22000. /* 33 */ "MustBeInt",
  22001. /* 34 */ "RealAffinity",
  22002. /* 35 */ "Permutation",
  22003. /* 36 */ "Compare",
  22004. /* 37 */ "Jump",
  22005. /* 38 */ "Once",
  22006. /* 39 */ "If",
  22007. /* 40 */ "IfNot",
  22008. /* 41 */ "Column",
  22009. /* 42 */ "Affinity",
  22010. /* 43 */ "MakeRecord",
  22011. /* 44 */ "Count",
  22012. /* 45 */ "ReadCookie",
  22013. /* 46 */ "SetCookie",
  22014. /* 47 */ "VerifyCookie",
  22015. /* 48 */ "OpenRead",
  22016. /* 49 */ "OpenWrite",
  22017. /* 50 */ "OpenAutoindex",
  22018. /* 51 */ "OpenEphemeral",
  22019. /* 52 */ "SorterOpen",
  22020. /* 53 */ "OpenPseudo",
  22021. /* 54 */ "Close",
  22022. /* 55 */ "SeekLt",
  22023. /* 56 */ "SeekLe",
  22024. /* 57 */ "SeekGe",
  22025. /* 58 */ "SeekGt",
  22026. /* 59 */ "Seek",
  22027. /* 60 */ "NotFound",
  22028. /* 61 */ "Found",
  22029. /* 62 */ "IsUnique",
  22030. /* 63 */ "NotExists",
  22031. /* 64 */ "Sequence",
  22032. /* 65 */ "NewRowid",
  22033. /* 66 */ "Insert",
  22034. /* 67 */ "InsertInt",
  22035. /* 68 */ "Or",
  22036. /* 69 */ "And",
  22037. /* 70 */ "Delete",
  22038. /* 71 */ "ResetCount",
  22039. /* 72 */ "SorterCompare",
  22040. /* 73 */ "IsNull",
  22041. /* 74 */ "NotNull",
  22042. /* 75 */ "Ne",
  22043. /* 76 */ "Eq",
  22044. /* 77 */ "Gt",
  22045. /* 78 */ "Le",
  22046. /* 79 */ "Lt",
  22047. /* 80 */ "Ge",
  22048. /* 81 */ "SorterData",
  22049. /* 82 */ "BitAnd",
  22050. /* 83 */ "BitOr",
  22051. /* 84 */ "ShiftLeft",
  22052. /* 85 */ "ShiftRight",
  22053. /* 86 */ "Add",
  22054. /* 87 */ "Subtract",
  22055. /* 88 */ "Multiply",
  22056. /* 89 */ "Divide",
  22057. /* 90 */ "Remainder",
  22058. /* 91 */ "Concat",
  22059. /* 92 */ "RowKey",
  22060. /* 93 */ "BitNot",
  22061. /* 94 */ "String8",
  22062. /* 95 */ "RowData",
  22063. /* 96 */ "Rowid",
  22064. /* 97 */ "NullRow",
  22065. /* 98 */ "Last",
  22066. /* 99 */ "SorterSort",
  22067. /* 100 */ "Sort",
  22068. /* 101 */ "Rewind",
  22069. /* 102 */ "SorterInsert",
  22070. /* 103 */ "IdxInsert",
  22071. /* 104 */ "IdxDelete",
  22072. /* 105 */ "IdxRowid",
  22073. /* 106 */ "IdxLT",
  22074. /* 107 */ "IdxGE",
  22075. /* 108 */ "Destroy",
  22076. /* 109 */ "Clear",
  22077. /* 110 */ "CreateIndex",
  22078. /* 111 */ "CreateTable",
  22079. /* 112 */ "ParseSchema",
  22080. /* 113 */ "LoadAnalysis",
  22081. /* 114 */ "DropTable",
  22082. /* 115 */ "DropIndex",
  22083. /* 116 */ "DropTrigger",
  22084. /* 117 */ "IntegrityCk",
  22085. /* 118 */ "RowSetAdd",
  22086. /* 119 */ "RowSetRead",
  22087. /* 120 */ "RowSetTest",
  22088. /* 121 */ "Program",
  22089. /* 122 */ "Param",
  22090. /* 123 */ "FkCounter",
  22091. /* 124 */ "FkIfZero",
  22092. /* 125 */ "MemMax",
  22093. /* 126 */ "IfPos",
  22094. /* 127 */ "IfNeg",
  22095. /* 128 */ "IfZero",
  22096. /* 129 */ "AggFinal",
  22097. /* 130 */ "Real",
  22098. /* 131 */ "IncrVacuum",
  22099. /* 132 */ "Expire",
  22100. /* 133 */ "TableLock",
  22101. /* 134 */ "VBegin",
  22102. /* 135 */ "VCreate",
  22103. /* 136 */ "VDestroy",
  22104. /* 137 */ "VOpen",
  22105. /* 138 */ "VColumn",
  22106. /* 139 */ "VNext",
  22107. /* 140 */ "VRename",
  22108. /* 141 */ "ToText",
  22109. /* 142 */ "ToBlob",
  22110. /* 143 */ "ToNumeric",
  22111. /* 144 */ "ToInt",
  22112. /* 145 */ "ToReal",
  22113. /* 146 */ "Pagecount",
  22114. /* 147 */ "MaxPgcnt",
  22115. /* 148 */ "Trace",
  22116. /* 149 */ "Noop",
  22117. /* 150 */ "Explain",
  22118. };
  22119. return azName[i];
  22120. }
  22121. #endif
  22122. /************** End of opcodes.c *********************************************/
  22123. /************** Begin file os_unix.c *****************************************/
  22124. /*
  22125. ** 2004 May 22
  22126. **
  22127. ** The author disclaims copyright to this source code. In place of
  22128. ** a legal notice, here is a blessing:
  22129. **
  22130. ** May you do good and not evil.
  22131. ** May you find forgiveness for yourself and forgive others.
  22132. ** May you share freely, never taking more than you give.
  22133. **
  22134. ******************************************************************************
  22135. **
  22136. ** This file contains the VFS implementation for unix-like operating systems
  22137. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  22138. **
  22139. ** There are actually several different VFS implementations in this file.
  22140. ** The differences are in the way that file locking is done. The default
  22141. ** implementation uses Posix Advisory Locks. Alternative implementations
  22142. ** use flock(), dot-files, various proprietary locking schemas, or simply
  22143. ** skip locking all together.
  22144. **
  22145. ** This source file is organized into divisions where the logic for various
  22146. ** subfunctions is contained within the appropriate division. PLEASE
  22147. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  22148. ** in the correct division and should be clearly labeled.
  22149. **
  22150. ** The layout of divisions is as follows:
  22151. **
  22152. ** * General-purpose declarations and utility functions.
  22153. ** * Unique file ID logic used by VxWorks.
  22154. ** * Various locking primitive implementations (all except proxy locking):
  22155. ** + for Posix Advisory Locks
  22156. ** + for no-op locks
  22157. ** + for dot-file locks
  22158. ** + for flock() locking
  22159. ** + for named semaphore locks (VxWorks only)
  22160. ** + for AFP filesystem locks (MacOSX only)
  22161. ** * sqlite3_file methods not associated with locking.
  22162. ** * Definitions of sqlite3_io_methods objects for all locking
  22163. ** methods plus "finder" functions for each locking method.
  22164. ** * sqlite3_vfs method implementations.
  22165. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  22166. ** * Definitions of sqlite3_vfs objects for all locking methods
  22167. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  22168. */
  22169. #if SQLITE_OS_UNIX /* This file is used on unix only */
  22170. /*
  22171. ** There are various methods for file locking used for concurrency
  22172. ** control:
  22173. **
  22174. ** 1. POSIX locking (the default),
  22175. ** 2. No locking,
  22176. ** 3. Dot-file locking,
  22177. ** 4. flock() locking,
  22178. ** 5. AFP locking (OSX only),
  22179. ** 6. Named POSIX semaphores (VXWorks only),
  22180. ** 7. proxy locking. (OSX only)
  22181. **
  22182. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  22183. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  22184. ** selection of the appropriate locking style based on the filesystem
  22185. ** where the database is located.
  22186. */
  22187. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  22188. # if defined(__APPLE__)
  22189. # define SQLITE_ENABLE_LOCKING_STYLE 1
  22190. # else
  22191. # define SQLITE_ENABLE_LOCKING_STYLE 0
  22192. # endif
  22193. #endif
  22194. /*
  22195. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  22196. ** vxworks, or 0 otherwise.
  22197. */
  22198. #ifndef OS_VXWORKS
  22199. # if defined(__RTP__) || defined(_WRS_KERNEL)
  22200. # define OS_VXWORKS 1
  22201. # else
  22202. # define OS_VXWORKS 0
  22203. # endif
  22204. #endif
  22205. /*
  22206. ** These #defines should enable >2GB file support on Posix if the
  22207. ** underlying operating system supports it. If the OS lacks
  22208. ** large file support, these should be no-ops.
  22209. **
  22210. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  22211. ** on the compiler command line. This is necessary if you are compiling
  22212. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  22213. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  22214. ** without this option, LFS is enable. But LFS does not exist in the kernel
  22215. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  22216. ** portability you should omit LFS.
  22217. **
  22218. ** The previous paragraph was written in 2005. (This paragraph is written
  22219. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  22220. ** you should probably leave LFS enabled. But some embedded platforms might
  22221. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  22222. */
  22223. #ifndef SQLITE_DISABLE_LFS
  22224. # define _LARGE_FILE 1
  22225. # ifndef _FILE_OFFSET_BITS
  22226. # define _FILE_OFFSET_BITS 64
  22227. # endif
  22228. # define _LARGEFILE_SOURCE 1
  22229. #endif
  22230. /*
  22231. ** standard include files.
  22232. */
  22233. #include <sys/types.h>
  22234. #include <sys/stat.h>
  22235. #include <fcntl.h>
  22236. #include <unistd.h>
  22237. /* #include <time.h> */
  22238. #include <sys/time.h>
  22239. #include <errno.h>
  22240. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  22241. #include <sys/mman.h>
  22242. #endif
  22243. #if SQLITE_ENABLE_LOCKING_STYLE
  22244. # include <sys/ioctl.h>
  22245. # if OS_VXWORKS
  22246. # include <semaphore.h>
  22247. # include <limits.h>
  22248. # else
  22249. # include <sys/file.h>
  22250. # include <sys/param.h>
  22251. # endif
  22252. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  22253. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  22254. # include <sys/mount.h>
  22255. #endif
  22256. #ifdef HAVE_UTIME
  22257. # include <utime.h>
  22258. #endif
  22259. /*
  22260. ** Allowed values of unixFile.fsFlags
  22261. */
  22262. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  22263. /*
  22264. ** If we are to be thread-safe, include the pthreads header and define
  22265. ** the SQLITE_UNIX_THREADS macro.
  22266. */
  22267. #if SQLITE_THREADSAFE
  22268. /* # include <pthread.h> */
  22269. # define SQLITE_UNIX_THREADS 1
  22270. #endif
  22271. /*
  22272. ** Default permissions when creating a new file
  22273. */
  22274. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  22275. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  22276. #endif
  22277. /*
  22278. ** Default permissions when creating auto proxy dir
  22279. */
  22280. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  22281. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  22282. #endif
  22283. /*
  22284. ** Maximum supported path-length.
  22285. */
  22286. #define MAX_PATHNAME 512
  22287. /*
  22288. ** Only set the lastErrno if the error code is a real error and not
  22289. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  22290. */
  22291. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  22292. /* Forward references */
  22293. typedef struct unixShm unixShm; /* Connection shared memory */
  22294. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  22295. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  22296. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  22297. /*
  22298. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  22299. ** cannot be closed immediately. In these cases, instances of the following
  22300. ** structure are used to store the file descriptor while waiting for an
  22301. ** opportunity to either close or reuse it.
  22302. */
  22303. struct UnixUnusedFd {
  22304. int fd; /* File descriptor to close */
  22305. int flags; /* Flags this file descriptor was opened with */
  22306. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  22307. };
  22308. /*
  22309. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  22310. ** VFS implementations.
  22311. */
  22312. typedef struct unixFile unixFile;
  22313. struct unixFile {
  22314. sqlite3_io_methods const *pMethod; /* Always the first entry */
  22315. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  22316. unixInodeInfo *pInode; /* Info about locks on this inode */
  22317. int h; /* The file descriptor */
  22318. unsigned char eFileLock; /* The type of lock held on this fd */
  22319. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  22320. int lastErrno; /* The unix errno from last I/O error */
  22321. void *lockingContext; /* Locking style specific state */
  22322. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  22323. const char *zPath; /* Name of the file */
  22324. unixShm *pShm; /* Shared memory segment information */
  22325. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  22326. #if SQLITE_MAX_MMAP_SIZE>0
  22327. int nFetchOut; /* Number of outstanding xFetch refs */
  22328. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  22329. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  22330. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  22331. void *pMapRegion; /* Memory mapped region */
  22332. #endif
  22333. #ifdef __QNXNTO__
  22334. int sectorSize; /* Device sector size */
  22335. int deviceCharacteristics; /* Precomputed device characteristics */
  22336. #endif
  22337. #if SQLITE_ENABLE_LOCKING_STYLE
  22338. int openFlags; /* The flags specified at open() */
  22339. #endif
  22340. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  22341. unsigned fsFlags; /* cached details from statfs() */
  22342. #endif
  22343. #if OS_VXWORKS
  22344. struct vxworksFileId *pId; /* Unique file ID */
  22345. #endif
  22346. #ifdef SQLITE_DEBUG
  22347. /* The next group of variables are used to track whether or not the
  22348. ** transaction counter in bytes 24-27 of database files are updated
  22349. ** whenever any part of the database changes. An assertion fault will
  22350. ** occur if a file is updated without also updating the transaction
  22351. ** counter. This test is made to avoid new problems similar to the
  22352. ** one described by ticket #3584.
  22353. */
  22354. unsigned char transCntrChng; /* True if the transaction counter changed */
  22355. unsigned char dbUpdate; /* True if any part of database file changed */
  22356. unsigned char inNormalWrite; /* True if in a normal write operation */
  22357. #endif
  22358. #ifdef SQLITE_TEST
  22359. /* In test mode, increase the size of this structure a bit so that
  22360. ** it is larger than the struct CrashFile defined in test6.c.
  22361. */
  22362. char aPadding[32];
  22363. #endif
  22364. };
  22365. /*
  22366. ** Allowed values for the unixFile.ctrlFlags bitmask:
  22367. */
  22368. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  22369. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  22370. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  22371. #ifndef SQLITE_DISABLE_DIRSYNC
  22372. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  22373. #else
  22374. # define UNIXFILE_DIRSYNC 0x00
  22375. #endif
  22376. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  22377. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  22378. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  22379. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  22380. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  22381. /*
  22382. ** Include code that is common to all os_*.c files
  22383. */
  22384. /************** Include os_common.h in the middle of os_unix.c ***************/
  22385. /************** Begin file os_common.h ***************************************/
  22386. /*
  22387. ** 2004 May 22
  22388. **
  22389. ** The author disclaims copyright to this source code. In place of
  22390. ** a legal notice, here is a blessing:
  22391. **
  22392. ** May you do good and not evil.
  22393. ** May you find forgiveness for yourself and forgive others.
  22394. ** May you share freely, never taking more than you give.
  22395. **
  22396. ******************************************************************************
  22397. **
  22398. ** This file contains macros and a little bit of code that is common to
  22399. ** all of the platform-specific files (os_*.c) and is #included into those
  22400. ** files.
  22401. **
  22402. ** This file should be #included by the os_*.c files only. It is not a
  22403. ** general purpose header file.
  22404. */
  22405. #ifndef _OS_COMMON_H_
  22406. #define _OS_COMMON_H_
  22407. /*
  22408. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22409. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22410. ** switch. The following code should catch this problem at compile-time.
  22411. */
  22412. #ifdef MEMORY_DEBUG
  22413. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22414. #endif
  22415. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22416. # ifndef SQLITE_DEBUG_OS_TRACE
  22417. # define SQLITE_DEBUG_OS_TRACE 0
  22418. # endif
  22419. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  22420. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  22421. #else
  22422. # define OSTRACE(X)
  22423. #endif
  22424. /*
  22425. ** Macros for performance tracing. Normally turned off. Only works
  22426. ** on i486 hardware.
  22427. */
  22428. #ifdef SQLITE_PERFORMANCE_TRACE
  22429. /*
  22430. ** hwtime.h contains inline assembler code for implementing
  22431. ** high-performance timing routines.
  22432. */
  22433. /************** Include hwtime.h in the middle of os_common.h ****************/
  22434. /************** Begin file hwtime.h ******************************************/
  22435. /*
  22436. ** 2008 May 27
  22437. **
  22438. ** The author disclaims copyright to this source code. In place of
  22439. ** a legal notice, here is a blessing:
  22440. **
  22441. ** May you do good and not evil.
  22442. ** May you find forgiveness for yourself and forgive others.
  22443. ** May you share freely, never taking more than you give.
  22444. **
  22445. ******************************************************************************
  22446. **
  22447. ** This file contains inline asm code for retrieving "high-performance"
  22448. ** counters for x86 class CPUs.
  22449. */
  22450. #ifndef _HWTIME_H_
  22451. #define _HWTIME_H_
  22452. /*
  22453. ** The following routine only works on pentium-class (or newer) processors.
  22454. ** It uses the RDTSC opcode to read the cycle count value out of the
  22455. ** processor and returns that value. This can be used for high-res
  22456. ** profiling.
  22457. */
  22458. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22459. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22460. #if defined(__GNUC__)
  22461. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22462. unsigned int lo, hi;
  22463. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22464. return (sqlite_uint64)hi << 32 | lo;
  22465. }
  22466. #elif defined(_MSC_VER)
  22467. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22468. __asm {
  22469. rdtsc
  22470. ret ; return value at EDX:EAX
  22471. }
  22472. }
  22473. #endif
  22474. #elif (defined(__GNUC__) && defined(__x86_64__))
  22475. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22476. unsigned long val;
  22477. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22478. return val;
  22479. }
  22480. #elif (defined(__GNUC__) && defined(__ppc__))
  22481. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22482. unsigned long long retval;
  22483. unsigned long junk;
  22484. __asm__ __volatile__ ("\n\
  22485. 1: mftbu %1\n\
  22486. mftb %L0\n\
  22487. mftbu %0\n\
  22488. cmpw %0,%1\n\
  22489. bne 1b"
  22490. : "=r" (retval), "=r" (junk));
  22491. return retval;
  22492. }
  22493. #else
  22494. #error Need implementation of sqlite3Hwtime() for your platform.
  22495. /*
  22496. ** To compile without implementing sqlite3Hwtime() for your platform,
  22497. ** you can remove the above #error and use the following
  22498. ** stub function. You will lose timing support for many
  22499. ** of the debugging and testing utilities, but it should at
  22500. ** least compile and run.
  22501. */
  22502. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22503. #endif
  22504. #endif /* !defined(_HWTIME_H_) */
  22505. /************** End of hwtime.h **********************************************/
  22506. /************** Continuing where we left off in os_common.h ******************/
  22507. static sqlite_uint64 g_start;
  22508. static sqlite_uint64 g_elapsed;
  22509. #define TIMER_START g_start=sqlite3Hwtime()
  22510. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22511. #define TIMER_ELAPSED g_elapsed
  22512. #else
  22513. #define TIMER_START
  22514. #define TIMER_END
  22515. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22516. #endif
  22517. /*
  22518. ** If we compile with the SQLITE_TEST macro set, then the following block
  22519. ** of code will give us the ability to simulate a disk I/O error. This
  22520. ** is used for testing the I/O recovery logic.
  22521. */
  22522. #ifdef SQLITE_TEST
  22523. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  22524. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  22525. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  22526. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  22527. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  22528. SQLITE_API int sqlite3_diskfull_pending = 0;
  22529. SQLITE_API int sqlite3_diskfull = 0;
  22530. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22531. #define SimulateIOError(CODE) \
  22532. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22533. || sqlite3_io_error_pending-- == 1 ) \
  22534. { local_ioerr(); CODE; }
  22535. static void local_ioerr(){
  22536. IOTRACE(("IOERR\n"));
  22537. sqlite3_io_error_hit++;
  22538. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22539. }
  22540. #define SimulateDiskfullError(CODE) \
  22541. if( sqlite3_diskfull_pending ){ \
  22542. if( sqlite3_diskfull_pending == 1 ){ \
  22543. local_ioerr(); \
  22544. sqlite3_diskfull = 1; \
  22545. sqlite3_io_error_hit = 1; \
  22546. CODE; \
  22547. }else{ \
  22548. sqlite3_diskfull_pending--; \
  22549. } \
  22550. }
  22551. #else
  22552. #define SimulateIOErrorBenign(X)
  22553. #define SimulateIOError(A)
  22554. #define SimulateDiskfullError(A)
  22555. #endif
  22556. /*
  22557. ** When testing, keep a count of the number of open files.
  22558. */
  22559. #ifdef SQLITE_TEST
  22560. SQLITE_API int sqlite3_open_file_count = 0;
  22561. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22562. #else
  22563. #define OpenCounter(X)
  22564. #endif
  22565. #endif /* !defined(_OS_COMMON_H_) */
  22566. /************** End of os_common.h *******************************************/
  22567. /************** Continuing where we left off in os_unix.c ********************/
  22568. /*
  22569. ** Define various macros that are missing from some systems.
  22570. */
  22571. #ifndef O_LARGEFILE
  22572. # define O_LARGEFILE 0
  22573. #endif
  22574. #ifdef SQLITE_DISABLE_LFS
  22575. # undef O_LARGEFILE
  22576. # define O_LARGEFILE 0
  22577. #endif
  22578. #ifndef O_NOFOLLOW
  22579. # define O_NOFOLLOW 0
  22580. #endif
  22581. #ifndef O_BINARY
  22582. # define O_BINARY 0
  22583. #endif
  22584. /*
  22585. ** The threadid macro resolves to the thread-id or to 0. Used for
  22586. ** testing and debugging only.
  22587. */
  22588. #if SQLITE_THREADSAFE
  22589. #define threadid pthread_self()
  22590. #else
  22591. #define threadid 0
  22592. #endif
  22593. /*
  22594. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  22595. */
  22596. #if !defined(HAVE_MREMAP)
  22597. # if defined(__linux__) && defined(_GNU_SOURCE)
  22598. # define HAVE_MREMAP 1
  22599. # else
  22600. # define HAVE_MREMAP 0
  22601. # endif
  22602. #endif
  22603. /*
  22604. ** Different Unix systems declare open() in different ways. Same use
  22605. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  22606. ** The difference is important when using a pointer to the function.
  22607. **
  22608. ** The safest way to deal with the problem is to always use this wrapper
  22609. ** which always has the same well-defined interface.
  22610. */
  22611. static int posixOpen(const char *zFile, int flags, int mode){
  22612. return open(zFile, flags, mode);
  22613. }
  22614. /*
  22615. ** On some systems, calls to fchown() will trigger a message in a security
  22616. ** log if they come from non-root processes. So avoid calling fchown() if
  22617. ** we are not running as root.
  22618. */
  22619. static int posixFchown(int fd, uid_t uid, gid_t gid){
  22620. return geteuid() ? 0 : fchown(fd,uid,gid);
  22621. }
  22622. /* Forward reference */
  22623. static int openDirectory(const char*, int*);
  22624. /*
  22625. ** Many system calls are accessed through pointer-to-functions so that
  22626. ** they may be overridden at runtime to facilitate fault injection during
  22627. ** testing and sandboxing. The following array holds the names and pointers
  22628. ** to all overrideable system calls.
  22629. */
  22630. static struct unix_syscall {
  22631. const char *zName; /* Name of the system call */
  22632. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  22633. sqlite3_syscall_ptr pDefault; /* Default value */
  22634. } aSyscall[] = {
  22635. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  22636. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  22637. { "close", (sqlite3_syscall_ptr)close, 0 },
  22638. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22639. { "access", (sqlite3_syscall_ptr)access, 0 },
  22640. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22641. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22642. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22643. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22644. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22645. /*
  22646. ** The DJGPP compiler environment looks mostly like Unix, but it
  22647. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22648. ** that always succeeds. This means that locking does not occur under
  22649. ** DJGPP. But it is DOS - what did you expect?
  22650. */
  22651. #ifdef __DJGPP__
  22652. { "fstat", 0, 0 },
  22653. #define osFstat(a,b,c) 0
  22654. #else
  22655. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22656. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  22657. #endif
  22658. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  22659. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  22660. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  22661. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  22662. { "read", (sqlite3_syscall_ptr)read, 0 },
  22663. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  22664. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22665. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  22666. #else
  22667. { "pread", (sqlite3_syscall_ptr)0, 0 },
  22668. #endif
  22669. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  22670. #if defined(USE_PREAD64)
  22671. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  22672. #else
  22673. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  22674. #endif
  22675. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  22676. { "write", (sqlite3_syscall_ptr)write, 0 },
  22677. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  22678. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22679. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  22680. #else
  22681. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  22682. #endif
  22683. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  22684. aSyscall[12].pCurrent)
  22685. #if defined(USE_PREAD64)
  22686. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  22687. #else
  22688. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  22689. #endif
  22690. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  22691. aSyscall[13].pCurrent)
  22692. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  22693. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  22694. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  22695. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  22696. #else
  22697. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  22698. #endif
  22699. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  22700. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  22701. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  22702. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  22703. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  22704. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  22705. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  22706. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  22707. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  22708. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  22709. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  22710. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  22711. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  22712. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  22713. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  22714. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  22715. #if HAVE_MREMAP
  22716. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  22717. #else
  22718. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  22719. #endif
  22720. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  22721. #endif
  22722. }; /* End of the overrideable system calls */
  22723. /*
  22724. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22725. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  22726. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22727. ** system call named zName.
  22728. */
  22729. static int unixSetSystemCall(
  22730. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22731. const char *zName, /* Name of system call to override */
  22732. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22733. ){
  22734. unsigned int i;
  22735. int rc = SQLITE_NOTFOUND;
  22736. UNUSED_PARAMETER(pNotUsed);
  22737. if( zName==0 ){
  22738. /* If no zName is given, restore all system calls to their default
  22739. ** settings and return NULL
  22740. */
  22741. rc = SQLITE_OK;
  22742. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22743. if( aSyscall[i].pDefault ){
  22744. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22745. }
  22746. }
  22747. }else{
  22748. /* If zName is specified, operate on only the one system call
  22749. ** specified.
  22750. */
  22751. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22752. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22753. if( aSyscall[i].pDefault==0 ){
  22754. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22755. }
  22756. rc = SQLITE_OK;
  22757. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22758. aSyscall[i].pCurrent = pNewFunc;
  22759. break;
  22760. }
  22761. }
  22762. }
  22763. return rc;
  22764. }
  22765. /*
  22766. ** Return the value of a system call. Return NULL if zName is not a
  22767. ** recognized system call name. NULL is also returned if the system call
  22768. ** is currently undefined.
  22769. */
  22770. static sqlite3_syscall_ptr unixGetSystemCall(
  22771. sqlite3_vfs *pNotUsed,
  22772. const char *zName
  22773. ){
  22774. unsigned int i;
  22775. UNUSED_PARAMETER(pNotUsed);
  22776. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22777. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22778. }
  22779. return 0;
  22780. }
  22781. /*
  22782. ** Return the name of the first system call after zName. If zName==NULL
  22783. ** then return the name of the first system call. Return NULL if zName
  22784. ** is the last system call or if zName is not the name of a valid
  22785. ** system call.
  22786. */
  22787. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  22788. int i = -1;
  22789. UNUSED_PARAMETER(p);
  22790. if( zName ){
  22791. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22792. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22793. }
  22794. }
  22795. for(i++; i<ArraySize(aSyscall); i++){
  22796. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22797. }
  22798. return 0;
  22799. }
  22800. /*
  22801. ** Do not accept any file descriptor less than this value, in order to avoid
  22802. ** opening database file using file descriptors that are commonly used for
  22803. ** standard input, output, and error.
  22804. */
  22805. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  22806. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  22807. #endif
  22808. /*
  22809. ** Invoke open(). Do so multiple times, until it either succeeds or
  22810. ** fails for some reason other than EINTR.
  22811. **
  22812. ** If the file creation mode "m" is 0 then set it to the default for
  22813. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22814. ** 0644) as modified by the system umask. If m is not 0, then
  22815. ** make the file creation mode be exactly m ignoring the umask.
  22816. **
  22817. ** The m parameter will be non-zero only when creating -wal, -journal,
  22818. ** and -shm files. We want those files to have *exactly* the same
  22819. ** permissions as their original database, unadulterated by the umask.
  22820. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22821. ** transaction crashes and leaves behind hot journals, then any
  22822. ** process that is able to write to the database will also be able to
  22823. ** recover the hot journals.
  22824. */
  22825. static int robust_open(const char *z, int f, mode_t m){
  22826. int fd;
  22827. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  22828. while(1){
  22829. #if defined(O_CLOEXEC)
  22830. fd = osOpen(z,f|O_CLOEXEC,m2);
  22831. #else
  22832. fd = osOpen(z,f,m2);
  22833. #endif
  22834. if( fd<0 ){
  22835. if( errno==EINTR ) continue;
  22836. break;
  22837. }
  22838. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  22839. osClose(fd);
  22840. sqlite3_log(SQLITE_WARNING,
  22841. "attempt to open \"%s\" as file descriptor %d", z, fd);
  22842. fd = -1;
  22843. if( osOpen("/dev/null", f, m)<0 ) break;
  22844. }
  22845. if( fd>=0 ){
  22846. if( m!=0 ){
  22847. struct stat statbuf;
  22848. if( osFstat(fd, &statbuf)==0
  22849. && statbuf.st_size==0
  22850. && (statbuf.st_mode&0777)!=m
  22851. ){
  22852. osFchmod(fd, m);
  22853. }
  22854. }
  22855. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  22856. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22857. #endif
  22858. }
  22859. return fd;
  22860. }
  22861. /*
  22862. ** Helper functions to obtain and relinquish the global mutex. The
  22863. ** global mutex is used to protect the unixInodeInfo and
  22864. ** vxworksFileId objects used by this file, all of which may be
  22865. ** shared by multiple threads.
  22866. **
  22867. ** Function unixMutexHeld() is used to assert() that the global mutex
  22868. ** is held when required. This function is only used as part of assert()
  22869. ** statements. e.g.
  22870. **
  22871. ** unixEnterMutex()
  22872. ** assert( unixMutexHeld() );
  22873. ** unixEnterLeave()
  22874. */
  22875. static void unixEnterMutex(void){
  22876. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22877. }
  22878. static void unixLeaveMutex(void){
  22879. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22880. }
  22881. #ifdef SQLITE_DEBUG
  22882. static int unixMutexHeld(void) {
  22883. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22884. }
  22885. #endif
  22886. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22887. /*
  22888. ** Helper function for printing out trace information from debugging
  22889. ** binaries. This returns the string represetation of the supplied
  22890. ** integer lock-type.
  22891. */
  22892. static const char *azFileLock(int eFileLock){
  22893. switch( eFileLock ){
  22894. case NO_LOCK: return "NONE";
  22895. case SHARED_LOCK: return "SHARED";
  22896. case RESERVED_LOCK: return "RESERVED";
  22897. case PENDING_LOCK: return "PENDING";
  22898. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22899. }
  22900. return "ERROR";
  22901. }
  22902. #endif
  22903. #ifdef SQLITE_LOCK_TRACE
  22904. /*
  22905. ** Print out information about all locking operations.
  22906. **
  22907. ** This routine is used for troubleshooting locks on multithreaded
  22908. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  22909. ** command-line option on the compiler. This code is normally
  22910. ** turned off.
  22911. */
  22912. static int lockTrace(int fd, int op, struct flock *p){
  22913. char *zOpName, *zType;
  22914. int s;
  22915. int savedErrno;
  22916. if( op==F_GETLK ){
  22917. zOpName = "GETLK";
  22918. }else if( op==F_SETLK ){
  22919. zOpName = "SETLK";
  22920. }else{
  22921. s = osFcntl(fd, op, p);
  22922. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  22923. return s;
  22924. }
  22925. if( p->l_type==F_RDLCK ){
  22926. zType = "RDLCK";
  22927. }else if( p->l_type==F_WRLCK ){
  22928. zType = "WRLCK";
  22929. }else if( p->l_type==F_UNLCK ){
  22930. zType = "UNLCK";
  22931. }else{
  22932. assert( 0 );
  22933. }
  22934. assert( p->l_whence==SEEK_SET );
  22935. s = osFcntl(fd, op, p);
  22936. savedErrno = errno;
  22937. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  22938. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  22939. (int)p->l_pid, s);
  22940. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  22941. struct flock l2;
  22942. l2 = *p;
  22943. osFcntl(fd, F_GETLK, &l2);
  22944. if( l2.l_type==F_RDLCK ){
  22945. zType = "RDLCK";
  22946. }else if( l2.l_type==F_WRLCK ){
  22947. zType = "WRLCK";
  22948. }else if( l2.l_type==F_UNLCK ){
  22949. zType = "UNLCK";
  22950. }else{
  22951. assert( 0 );
  22952. }
  22953. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  22954. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  22955. }
  22956. errno = savedErrno;
  22957. return s;
  22958. }
  22959. #undef osFcntl
  22960. #define osFcntl lockTrace
  22961. #endif /* SQLITE_LOCK_TRACE */
  22962. /*
  22963. ** Retry ftruncate() calls that fail due to EINTR
  22964. */
  22965. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22966. int rc;
  22967. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  22968. return rc;
  22969. }
  22970. /*
  22971. ** This routine translates a standard POSIX errno code into something
  22972. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22973. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22974. ** and a variety of "please close the file descriptor NOW" errors into
  22975. ** SQLITE_IOERR
  22976. **
  22977. ** Errors during initialization of locks, or file system support for locks,
  22978. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22979. */
  22980. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22981. switch (posixError) {
  22982. #if 0
  22983. /* At one point this code was not commented out. In theory, this branch
  22984. ** should never be hit, as this function should only be called after
  22985. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22986. ** the value of errno as the first argument. Since a system call has failed,
  22987. ** errno should be non-zero.
  22988. **
  22989. ** Despite this, if errno really is zero, we still don't want to return
  22990. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22991. ** propagated back to the caller. Commenting this branch out means errno==0
  22992. ** will be handled by the "default:" case below.
  22993. */
  22994. case 0:
  22995. return SQLITE_OK;
  22996. #endif
  22997. case EAGAIN:
  22998. case ETIMEDOUT:
  22999. case EBUSY:
  23000. case EINTR:
  23001. case ENOLCK:
  23002. /* random NFS retry error, unless during file system support
  23003. * introspection, in which it actually means what it says */
  23004. return SQLITE_BUSY;
  23005. case EACCES:
  23006. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  23007. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  23008. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  23009. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  23010. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  23011. return SQLITE_BUSY;
  23012. }
  23013. /* else fall through */
  23014. case EPERM:
  23015. return SQLITE_PERM;
  23016. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  23017. ** this module never makes such a call. And the code in SQLite itself
  23018. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  23019. ** this case is also commented out. If the system does set errno to EDEADLK,
  23020. ** the default SQLITE_IOERR_XXX code will be returned. */
  23021. #if 0
  23022. case EDEADLK:
  23023. return SQLITE_IOERR_BLOCKED;
  23024. #endif
  23025. #if EOPNOTSUPP!=ENOTSUP
  23026. case EOPNOTSUPP:
  23027. /* something went terribly awry, unless during file system support
  23028. * introspection, in which it actually means what it says */
  23029. #endif
  23030. #ifdef ENOTSUP
  23031. case ENOTSUP:
  23032. /* invalid fd, unless during file system support introspection, in which
  23033. * it actually means what it says */
  23034. #endif
  23035. case EIO:
  23036. case EBADF:
  23037. case EINVAL:
  23038. case ENOTCONN:
  23039. case ENODEV:
  23040. case ENXIO:
  23041. case ENOENT:
  23042. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  23043. case ESTALE:
  23044. #endif
  23045. case ENOSYS:
  23046. /* these should force the client to close the file and reconnect */
  23047. default:
  23048. return sqliteIOErr;
  23049. }
  23050. }
  23051. /******************************************************************************
  23052. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  23053. **
  23054. ** On most versions of unix, we can get a unique ID for a file by concatenating
  23055. ** the device number and the inode number. But this does not work on VxWorks.
  23056. ** On VxWorks, a unique file id must be based on the canonical filename.
  23057. **
  23058. ** A pointer to an instance of the following structure can be used as a
  23059. ** unique file ID in VxWorks. Each instance of this structure contains
  23060. ** a copy of the canonical filename. There is also a reference count.
  23061. ** The structure is reclaimed when the number of pointers to it drops to
  23062. ** zero.
  23063. **
  23064. ** There are never very many files open at one time and lookups are not
  23065. ** a performance-critical path, so it is sufficient to put these
  23066. ** structures on a linked list.
  23067. */
  23068. struct vxworksFileId {
  23069. struct vxworksFileId *pNext; /* Next in a list of them all */
  23070. int nRef; /* Number of references to this one */
  23071. int nName; /* Length of the zCanonicalName[] string */
  23072. char *zCanonicalName; /* Canonical filename */
  23073. };
  23074. #if OS_VXWORKS
  23075. /*
  23076. ** All unique filenames are held on a linked list headed by this
  23077. ** variable:
  23078. */
  23079. static struct vxworksFileId *vxworksFileList = 0;
  23080. /*
  23081. ** Simplify a filename into its canonical form
  23082. ** by making the following changes:
  23083. **
  23084. ** * removing any trailing and duplicate /
  23085. ** * convert /./ into just /
  23086. ** * convert /A/../ where A is any simple name into just /
  23087. **
  23088. ** Changes are made in-place. Return the new name length.
  23089. **
  23090. ** The original filename is in z[0..n-1]. Return the number of
  23091. ** characters in the simplified name.
  23092. */
  23093. static int vxworksSimplifyName(char *z, int n){
  23094. int i, j;
  23095. while( n>1 && z[n-1]=='/' ){ n--; }
  23096. for(i=j=0; i<n; i++){
  23097. if( z[i]=='/' ){
  23098. if( z[i+1]=='/' ) continue;
  23099. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  23100. i += 1;
  23101. continue;
  23102. }
  23103. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  23104. while( j>0 && z[j-1]!='/' ){ j--; }
  23105. if( j>0 ){ j--; }
  23106. i += 2;
  23107. continue;
  23108. }
  23109. }
  23110. z[j++] = z[i];
  23111. }
  23112. z[j] = 0;
  23113. return j;
  23114. }
  23115. /*
  23116. ** Find a unique file ID for the given absolute pathname. Return
  23117. ** a pointer to the vxworksFileId object. This pointer is the unique
  23118. ** file ID.
  23119. **
  23120. ** The nRef field of the vxworksFileId object is incremented before
  23121. ** the object is returned. A new vxworksFileId object is created
  23122. ** and added to the global list if necessary.
  23123. **
  23124. ** If a memory allocation error occurs, return NULL.
  23125. */
  23126. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  23127. struct vxworksFileId *pNew; /* search key and new file ID */
  23128. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  23129. int n; /* Length of zAbsoluteName string */
  23130. assert( zAbsoluteName[0]=='/' );
  23131. n = (int)strlen(zAbsoluteName);
  23132. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  23133. if( pNew==0 ) return 0;
  23134. pNew->zCanonicalName = (char*)&pNew[1];
  23135. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  23136. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  23137. /* Search for an existing entry that matching the canonical name.
  23138. ** If found, increment the reference count and return a pointer to
  23139. ** the existing file ID.
  23140. */
  23141. unixEnterMutex();
  23142. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  23143. if( pCandidate->nName==n
  23144. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  23145. ){
  23146. sqlite3_free(pNew);
  23147. pCandidate->nRef++;
  23148. unixLeaveMutex();
  23149. return pCandidate;
  23150. }
  23151. }
  23152. /* No match was found. We will make a new file ID */
  23153. pNew->nRef = 1;
  23154. pNew->nName = n;
  23155. pNew->pNext = vxworksFileList;
  23156. vxworksFileList = pNew;
  23157. unixLeaveMutex();
  23158. return pNew;
  23159. }
  23160. /*
  23161. ** Decrement the reference count on a vxworksFileId object. Free
  23162. ** the object when the reference count reaches zero.
  23163. */
  23164. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  23165. unixEnterMutex();
  23166. assert( pId->nRef>0 );
  23167. pId->nRef--;
  23168. if( pId->nRef==0 ){
  23169. struct vxworksFileId **pp;
  23170. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  23171. assert( *pp==pId );
  23172. *pp = pId->pNext;
  23173. sqlite3_free(pId);
  23174. }
  23175. unixLeaveMutex();
  23176. }
  23177. #endif /* OS_VXWORKS */
  23178. /*************** End of Unique File ID Utility Used By VxWorks ****************
  23179. ******************************************************************************/
  23180. /******************************************************************************
  23181. *************************** Posix Advisory Locking ****************************
  23182. **
  23183. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  23184. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  23185. ** sets or clears a lock, that operation overrides any prior locks set
  23186. ** by the same process. It does not explicitly say so, but this implies
  23187. ** that it overrides locks set by the same process using a different
  23188. ** file descriptor. Consider this test case:
  23189. **
  23190. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  23191. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  23192. **
  23193. ** Suppose ./file1 and ./file2 are really the same file (because
  23194. ** one is a hard or symbolic link to the other) then if you set
  23195. ** an exclusive lock on fd1, then try to get an exclusive lock
  23196. ** on fd2, it works. I would have expected the second lock to
  23197. ** fail since there was already a lock on the file due to fd1.
  23198. ** But not so. Since both locks came from the same process, the
  23199. ** second overrides the first, even though they were on different
  23200. ** file descriptors opened on different file names.
  23201. **
  23202. ** This means that we cannot use POSIX locks to synchronize file access
  23203. ** among competing threads of the same process. POSIX locks will work fine
  23204. ** to synchronize access for threads in separate processes, but not
  23205. ** threads within the same process.
  23206. **
  23207. ** To work around the problem, SQLite has to manage file locks internally
  23208. ** on its own. Whenever a new database is opened, we have to find the
  23209. ** specific inode of the database file (the inode is determined by the
  23210. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  23211. ** and check for locks already existing on that inode. When locks are
  23212. ** created or removed, we have to look at our own internal record of the
  23213. ** locks to see if another thread has previously set a lock on that same
  23214. ** inode.
  23215. **
  23216. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  23217. ** For VxWorks, we have to use the alternative unique ID system based on
  23218. ** canonical filename and implemented in the previous division.)
  23219. **
  23220. ** The sqlite3_file structure for POSIX is no longer just an integer file
  23221. ** descriptor. It is now a structure that holds the integer file
  23222. ** descriptor and a pointer to a structure that describes the internal
  23223. ** locks on the corresponding inode. There is one locking structure
  23224. ** per inode, so if the same inode is opened twice, both unixFile structures
  23225. ** point to the same locking structure. The locking structure keeps
  23226. ** a reference count (so we will know when to delete it) and a "cnt"
  23227. ** field that tells us its internal lock status. cnt==0 means the
  23228. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  23229. ** cnt>0 means there are cnt shared locks on the file.
  23230. **
  23231. ** Any attempt to lock or unlock a file first checks the locking
  23232. ** structure. The fcntl() system call is only invoked to set a
  23233. ** POSIX lock if the internal lock structure transitions between
  23234. ** a locked and an unlocked state.
  23235. **
  23236. ** But wait: there are yet more problems with POSIX advisory locks.
  23237. **
  23238. ** If you close a file descriptor that points to a file that has locks,
  23239. ** all locks on that file that are owned by the current process are
  23240. ** released. To work around this problem, each unixInodeInfo object
  23241. ** maintains a count of the number of pending locks on tha inode.
  23242. ** When an attempt is made to close an unixFile, if there are
  23243. ** other unixFile open on the same inode that are holding locks, the call
  23244. ** to close() the file descriptor is deferred until all of the locks clear.
  23245. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  23246. ** be closed and that list is walked (and cleared) when the last lock
  23247. ** clears.
  23248. **
  23249. ** Yet another problem: LinuxThreads do not play well with posix locks.
  23250. **
  23251. ** Many older versions of linux use the LinuxThreads library which is
  23252. ** not posix compliant. Under LinuxThreads, a lock created by thread
  23253. ** A cannot be modified or overridden by a different thread B.
  23254. ** Only thread A can modify the lock. Locking behavior is correct
  23255. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  23256. ** on linux - with NPTL a lock created by thread A can override locks
  23257. ** in thread B. But there is no way to know at compile-time which
  23258. ** threading library is being used. So there is no way to know at
  23259. ** compile-time whether or not thread A can override locks on thread B.
  23260. ** One has to do a run-time check to discover the behavior of the
  23261. ** current process.
  23262. **
  23263. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  23264. ** was dropped beginning with version 3.7.0. SQLite will still work with
  23265. ** LinuxThreads provided that (1) there is no more than one connection
  23266. ** per database file in the same process and (2) database connections
  23267. ** do not move across threads.
  23268. */
  23269. /*
  23270. ** An instance of the following structure serves as the key used
  23271. ** to locate a particular unixInodeInfo object.
  23272. */
  23273. struct unixFileId {
  23274. dev_t dev; /* Device number */
  23275. #if OS_VXWORKS
  23276. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  23277. #else
  23278. ino_t ino; /* Inode number */
  23279. #endif
  23280. };
  23281. /*
  23282. ** An instance of the following structure is allocated for each open
  23283. ** inode. Or, on LinuxThreads, there is one of these structures for
  23284. ** each inode opened by each thread.
  23285. **
  23286. ** A single inode can have multiple file descriptors, so each unixFile
  23287. ** structure contains a pointer to an instance of this object and this
  23288. ** object keeps a count of the number of unixFile pointing to it.
  23289. */
  23290. struct unixInodeInfo {
  23291. struct unixFileId fileId; /* The lookup key */
  23292. int nShared; /* Number of SHARED locks held */
  23293. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  23294. unsigned char bProcessLock; /* An exclusive process lock is held */
  23295. int nRef; /* Number of pointers to this structure */
  23296. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  23297. int nLock; /* Number of outstanding file locks */
  23298. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  23299. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  23300. unixInodeInfo *pPrev; /* .... doubly linked */
  23301. #if SQLITE_ENABLE_LOCKING_STYLE
  23302. unsigned long long sharedByte; /* for AFP simulated shared lock */
  23303. #endif
  23304. #if OS_VXWORKS
  23305. sem_t *pSem; /* Named POSIX semaphore */
  23306. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  23307. #endif
  23308. };
  23309. /*
  23310. ** A lists of all unixInodeInfo objects.
  23311. */
  23312. static unixInodeInfo *inodeList = 0;
  23313. /*
  23314. **
  23315. ** This function - unixLogError_x(), is only ever called via the macro
  23316. ** unixLogError().
  23317. **
  23318. ** It is invoked after an error occurs in an OS function and errno has been
  23319. ** set. It logs a message using sqlite3_log() containing the current value of
  23320. ** errno and, if possible, the human-readable equivalent from strerror() or
  23321. ** strerror_r().
  23322. **
  23323. ** The first argument passed to the macro should be the error code that
  23324. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  23325. ** The two subsequent arguments should be the name of the OS function that
  23326. ** failed (e.g. "unlink", "open") and the associated file-system path,
  23327. ** if any.
  23328. */
  23329. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  23330. static int unixLogErrorAtLine(
  23331. int errcode, /* SQLite error code */
  23332. const char *zFunc, /* Name of OS function that failed */
  23333. const char *zPath, /* File path associated with error */
  23334. int iLine /* Source line number where error occurred */
  23335. ){
  23336. char *zErr; /* Message from strerror() or equivalent */
  23337. int iErrno = errno; /* Saved syscall error number */
  23338. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  23339. ** the strerror() function to obtain the human-readable error message
  23340. ** equivalent to errno. Otherwise, use strerror_r().
  23341. */
  23342. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  23343. char aErr[80];
  23344. memset(aErr, 0, sizeof(aErr));
  23345. zErr = aErr;
  23346. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  23347. ** assume that the system provides the GNU version of strerror_r() that
  23348. ** returns a pointer to a buffer containing the error message. That pointer
  23349. ** may point to aErr[], or it may point to some static storage somewhere.
  23350. ** Otherwise, assume that the system provides the POSIX version of
  23351. ** strerror_r(), which always writes an error message into aErr[].
  23352. **
  23353. ** If the code incorrectly assumes that it is the POSIX version that is
  23354. ** available, the error message will often be an empty string. Not a
  23355. ** huge problem. Incorrectly concluding that the GNU version is available
  23356. ** could lead to a segfault though.
  23357. */
  23358. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  23359. zErr =
  23360. # endif
  23361. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  23362. #elif SQLITE_THREADSAFE
  23363. /* This is a threadsafe build, but strerror_r() is not available. */
  23364. zErr = "";
  23365. #else
  23366. /* Non-threadsafe build, use strerror(). */
  23367. zErr = strerror(iErrno);
  23368. #endif
  23369. if( zPath==0 ) zPath = "";
  23370. sqlite3_log(errcode,
  23371. "os_unix.c:%d: (%d) %s(%s) - %s",
  23372. iLine, iErrno, zFunc, zPath, zErr
  23373. );
  23374. return errcode;
  23375. }
  23376. /*
  23377. ** Close a file descriptor.
  23378. **
  23379. ** We assume that close() almost always works, since it is only in a
  23380. ** very sick application or on a very sick platform that it might fail.
  23381. ** If it does fail, simply leak the file descriptor, but do log the
  23382. ** error.
  23383. **
  23384. ** Note that it is not safe to retry close() after EINTR since the
  23385. ** file descriptor might have already been reused by another thread.
  23386. ** So we don't even try to recover from an EINTR. Just log the error
  23387. ** and move on.
  23388. */
  23389. static void robust_close(unixFile *pFile, int h, int lineno){
  23390. if( osClose(h) ){
  23391. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  23392. pFile ? pFile->zPath : 0, lineno);
  23393. }
  23394. }
  23395. /*
  23396. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  23397. */
  23398. static void closePendingFds(unixFile *pFile){
  23399. unixInodeInfo *pInode = pFile->pInode;
  23400. UnixUnusedFd *p;
  23401. UnixUnusedFd *pNext;
  23402. for(p=pInode->pUnused; p; p=pNext){
  23403. pNext = p->pNext;
  23404. robust_close(pFile, p->fd, __LINE__);
  23405. sqlite3_free(p);
  23406. }
  23407. pInode->pUnused = 0;
  23408. }
  23409. /*
  23410. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  23411. **
  23412. ** The mutex entered using the unixEnterMutex() function must be held
  23413. ** when this function is called.
  23414. */
  23415. static void releaseInodeInfo(unixFile *pFile){
  23416. unixInodeInfo *pInode = pFile->pInode;
  23417. assert( unixMutexHeld() );
  23418. if( ALWAYS(pInode) ){
  23419. pInode->nRef--;
  23420. if( pInode->nRef==0 ){
  23421. assert( pInode->pShmNode==0 );
  23422. closePendingFds(pFile);
  23423. if( pInode->pPrev ){
  23424. assert( pInode->pPrev->pNext==pInode );
  23425. pInode->pPrev->pNext = pInode->pNext;
  23426. }else{
  23427. assert( inodeList==pInode );
  23428. inodeList = pInode->pNext;
  23429. }
  23430. if( pInode->pNext ){
  23431. assert( pInode->pNext->pPrev==pInode );
  23432. pInode->pNext->pPrev = pInode->pPrev;
  23433. }
  23434. sqlite3_free(pInode);
  23435. }
  23436. }
  23437. }
  23438. /*
  23439. ** Given a file descriptor, locate the unixInodeInfo object that
  23440. ** describes that file descriptor. Create a new one if necessary. The
  23441. ** return value might be uninitialized if an error occurs.
  23442. **
  23443. ** The mutex entered using the unixEnterMutex() function must be held
  23444. ** when this function is called.
  23445. **
  23446. ** Return an appropriate error code.
  23447. */
  23448. static int findInodeInfo(
  23449. unixFile *pFile, /* Unix file with file desc used in the key */
  23450. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  23451. ){
  23452. int rc; /* System call return code */
  23453. int fd; /* The file descriptor for pFile */
  23454. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  23455. struct stat statbuf; /* Low-level file information */
  23456. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  23457. assert( unixMutexHeld() );
  23458. /* Get low-level information about the file that we can used to
  23459. ** create a unique name for the file.
  23460. */
  23461. fd = pFile->h;
  23462. rc = osFstat(fd, &statbuf);
  23463. if( rc!=0 ){
  23464. pFile->lastErrno = errno;
  23465. #ifdef EOVERFLOW
  23466. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  23467. #endif
  23468. return SQLITE_IOERR;
  23469. }
  23470. #ifdef __APPLE__
  23471. /* On OS X on an msdos filesystem, the inode number is reported
  23472. ** incorrectly for zero-size files. See ticket #3260. To work
  23473. ** around this problem (we consider it a bug in OS X, not SQLite)
  23474. ** we always increase the file size to 1 by writing a single byte
  23475. ** prior to accessing the inode number. The one byte written is
  23476. ** an ASCII 'S' character which also happens to be the first byte
  23477. ** in the header of every SQLite database. In this way, if there
  23478. ** is a race condition such that another thread has already populated
  23479. ** the first page of the database, no damage is done.
  23480. */
  23481. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  23482. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  23483. if( rc!=1 ){
  23484. pFile->lastErrno = errno;
  23485. return SQLITE_IOERR;
  23486. }
  23487. rc = osFstat(fd, &statbuf);
  23488. if( rc!=0 ){
  23489. pFile->lastErrno = errno;
  23490. return SQLITE_IOERR;
  23491. }
  23492. }
  23493. #endif
  23494. memset(&fileId, 0, sizeof(fileId));
  23495. fileId.dev = statbuf.st_dev;
  23496. #if OS_VXWORKS
  23497. fileId.pId = pFile->pId;
  23498. #else
  23499. fileId.ino = statbuf.st_ino;
  23500. #endif
  23501. pInode = inodeList;
  23502. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  23503. pInode = pInode->pNext;
  23504. }
  23505. if( pInode==0 ){
  23506. pInode = sqlite3_malloc( sizeof(*pInode) );
  23507. if( pInode==0 ){
  23508. return SQLITE_NOMEM;
  23509. }
  23510. memset(pInode, 0, sizeof(*pInode));
  23511. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  23512. pInode->nRef = 1;
  23513. pInode->pNext = inodeList;
  23514. pInode->pPrev = 0;
  23515. if( inodeList ) inodeList->pPrev = pInode;
  23516. inodeList = pInode;
  23517. }else{
  23518. pInode->nRef++;
  23519. }
  23520. *ppInode = pInode;
  23521. return SQLITE_OK;
  23522. }
  23523. /*
  23524. ** Check a unixFile that is a database. Verify the following:
  23525. **
  23526. ** (1) There is exactly one hard link on the file
  23527. ** (2) The file is not a symbolic link
  23528. ** (3) The file has not been renamed or unlinked
  23529. **
  23530. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  23531. */
  23532. static void verifyDbFile(unixFile *pFile){
  23533. struct stat buf;
  23534. int rc;
  23535. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  23536. /* One or more of the following warnings have already been issued. Do not
  23537. ** repeat them so as not to clutter the error log */
  23538. return;
  23539. }
  23540. rc = osFstat(pFile->h, &buf);
  23541. if( rc!=0 ){
  23542. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  23543. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23544. return;
  23545. }
  23546. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  23547. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  23548. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23549. return;
  23550. }
  23551. if( buf.st_nlink>1 ){
  23552. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  23553. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23554. return;
  23555. }
  23556. if( pFile->pInode!=0
  23557. && ((rc = osStat(pFile->zPath, &buf))!=0
  23558. || buf.st_ino!=pFile->pInode->fileId.ino)
  23559. ){
  23560. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  23561. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23562. return;
  23563. }
  23564. }
  23565. /*
  23566. ** This routine checks if there is a RESERVED lock held on the specified
  23567. ** file by this or any other process. If such a lock is held, set *pResOut
  23568. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23569. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23570. */
  23571. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  23572. int rc = SQLITE_OK;
  23573. int reserved = 0;
  23574. unixFile *pFile = (unixFile*)id;
  23575. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23576. assert( pFile );
  23577. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  23578. /* Check if a thread in this process holds such a lock */
  23579. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  23580. reserved = 1;
  23581. }
  23582. /* Otherwise see if some other process holds it.
  23583. */
  23584. #ifndef __DJGPP__
  23585. if( !reserved && !pFile->pInode->bProcessLock ){
  23586. struct flock lock;
  23587. lock.l_whence = SEEK_SET;
  23588. lock.l_start = RESERVED_BYTE;
  23589. lock.l_len = 1;
  23590. lock.l_type = F_WRLCK;
  23591. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  23592. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  23593. pFile->lastErrno = errno;
  23594. } else if( lock.l_type!=F_UNLCK ){
  23595. reserved = 1;
  23596. }
  23597. }
  23598. #endif
  23599. unixLeaveMutex();
  23600. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  23601. *pResOut = reserved;
  23602. return rc;
  23603. }
  23604. /*
  23605. ** Attempt to set a system-lock on the file pFile. The lock is
  23606. ** described by pLock.
  23607. **
  23608. ** If the pFile was opened read/write from unix-excl, then the only lock
  23609. ** ever obtained is an exclusive lock, and it is obtained exactly once
  23610. ** the first time any lock is attempted. All subsequent system locking
  23611. ** operations become no-ops. Locking operations still happen internally,
  23612. ** in order to coordinate access between separate database connections
  23613. ** within this process, but all of that is handled in memory and the
  23614. ** operating system does not participate.
  23615. **
  23616. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  23617. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  23618. ** and is read-only.
  23619. **
  23620. ** Zero is returned if the call completes successfully, or -1 if a call
  23621. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  23622. */
  23623. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  23624. int rc;
  23625. unixInodeInfo *pInode = pFile->pInode;
  23626. assert( unixMutexHeld() );
  23627. assert( pInode!=0 );
  23628. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  23629. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  23630. ){
  23631. if( pInode->bProcessLock==0 ){
  23632. struct flock lock;
  23633. assert( pInode->nLock==0 );
  23634. lock.l_whence = SEEK_SET;
  23635. lock.l_start = SHARED_FIRST;
  23636. lock.l_len = SHARED_SIZE;
  23637. lock.l_type = F_WRLCK;
  23638. rc = osFcntl(pFile->h, F_SETLK, &lock);
  23639. if( rc<0 ) return rc;
  23640. pInode->bProcessLock = 1;
  23641. pInode->nLock++;
  23642. }else{
  23643. rc = 0;
  23644. }
  23645. }else{
  23646. rc = osFcntl(pFile->h, F_SETLK, pLock);
  23647. }
  23648. return rc;
  23649. }
  23650. /*
  23651. ** Lock the file with the lock specified by parameter eFileLock - one
  23652. ** of the following:
  23653. **
  23654. ** (1) SHARED_LOCK
  23655. ** (2) RESERVED_LOCK
  23656. ** (3) PENDING_LOCK
  23657. ** (4) EXCLUSIVE_LOCK
  23658. **
  23659. ** Sometimes when requesting one lock state, additional lock states
  23660. ** are inserted in between. The locking might fail on one of the later
  23661. ** transitions leaving the lock state different from what it started but
  23662. ** still short of its goal. The following chart shows the allowed
  23663. ** transitions and the inserted intermediate states:
  23664. **
  23665. ** UNLOCKED -> SHARED
  23666. ** SHARED -> RESERVED
  23667. ** SHARED -> (PENDING) -> EXCLUSIVE
  23668. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23669. ** PENDING -> EXCLUSIVE
  23670. **
  23671. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23672. ** routine to lower a locking level.
  23673. */
  23674. static int unixLock(sqlite3_file *id, int eFileLock){
  23675. /* The following describes the implementation of the various locks and
  23676. ** lock transitions in terms of the POSIX advisory shared and exclusive
  23677. ** lock primitives (called read-locks and write-locks below, to avoid
  23678. ** confusion with SQLite lock names). The algorithms are complicated
  23679. ** slightly in order to be compatible with windows systems simultaneously
  23680. ** accessing the same database file, in case that is ever required.
  23681. **
  23682. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  23683. ** byte', each single bytes at well known offsets, and the 'shared byte
  23684. ** range', a range of 510 bytes at a well known offset.
  23685. **
  23686. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  23687. ** byte'. If this is successful, a random byte from the 'shared byte
  23688. ** range' is read-locked and the lock on the 'pending byte' released.
  23689. **
  23690. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  23691. ** A RESERVED lock is implemented by grabbing a write-lock on the
  23692. ** 'reserved byte'.
  23693. **
  23694. ** A process may only obtain a PENDING lock after it has obtained a
  23695. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  23696. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  23697. ** obtained, but existing SHARED locks are allowed to persist. A process
  23698. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  23699. ** This property is used by the algorithm for rolling back a journal file
  23700. ** after a crash.
  23701. **
  23702. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23703. ** implemented by obtaining a write-lock on the entire 'shared byte
  23704. ** range'. Since all other locks require a read-lock on one of the bytes
  23705. ** within this range, this ensures that no other locks are held on the
  23706. ** database.
  23707. **
  23708. ** The reason a single byte cannot be used instead of the 'shared byte
  23709. ** range' is that some versions of windows do not support read-locks. By
  23710. ** locking a random byte from a range, concurrent SHARED locks may exist
  23711. ** even if the locking primitive used is always a write-lock.
  23712. */
  23713. int rc = SQLITE_OK;
  23714. unixFile *pFile = (unixFile*)id;
  23715. unixInodeInfo *pInode;
  23716. struct flock lock;
  23717. int tErrno = 0;
  23718. assert( pFile );
  23719. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23720. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23721. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  23722. /* If there is already a lock of this type or more restrictive on the
  23723. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23724. ** unixEnterMutex() hasn't been called yet.
  23725. */
  23726. if( pFile->eFileLock>=eFileLock ){
  23727. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23728. azFileLock(eFileLock)));
  23729. return SQLITE_OK;
  23730. }
  23731. /* Make sure the locking sequence is correct.
  23732. ** (1) We never move from unlocked to anything higher than shared lock.
  23733. ** (2) SQLite never explicitly requests a pendig lock.
  23734. ** (3) A shared lock is always held when a reserve lock is requested.
  23735. */
  23736. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23737. assert( eFileLock!=PENDING_LOCK );
  23738. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23739. /* This mutex is needed because pFile->pInode is shared across threads
  23740. */
  23741. unixEnterMutex();
  23742. pInode = pFile->pInode;
  23743. /* If some thread using this PID has a lock via a different unixFile*
  23744. ** handle that precludes the requested lock, return BUSY.
  23745. */
  23746. if( (pFile->eFileLock!=pInode->eFileLock &&
  23747. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23748. ){
  23749. rc = SQLITE_BUSY;
  23750. goto end_lock;
  23751. }
  23752. /* If a SHARED lock is requested, and some thread using this PID already
  23753. ** has a SHARED or RESERVED lock, then increment reference counts and
  23754. ** return SQLITE_OK.
  23755. */
  23756. if( eFileLock==SHARED_LOCK &&
  23757. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23758. assert( eFileLock==SHARED_LOCK );
  23759. assert( pFile->eFileLock==0 );
  23760. assert( pInode->nShared>0 );
  23761. pFile->eFileLock = SHARED_LOCK;
  23762. pInode->nShared++;
  23763. pInode->nLock++;
  23764. goto end_lock;
  23765. }
  23766. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23767. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23768. ** be released.
  23769. */
  23770. lock.l_len = 1L;
  23771. lock.l_whence = SEEK_SET;
  23772. if( eFileLock==SHARED_LOCK
  23773. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  23774. ){
  23775. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  23776. lock.l_start = PENDING_BYTE;
  23777. if( unixFileLock(pFile, &lock) ){
  23778. tErrno = errno;
  23779. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23780. if( rc!=SQLITE_BUSY ){
  23781. pFile->lastErrno = tErrno;
  23782. }
  23783. goto end_lock;
  23784. }
  23785. }
  23786. /* If control gets to this point, then actually go ahead and make
  23787. ** operating system calls for the specified lock.
  23788. */
  23789. if( eFileLock==SHARED_LOCK ){
  23790. assert( pInode->nShared==0 );
  23791. assert( pInode->eFileLock==0 );
  23792. assert( rc==SQLITE_OK );
  23793. /* Now get the read-lock */
  23794. lock.l_start = SHARED_FIRST;
  23795. lock.l_len = SHARED_SIZE;
  23796. if( unixFileLock(pFile, &lock) ){
  23797. tErrno = errno;
  23798. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23799. }
  23800. /* Drop the temporary PENDING lock */
  23801. lock.l_start = PENDING_BYTE;
  23802. lock.l_len = 1L;
  23803. lock.l_type = F_UNLCK;
  23804. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  23805. /* This could happen with a network mount */
  23806. tErrno = errno;
  23807. rc = SQLITE_IOERR_UNLOCK;
  23808. }
  23809. if( rc ){
  23810. if( rc!=SQLITE_BUSY ){
  23811. pFile->lastErrno = tErrno;
  23812. }
  23813. goto end_lock;
  23814. }else{
  23815. pFile->eFileLock = SHARED_LOCK;
  23816. pInode->nLock++;
  23817. pInode->nShared = 1;
  23818. }
  23819. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  23820. /* We are trying for an exclusive lock but another thread in this
  23821. ** same process is still holding a shared lock. */
  23822. rc = SQLITE_BUSY;
  23823. }else{
  23824. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  23825. ** assumed that there is a SHARED or greater lock on the file
  23826. ** already.
  23827. */
  23828. assert( 0!=pFile->eFileLock );
  23829. lock.l_type = F_WRLCK;
  23830. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  23831. if( eFileLock==RESERVED_LOCK ){
  23832. lock.l_start = RESERVED_BYTE;
  23833. lock.l_len = 1L;
  23834. }else{
  23835. lock.l_start = SHARED_FIRST;
  23836. lock.l_len = SHARED_SIZE;
  23837. }
  23838. if( unixFileLock(pFile, &lock) ){
  23839. tErrno = errno;
  23840. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23841. if( rc!=SQLITE_BUSY ){
  23842. pFile->lastErrno = tErrno;
  23843. }
  23844. }
  23845. }
  23846. #ifdef SQLITE_DEBUG
  23847. /* Set up the transaction-counter change checking flags when
  23848. ** transitioning from a SHARED to a RESERVED lock. The change
  23849. ** from SHARED to RESERVED marks the beginning of a normal
  23850. ** write operation (not a hot journal rollback).
  23851. */
  23852. if( rc==SQLITE_OK
  23853. && pFile->eFileLock<=SHARED_LOCK
  23854. && eFileLock==RESERVED_LOCK
  23855. ){
  23856. pFile->transCntrChng = 0;
  23857. pFile->dbUpdate = 0;
  23858. pFile->inNormalWrite = 1;
  23859. }
  23860. #endif
  23861. if( rc==SQLITE_OK ){
  23862. pFile->eFileLock = eFileLock;
  23863. pInode->eFileLock = eFileLock;
  23864. }else if( eFileLock==EXCLUSIVE_LOCK ){
  23865. pFile->eFileLock = PENDING_LOCK;
  23866. pInode->eFileLock = PENDING_LOCK;
  23867. }
  23868. end_lock:
  23869. unixLeaveMutex();
  23870. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  23871. rc==SQLITE_OK ? "ok" : "failed"));
  23872. return rc;
  23873. }
  23874. /*
  23875. ** Add the file descriptor used by file handle pFile to the corresponding
  23876. ** pUnused list.
  23877. */
  23878. static void setPendingFd(unixFile *pFile){
  23879. unixInodeInfo *pInode = pFile->pInode;
  23880. UnixUnusedFd *p = pFile->pUnused;
  23881. p->pNext = pInode->pUnused;
  23882. pInode->pUnused = p;
  23883. pFile->h = -1;
  23884. pFile->pUnused = 0;
  23885. }
  23886. /*
  23887. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23888. ** must be either NO_LOCK or SHARED_LOCK.
  23889. **
  23890. ** If the locking level of the file descriptor is already at or below
  23891. ** the requested locking level, this routine is a no-op.
  23892. **
  23893. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  23894. ** the byte range is divided into 2 parts and the first part is unlocked then
  23895. ** set to a read lock, then the other part is simply unlocked. This works
  23896. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  23897. ** remove the write lock on a region when a read lock is set.
  23898. */
  23899. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  23900. unixFile *pFile = (unixFile*)id;
  23901. unixInodeInfo *pInode;
  23902. struct flock lock;
  23903. int rc = SQLITE_OK;
  23904. assert( pFile );
  23905. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  23906. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  23907. getpid()));
  23908. assert( eFileLock<=SHARED_LOCK );
  23909. if( pFile->eFileLock<=eFileLock ){
  23910. return SQLITE_OK;
  23911. }
  23912. unixEnterMutex();
  23913. pInode = pFile->pInode;
  23914. assert( pInode->nShared!=0 );
  23915. if( pFile->eFileLock>SHARED_LOCK ){
  23916. assert( pInode->eFileLock==pFile->eFileLock );
  23917. #ifdef SQLITE_DEBUG
  23918. /* When reducing a lock such that other processes can start
  23919. ** reading the database file again, make sure that the
  23920. ** transaction counter was updated if any part of the database
  23921. ** file changed. If the transaction counter is not updated,
  23922. ** other connections to the same file might not realize that
  23923. ** the file has changed and hence might not know to flush their
  23924. ** cache. The use of a stale cache can lead to database corruption.
  23925. */
  23926. pFile->inNormalWrite = 0;
  23927. #endif
  23928. /* downgrading to a shared lock on NFS involves clearing the write lock
  23929. ** before establishing the readlock - to avoid a race condition we downgrade
  23930. ** the lock in 2 blocks, so that part of the range will be covered by a
  23931. ** write lock until the rest is covered by a read lock:
  23932. ** 1: [WWWWW]
  23933. ** 2: [....W]
  23934. ** 3: [RRRRW]
  23935. ** 4: [RRRR.]
  23936. */
  23937. if( eFileLock==SHARED_LOCK ){
  23938. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  23939. (void)handleNFSUnlock;
  23940. assert( handleNFSUnlock==0 );
  23941. #endif
  23942. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23943. if( handleNFSUnlock ){
  23944. int tErrno; /* Error code from system call errors */
  23945. off_t divSize = SHARED_SIZE - 1;
  23946. lock.l_type = F_UNLCK;
  23947. lock.l_whence = SEEK_SET;
  23948. lock.l_start = SHARED_FIRST;
  23949. lock.l_len = divSize;
  23950. if( unixFileLock(pFile, &lock)==(-1) ){
  23951. tErrno = errno;
  23952. rc = SQLITE_IOERR_UNLOCK;
  23953. if( IS_LOCK_ERROR(rc) ){
  23954. pFile->lastErrno = tErrno;
  23955. }
  23956. goto end_unlock;
  23957. }
  23958. lock.l_type = F_RDLCK;
  23959. lock.l_whence = SEEK_SET;
  23960. lock.l_start = SHARED_FIRST;
  23961. lock.l_len = divSize;
  23962. if( unixFileLock(pFile, &lock)==(-1) ){
  23963. tErrno = errno;
  23964. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  23965. if( IS_LOCK_ERROR(rc) ){
  23966. pFile->lastErrno = tErrno;
  23967. }
  23968. goto end_unlock;
  23969. }
  23970. lock.l_type = F_UNLCK;
  23971. lock.l_whence = SEEK_SET;
  23972. lock.l_start = SHARED_FIRST+divSize;
  23973. lock.l_len = SHARED_SIZE-divSize;
  23974. if( unixFileLock(pFile, &lock)==(-1) ){
  23975. tErrno = errno;
  23976. rc = SQLITE_IOERR_UNLOCK;
  23977. if( IS_LOCK_ERROR(rc) ){
  23978. pFile->lastErrno = tErrno;
  23979. }
  23980. goto end_unlock;
  23981. }
  23982. }else
  23983. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23984. {
  23985. lock.l_type = F_RDLCK;
  23986. lock.l_whence = SEEK_SET;
  23987. lock.l_start = SHARED_FIRST;
  23988. lock.l_len = SHARED_SIZE;
  23989. if( unixFileLock(pFile, &lock) ){
  23990. /* In theory, the call to unixFileLock() cannot fail because another
  23991. ** process is holding an incompatible lock. If it does, this
  23992. ** indicates that the other process is not following the locking
  23993. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  23994. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  23995. ** an assert to fail). */
  23996. rc = SQLITE_IOERR_RDLOCK;
  23997. pFile->lastErrno = errno;
  23998. goto end_unlock;
  23999. }
  24000. }
  24001. }
  24002. lock.l_type = F_UNLCK;
  24003. lock.l_whence = SEEK_SET;
  24004. lock.l_start = PENDING_BYTE;
  24005. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  24006. if( unixFileLock(pFile, &lock)==0 ){
  24007. pInode->eFileLock = SHARED_LOCK;
  24008. }else{
  24009. rc = SQLITE_IOERR_UNLOCK;
  24010. pFile->lastErrno = errno;
  24011. goto end_unlock;
  24012. }
  24013. }
  24014. if( eFileLock==NO_LOCK ){
  24015. /* Decrement the shared lock counter. Release the lock using an
  24016. ** OS call only when all threads in this same process have released
  24017. ** the lock.
  24018. */
  24019. pInode->nShared--;
  24020. if( pInode->nShared==0 ){
  24021. lock.l_type = F_UNLCK;
  24022. lock.l_whence = SEEK_SET;
  24023. lock.l_start = lock.l_len = 0L;
  24024. if( unixFileLock(pFile, &lock)==0 ){
  24025. pInode->eFileLock = NO_LOCK;
  24026. }else{
  24027. rc = SQLITE_IOERR_UNLOCK;
  24028. pFile->lastErrno = errno;
  24029. pInode->eFileLock = NO_LOCK;
  24030. pFile->eFileLock = NO_LOCK;
  24031. }
  24032. }
  24033. /* Decrement the count of locks against this same file. When the
  24034. ** count reaches zero, close any other file descriptors whose close
  24035. ** was deferred because of outstanding locks.
  24036. */
  24037. pInode->nLock--;
  24038. assert( pInode->nLock>=0 );
  24039. if( pInode->nLock==0 ){
  24040. closePendingFds(pFile);
  24041. }
  24042. }
  24043. end_unlock:
  24044. unixLeaveMutex();
  24045. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24046. return rc;
  24047. }
  24048. /*
  24049. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24050. ** must be either NO_LOCK or SHARED_LOCK.
  24051. **
  24052. ** If the locking level of the file descriptor is already at or below
  24053. ** the requested locking level, this routine is a no-op.
  24054. */
  24055. static int unixUnlock(sqlite3_file *id, int eFileLock){
  24056. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  24057. return posixUnlock(id, eFileLock, 0);
  24058. }
  24059. #if SQLITE_MAX_MMAP_SIZE>0
  24060. static int unixMapfile(unixFile *pFd, i64 nByte);
  24061. static void unixUnmapfile(unixFile *pFd);
  24062. #endif
  24063. /*
  24064. ** This function performs the parts of the "close file" operation
  24065. ** common to all locking schemes. It closes the directory and file
  24066. ** handles, if they are valid, and sets all fields of the unixFile
  24067. ** structure to 0.
  24068. **
  24069. ** It is *not* necessary to hold the mutex when this routine is called,
  24070. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  24071. ** vxworksReleaseFileId() routine.
  24072. */
  24073. static int closeUnixFile(sqlite3_file *id){
  24074. unixFile *pFile = (unixFile*)id;
  24075. #if SQLITE_MAX_MMAP_SIZE>0
  24076. unixUnmapfile(pFile);
  24077. #endif
  24078. if( pFile->h>=0 ){
  24079. robust_close(pFile, pFile->h, __LINE__);
  24080. pFile->h = -1;
  24081. }
  24082. #if OS_VXWORKS
  24083. if( pFile->pId ){
  24084. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  24085. osUnlink(pFile->pId->zCanonicalName);
  24086. }
  24087. vxworksReleaseFileId(pFile->pId);
  24088. pFile->pId = 0;
  24089. }
  24090. #endif
  24091. OSTRACE(("CLOSE %-3d\n", pFile->h));
  24092. OpenCounter(-1);
  24093. sqlite3_free(pFile->pUnused);
  24094. memset(pFile, 0, sizeof(unixFile));
  24095. return SQLITE_OK;
  24096. }
  24097. /*
  24098. ** Close a file.
  24099. */
  24100. static int unixClose(sqlite3_file *id){
  24101. int rc = SQLITE_OK;
  24102. unixFile *pFile = (unixFile *)id;
  24103. verifyDbFile(pFile);
  24104. unixUnlock(id, NO_LOCK);
  24105. unixEnterMutex();
  24106. /* unixFile.pInode is always valid here. Otherwise, a different close
  24107. ** routine (e.g. nolockClose()) would be called instead.
  24108. */
  24109. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  24110. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  24111. /* If there are outstanding locks, do not actually close the file just
  24112. ** yet because that would clear those locks. Instead, add the file
  24113. ** descriptor to pInode->pUnused list. It will be automatically closed
  24114. ** when the last lock is cleared.
  24115. */
  24116. setPendingFd(pFile);
  24117. }
  24118. releaseInodeInfo(pFile);
  24119. rc = closeUnixFile(id);
  24120. unixLeaveMutex();
  24121. return rc;
  24122. }
  24123. /************** End of the posix advisory lock implementation *****************
  24124. ******************************************************************************/
  24125. /******************************************************************************
  24126. ****************************** No-op Locking **********************************
  24127. **
  24128. ** Of the various locking implementations available, this is by far the
  24129. ** simplest: locking is ignored. No attempt is made to lock the database
  24130. ** file for reading or writing.
  24131. **
  24132. ** This locking mode is appropriate for use on read-only databases
  24133. ** (ex: databases that are burned into CD-ROM, for example.) It can
  24134. ** also be used if the application employs some external mechanism to
  24135. ** prevent simultaneous access of the same database by two or more
  24136. ** database connections. But there is a serious risk of database
  24137. ** corruption if this locking mode is used in situations where multiple
  24138. ** database connections are accessing the same database file at the same
  24139. ** time and one or more of those connections are writing.
  24140. */
  24141. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  24142. UNUSED_PARAMETER(NotUsed);
  24143. *pResOut = 0;
  24144. return SQLITE_OK;
  24145. }
  24146. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  24147. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24148. return SQLITE_OK;
  24149. }
  24150. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  24151. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24152. return SQLITE_OK;
  24153. }
  24154. /*
  24155. ** Close the file.
  24156. */
  24157. static int nolockClose(sqlite3_file *id) {
  24158. return closeUnixFile(id);
  24159. }
  24160. /******************* End of the no-op lock implementation *********************
  24161. ******************************************************************************/
  24162. /******************************************************************************
  24163. ************************* Begin dot-file Locking ******************************
  24164. **
  24165. ** The dotfile locking implementation uses the existence of separate lock
  24166. ** files (really a directory) to control access to the database. This works
  24167. ** on just about every filesystem imaginable. But there are serious downsides:
  24168. **
  24169. ** (1) There is zero concurrency. A single reader blocks all other
  24170. ** connections from reading or writing the database.
  24171. **
  24172. ** (2) An application crash or power loss can leave stale lock files
  24173. ** sitting around that need to be cleared manually.
  24174. **
  24175. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  24176. ** other locking strategy is available.
  24177. **
  24178. ** Dotfile locking works by creating a subdirectory in the same directory as
  24179. ** the database and with the same name but with a ".lock" extension added.
  24180. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  24181. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  24182. */
  24183. /*
  24184. ** The file suffix added to the data base filename in order to create the
  24185. ** lock directory.
  24186. */
  24187. #define DOTLOCK_SUFFIX ".lock"
  24188. /*
  24189. ** This routine checks if there is a RESERVED lock held on the specified
  24190. ** file by this or any other process. If such a lock is held, set *pResOut
  24191. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24192. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24193. **
  24194. ** In dotfile locking, either a lock exists or it does not. So in this
  24195. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  24196. ** is held on the file and false if the file is unlocked.
  24197. */
  24198. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24199. int rc = SQLITE_OK;
  24200. int reserved = 0;
  24201. unixFile *pFile = (unixFile*)id;
  24202. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24203. assert( pFile );
  24204. /* Check if a thread in this process holds such a lock */
  24205. if( pFile->eFileLock>SHARED_LOCK ){
  24206. /* Either this connection or some other connection in the same process
  24207. ** holds a lock on the file. No need to check further. */
  24208. reserved = 1;
  24209. }else{
  24210. /* The lock is held if and only if the lockfile exists */
  24211. const char *zLockFile = (const char*)pFile->lockingContext;
  24212. reserved = osAccess(zLockFile, 0)==0;
  24213. }
  24214. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  24215. *pResOut = reserved;
  24216. return rc;
  24217. }
  24218. /*
  24219. ** Lock the file with the lock specified by parameter eFileLock - one
  24220. ** of the following:
  24221. **
  24222. ** (1) SHARED_LOCK
  24223. ** (2) RESERVED_LOCK
  24224. ** (3) PENDING_LOCK
  24225. ** (4) EXCLUSIVE_LOCK
  24226. **
  24227. ** Sometimes when requesting one lock state, additional lock states
  24228. ** are inserted in between. The locking might fail on one of the later
  24229. ** transitions leaving the lock state different from what it started but
  24230. ** still short of its goal. The following chart shows the allowed
  24231. ** transitions and the inserted intermediate states:
  24232. **
  24233. ** UNLOCKED -> SHARED
  24234. ** SHARED -> RESERVED
  24235. ** SHARED -> (PENDING) -> EXCLUSIVE
  24236. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24237. ** PENDING -> EXCLUSIVE
  24238. **
  24239. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24240. ** routine to lower a locking level.
  24241. **
  24242. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  24243. ** But we track the other locking levels internally.
  24244. */
  24245. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  24246. unixFile *pFile = (unixFile*)id;
  24247. char *zLockFile = (char *)pFile->lockingContext;
  24248. int rc = SQLITE_OK;
  24249. /* If we have any lock, then the lock file already exists. All we have
  24250. ** to do is adjust our internal record of the lock level.
  24251. */
  24252. if( pFile->eFileLock > NO_LOCK ){
  24253. pFile->eFileLock = eFileLock;
  24254. /* Always update the timestamp on the old file */
  24255. #ifdef HAVE_UTIME
  24256. utime(zLockFile, NULL);
  24257. #else
  24258. utimes(zLockFile, NULL);
  24259. #endif
  24260. return SQLITE_OK;
  24261. }
  24262. /* grab an exclusive lock */
  24263. rc = osMkdir(zLockFile, 0777);
  24264. if( rc<0 ){
  24265. /* failed to open/create the lock directory */
  24266. int tErrno = errno;
  24267. if( EEXIST == tErrno ){
  24268. rc = SQLITE_BUSY;
  24269. } else {
  24270. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24271. if( IS_LOCK_ERROR(rc) ){
  24272. pFile->lastErrno = tErrno;
  24273. }
  24274. }
  24275. return rc;
  24276. }
  24277. /* got it, set the type and return ok */
  24278. pFile->eFileLock = eFileLock;
  24279. return rc;
  24280. }
  24281. /*
  24282. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24283. ** must be either NO_LOCK or SHARED_LOCK.
  24284. **
  24285. ** If the locking level of the file descriptor is already at or below
  24286. ** the requested locking level, this routine is a no-op.
  24287. **
  24288. ** When the locking level reaches NO_LOCK, delete the lock file.
  24289. */
  24290. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  24291. unixFile *pFile = (unixFile*)id;
  24292. char *zLockFile = (char *)pFile->lockingContext;
  24293. int rc;
  24294. assert( pFile );
  24295. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  24296. pFile->eFileLock, getpid()));
  24297. assert( eFileLock<=SHARED_LOCK );
  24298. /* no-op if possible */
  24299. if( pFile->eFileLock==eFileLock ){
  24300. return SQLITE_OK;
  24301. }
  24302. /* To downgrade to shared, simply update our internal notion of the
  24303. ** lock state. No need to mess with the file on disk.
  24304. */
  24305. if( eFileLock==SHARED_LOCK ){
  24306. pFile->eFileLock = SHARED_LOCK;
  24307. return SQLITE_OK;
  24308. }
  24309. /* To fully unlock the database, delete the lock file */
  24310. assert( eFileLock==NO_LOCK );
  24311. rc = osRmdir(zLockFile);
  24312. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  24313. if( rc<0 ){
  24314. int tErrno = errno;
  24315. rc = 0;
  24316. if( ENOENT != tErrno ){
  24317. rc = SQLITE_IOERR_UNLOCK;
  24318. }
  24319. if( IS_LOCK_ERROR(rc) ){
  24320. pFile->lastErrno = tErrno;
  24321. }
  24322. return rc;
  24323. }
  24324. pFile->eFileLock = NO_LOCK;
  24325. return SQLITE_OK;
  24326. }
  24327. /*
  24328. ** Close a file. Make sure the lock has been released before closing.
  24329. */
  24330. static int dotlockClose(sqlite3_file *id) {
  24331. int rc = SQLITE_OK;
  24332. if( id ){
  24333. unixFile *pFile = (unixFile*)id;
  24334. dotlockUnlock(id, NO_LOCK);
  24335. sqlite3_free(pFile->lockingContext);
  24336. rc = closeUnixFile(id);
  24337. }
  24338. return rc;
  24339. }
  24340. /****************** End of the dot-file lock implementation *******************
  24341. ******************************************************************************/
  24342. /******************************************************************************
  24343. ************************** Begin flock Locking ********************************
  24344. **
  24345. ** Use the flock() system call to do file locking.
  24346. **
  24347. ** flock() locking is like dot-file locking in that the various
  24348. ** fine-grain locking levels supported by SQLite are collapsed into
  24349. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  24350. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  24351. ** still works when you do this, but concurrency is reduced since
  24352. ** only a single process can be reading the database at a time.
  24353. **
  24354. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  24355. ** compiling for VXWORKS.
  24356. */
  24357. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  24358. /*
  24359. ** Retry flock() calls that fail with EINTR
  24360. */
  24361. #ifdef EINTR
  24362. static int robust_flock(int fd, int op){
  24363. int rc;
  24364. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  24365. return rc;
  24366. }
  24367. #else
  24368. # define robust_flock(a,b) flock(a,b)
  24369. #endif
  24370. /*
  24371. ** This routine checks if there is a RESERVED lock held on the specified
  24372. ** file by this or any other process. If such a lock is held, set *pResOut
  24373. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24374. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24375. */
  24376. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  24377. int rc = SQLITE_OK;
  24378. int reserved = 0;
  24379. unixFile *pFile = (unixFile*)id;
  24380. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24381. assert( pFile );
  24382. /* Check if a thread in this process holds such a lock */
  24383. if( pFile->eFileLock>SHARED_LOCK ){
  24384. reserved = 1;
  24385. }
  24386. /* Otherwise see if some other process holds it. */
  24387. if( !reserved ){
  24388. /* attempt to get the lock */
  24389. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  24390. if( !lrc ){
  24391. /* got the lock, unlock it */
  24392. lrc = robust_flock(pFile->h, LOCK_UN);
  24393. if ( lrc ) {
  24394. int tErrno = errno;
  24395. /* unlock failed with an error */
  24396. lrc = SQLITE_IOERR_UNLOCK;
  24397. if( IS_LOCK_ERROR(lrc) ){
  24398. pFile->lastErrno = tErrno;
  24399. rc = lrc;
  24400. }
  24401. }
  24402. } else {
  24403. int tErrno = errno;
  24404. reserved = 1;
  24405. /* someone else might have it reserved */
  24406. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24407. if( IS_LOCK_ERROR(lrc) ){
  24408. pFile->lastErrno = tErrno;
  24409. rc = lrc;
  24410. }
  24411. }
  24412. }
  24413. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  24414. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24415. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24416. rc = SQLITE_OK;
  24417. reserved=1;
  24418. }
  24419. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24420. *pResOut = reserved;
  24421. return rc;
  24422. }
  24423. /*
  24424. ** Lock the file with the lock specified by parameter eFileLock - one
  24425. ** of the following:
  24426. **
  24427. ** (1) SHARED_LOCK
  24428. ** (2) RESERVED_LOCK
  24429. ** (3) PENDING_LOCK
  24430. ** (4) EXCLUSIVE_LOCK
  24431. **
  24432. ** Sometimes when requesting one lock state, additional lock states
  24433. ** are inserted in between. The locking might fail on one of the later
  24434. ** transitions leaving the lock state different from what it started but
  24435. ** still short of its goal. The following chart shows the allowed
  24436. ** transitions and the inserted intermediate states:
  24437. **
  24438. ** UNLOCKED -> SHARED
  24439. ** SHARED -> RESERVED
  24440. ** SHARED -> (PENDING) -> EXCLUSIVE
  24441. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24442. ** PENDING -> EXCLUSIVE
  24443. **
  24444. ** flock() only really support EXCLUSIVE locks. We track intermediate
  24445. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24446. ** above are really EXCLUSIVE locks and exclude all other processes from
  24447. ** access the file.
  24448. **
  24449. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24450. ** routine to lower a locking level.
  24451. */
  24452. static int flockLock(sqlite3_file *id, int eFileLock) {
  24453. int rc = SQLITE_OK;
  24454. unixFile *pFile = (unixFile*)id;
  24455. assert( pFile );
  24456. /* if we already have a lock, it is exclusive.
  24457. ** Just adjust level and punt on outta here. */
  24458. if (pFile->eFileLock > NO_LOCK) {
  24459. pFile->eFileLock = eFileLock;
  24460. return SQLITE_OK;
  24461. }
  24462. /* grab an exclusive lock */
  24463. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  24464. int tErrno = errno;
  24465. /* didn't get, must be busy */
  24466. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24467. if( IS_LOCK_ERROR(rc) ){
  24468. pFile->lastErrno = tErrno;
  24469. }
  24470. } else {
  24471. /* got it, set the type and return ok */
  24472. pFile->eFileLock = eFileLock;
  24473. }
  24474. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  24475. rc==SQLITE_OK ? "ok" : "failed"));
  24476. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24477. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24478. rc = SQLITE_BUSY;
  24479. }
  24480. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24481. return rc;
  24482. }
  24483. /*
  24484. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24485. ** must be either NO_LOCK or SHARED_LOCK.
  24486. **
  24487. ** If the locking level of the file descriptor is already at or below
  24488. ** the requested locking level, this routine is a no-op.
  24489. */
  24490. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  24491. unixFile *pFile = (unixFile*)id;
  24492. assert( pFile );
  24493. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  24494. pFile->eFileLock, getpid()));
  24495. assert( eFileLock<=SHARED_LOCK );
  24496. /* no-op if possible */
  24497. if( pFile->eFileLock==eFileLock ){
  24498. return SQLITE_OK;
  24499. }
  24500. /* shared can just be set because we always have an exclusive */
  24501. if (eFileLock==SHARED_LOCK) {
  24502. pFile->eFileLock = eFileLock;
  24503. return SQLITE_OK;
  24504. }
  24505. /* no, really, unlock. */
  24506. if( robust_flock(pFile->h, LOCK_UN) ){
  24507. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24508. return SQLITE_OK;
  24509. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24510. return SQLITE_IOERR_UNLOCK;
  24511. }else{
  24512. pFile->eFileLock = NO_LOCK;
  24513. return SQLITE_OK;
  24514. }
  24515. }
  24516. /*
  24517. ** Close a file.
  24518. */
  24519. static int flockClose(sqlite3_file *id) {
  24520. int rc = SQLITE_OK;
  24521. if( id ){
  24522. flockUnlock(id, NO_LOCK);
  24523. rc = closeUnixFile(id);
  24524. }
  24525. return rc;
  24526. }
  24527. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  24528. /******************* End of the flock lock implementation *********************
  24529. ******************************************************************************/
  24530. /******************************************************************************
  24531. ************************ Begin Named Semaphore Locking ************************
  24532. **
  24533. ** Named semaphore locking is only supported on VxWorks.
  24534. **
  24535. ** Semaphore locking is like dot-lock and flock in that it really only
  24536. ** supports EXCLUSIVE locking. Only a single process can read or write
  24537. ** the database file at a time. This reduces potential concurrency, but
  24538. ** makes the lock implementation much easier.
  24539. */
  24540. #if OS_VXWORKS
  24541. /*
  24542. ** This routine checks if there is a RESERVED lock held on the specified
  24543. ** file by this or any other process. If such a lock is held, set *pResOut
  24544. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24545. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24546. */
  24547. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24548. int rc = SQLITE_OK;
  24549. int reserved = 0;
  24550. unixFile *pFile = (unixFile*)id;
  24551. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24552. assert( pFile );
  24553. /* Check if a thread in this process holds such a lock */
  24554. if( pFile->eFileLock>SHARED_LOCK ){
  24555. reserved = 1;
  24556. }
  24557. /* Otherwise see if some other process holds it. */
  24558. if( !reserved ){
  24559. sem_t *pSem = pFile->pInode->pSem;
  24560. struct stat statBuf;
  24561. if( sem_trywait(pSem)==-1 ){
  24562. int tErrno = errno;
  24563. if( EAGAIN != tErrno ){
  24564. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  24565. pFile->lastErrno = tErrno;
  24566. } else {
  24567. /* someone else has the lock when we are in NO_LOCK */
  24568. reserved = (pFile->eFileLock < SHARED_LOCK);
  24569. }
  24570. }else{
  24571. /* we could have it if we want it */
  24572. sem_post(pSem);
  24573. }
  24574. }
  24575. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  24576. *pResOut = reserved;
  24577. return rc;
  24578. }
  24579. /*
  24580. ** Lock the file with the lock specified by parameter eFileLock - one
  24581. ** of the following:
  24582. **
  24583. ** (1) SHARED_LOCK
  24584. ** (2) RESERVED_LOCK
  24585. ** (3) PENDING_LOCK
  24586. ** (4) EXCLUSIVE_LOCK
  24587. **
  24588. ** Sometimes when requesting one lock state, additional lock states
  24589. ** are inserted in between. The locking might fail on one of the later
  24590. ** transitions leaving the lock state different from what it started but
  24591. ** still short of its goal. The following chart shows the allowed
  24592. ** transitions and the inserted intermediate states:
  24593. **
  24594. ** UNLOCKED -> SHARED
  24595. ** SHARED -> RESERVED
  24596. ** SHARED -> (PENDING) -> EXCLUSIVE
  24597. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24598. ** PENDING -> EXCLUSIVE
  24599. **
  24600. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  24601. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24602. ** above are really EXCLUSIVE locks and exclude all other processes from
  24603. ** access the file.
  24604. **
  24605. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24606. ** routine to lower a locking level.
  24607. */
  24608. static int semLock(sqlite3_file *id, int eFileLock) {
  24609. unixFile *pFile = (unixFile*)id;
  24610. int fd;
  24611. sem_t *pSem = pFile->pInode->pSem;
  24612. int rc = SQLITE_OK;
  24613. /* if we already have a lock, it is exclusive.
  24614. ** Just adjust level and punt on outta here. */
  24615. if (pFile->eFileLock > NO_LOCK) {
  24616. pFile->eFileLock = eFileLock;
  24617. rc = SQLITE_OK;
  24618. goto sem_end_lock;
  24619. }
  24620. /* lock semaphore now but bail out when already locked. */
  24621. if( sem_trywait(pSem)==-1 ){
  24622. rc = SQLITE_BUSY;
  24623. goto sem_end_lock;
  24624. }
  24625. /* got it, set the type and return ok */
  24626. pFile->eFileLock = eFileLock;
  24627. sem_end_lock:
  24628. return rc;
  24629. }
  24630. /*
  24631. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24632. ** must be either NO_LOCK or SHARED_LOCK.
  24633. **
  24634. ** If the locking level of the file descriptor is already at or below
  24635. ** the requested locking level, this routine is a no-op.
  24636. */
  24637. static int semUnlock(sqlite3_file *id, int eFileLock) {
  24638. unixFile *pFile = (unixFile*)id;
  24639. sem_t *pSem = pFile->pInode->pSem;
  24640. assert( pFile );
  24641. assert( pSem );
  24642. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  24643. pFile->eFileLock, getpid()));
  24644. assert( eFileLock<=SHARED_LOCK );
  24645. /* no-op if possible */
  24646. if( pFile->eFileLock==eFileLock ){
  24647. return SQLITE_OK;
  24648. }
  24649. /* shared can just be set because we always have an exclusive */
  24650. if (eFileLock==SHARED_LOCK) {
  24651. pFile->eFileLock = eFileLock;
  24652. return SQLITE_OK;
  24653. }
  24654. /* no, really unlock. */
  24655. if ( sem_post(pSem)==-1 ) {
  24656. int rc, tErrno = errno;
  24657. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  24658. if( IS_LOCK_ERROR(rc) ){
  24659. pFile->lastErrno = tErrno;
  24660. }
  24661. return rc;
  24662. }
  24663. pFile->eFileLock = NO_LOCK;
  24664. return SQLITE_OK;
  24665. }
  24666. /*
  24667. ** Close a file.
  24668. */
  24669. static int semClose(sqlite3_file *id) {
  24670. if( id ){
  24671. unixFile *pFile = (unixFile*)id;
  24672. semUnlock(id, NO_LOCK);
  24673. assert( pFile );
  24674. unixEnterMutex();
  24675. releaseInodeInfo(pFile);
  24676. unixLeaveMutex();
  24677. closeUnixFile(id);
  24678. }
  24679. return SQLITE_OK;
  24680. }
  24681. #endif /* OS_VXWORKS */
  24682. /*
  24683. ** Named semaphore locking is only available on VxWorks.
  24684. **
  24685. *************** End of the named semaphore lock implementation ****************
  24686. ******************************************************************************/
  24687. /******************************************************************************
  24688. *************************** Begin AFP Locking *********************************
  24689. **
  24690. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  24691. ** on Apple Macintosh computers - both OS9 and OSX.
  24692. **
  24693. ** Third-party implementations of AFP are available. But this code here
  24694. ** only works on OSX.
  24695. */
  24696. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24697. /*
  24698. ** The afpLockingContext structure contains all afp lock specific state
  24699. */
  24700. typedef struct afpLockingContext afpLockingContext;
  24701. struct afpLockingContext {
  24702. int reserved;
  24703. const char *dbPath; /* Name of the open file */
  24704. };
  24705. struct ByteRangeLockPB2
  24706. {
  24707. unsigned long long offset; /* offset to first byte to lock */
  24708. unsigned long long length; /* nbr of bytes to lock */
  24709. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  24710. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24711. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24712. int fd; /* file desc to assoc this lock with */
  24713. };
  24714. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24715. /*
  24716. ** This is a utility for setting or clearing a bit-range lock on an
  24717. ** AFP filesystem.
  24718. **
  24719. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24720. */
  24721. static int afpSetLock(
  24722. const char *path, /* Name of the file to be locked or unlocked */
  24723. unixFile *pFile, /* Open file descriptor on path */
  24724. unsigned long long offset, /* First byte to be locked */
  24725. unsigned long long length, /* Number of bytes to lock */
  24726. int setLockFlag /* True to set lock. False to clear lock */
  24727. ){
  24728. struct ByteRangeLockPB2 pb;
  24729. int err;
  24730. pb.unLockFlag = setLockFlag ? 0 : 1;
  24731. pb.startEndFlag = 0;
  24732. pb.offset = offset;
  24733. pb.length = length;
  24734. pb.fd = pFile->h;
  24735. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24736. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24737. offset, length));
  24738. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24739. if ( err==-1 ) {
  24740. int rc;
  24741. int tErrno = errno;
  24742. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24743. path, tErrno, strerror(tErrno)));
  24744. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24745. rc = SQLITE_BUSY;
  24746. #else
  24747. rc = sqliteErrorFromPosixError(tErrno,
  24748. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24749. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24750. if( IS_LOCK_ERROR(rc) ){
  24751. pFile->lastErrno = tErrno;
  24752. }
  24753. return rc;
  24754. } else {
  24755. return SQLITE_OK;
  24756. }
  24757. }
  24758. /*
  24759. ** This routine checks if there is a RESERVED lock held on the specified
  24760. ** file by this or any other process. If such a lock is held, set *pResOut
  24761. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24762. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24763. */
  24764. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24765. int rc = SQLITE_OK;
  24766. int reserved = 0;
  24767. unixFile *pFile = (unixFile*)id;
  24768. afpLockingContext *context;
  24769. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24770. assert( pFile );
  24771. context = (afpLockingContext *) pFile->lockingContext;
  24772. if( context->reserved ){
  24773. *pResOut = 1;
  24774. return SQLITE_OK;
  24775. }
  24776. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24777. /* Check if a thread in this process holds such a lock */
  24778. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24779. reserved = 1;
  24780. }
  24781. /* Otherwise see if some other process holds it.
  24782. */
  24783. if( !reserved ){
  24784. /* lock the RESERVED byte */
  24785. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24786. if( SQLITE_OK==lrc ){
  24787. /* if we succeeded in taking the reserved lock, unlock it to restore
  24788. ** the original state */
  24789. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24790. } else {
  24791. /* if we failed to get the lock then someone else must have it */
  24792. reserved = 1;
  24793. }
  24794. if( IS_LOCK_ERROR(lrc) ){
  24795. rc=lrc;
  24796. }
  24797. }
  24798. unixLeaveMutex();
  24799. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  24800. *pResOut = reserved;
  24801. return rc;
  24802. }
  24803. /*
  24804. ** Lock the file with the lock specified by parameter eFileLock - one
  24805. ** of the following:
  24806. **
  24807. ** (1) SHARED_LOCK
  24808. ** (2) RESERVED_LOCK
  24809. ** (3) PENDING_LOCK
  24810. ** (4) EXCLUSIVE_LOCK
  24811. **
  24812. ** Sometimes when requesting one lock state, additional lock states
  24813. ** are inserted in between. The locking might fail on one of the later
  24814. ** transitions leaving the lock state different from what it started but
  24815. ** still short of its goal. The following chart shows the allowed
  24816. ** transitions and the inserted intermediate states:
  24817. **
  24818. ** UNLOCKED -> SHARED
  24819. ** SHARED -> RESERVED
  24820. ** SHARED -> (PENDING) -> EXCLUSIVE
  24821. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24822. ** PENDING -> EXCLUSIVE
  24823. **
  24824. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24825. ** routine to lower a locking level.
  24826. */
  24827. static int afpLock(sqlite3_file *id, int eFileLock){
  24828. int rc = SQLITE_OK;
  24829. unixFile *pFile = (unixFile*)id;
  24830. unixInodeInfo *pInode = pFile->pInode;
  24831. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24832. assert( pFile );
  24833. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  24834. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24835. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  24836. /* If there is already a lock of this type or more restrictive on the
  24837. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  24838. ** unixEnterMutex() hasn't been called yet.
  24839. */
  24840. if( pFile->eFileLock>=eFileLock ){
  24841. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  24842. azFileLock(eFileLock)));
  24843. return SQLITE_OK;
  24844. }
  24845. /* Make sure the locking sequence is correct
  24846. ** (1) We never move from unlocked to anything higher than shared lock.
  24847. ** (2) SQLite never explicitly requests a pendig lock.
  24848. ** (3) A shared lock is always held when a reserve lock is requested.
  24849. */
  24850. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24851. assert( eFileLock!=PENDING_LOCK );
  24852. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24853. /* This mutex is needed because pFile->pInode is shared across threads
  24854. */
  24855. unixEnterMutex();
  24856. pInode = pFile->pInode;
  24857. /* If some thread using this PID has a lock via a different unixFile*
  24858. ** handle that precludes the requested lock, return BUSY.
  24859. */
  24860. if( (pFile->eFileLock!=pInode->eFileLock &&
  24861. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24862. ){
  24863. rc = SQLITE_BUSY;
  24864. goto afp_end_lock;
  24865. }
  24866. /* If a SHARED lock is requested, and some thread using this PID already
  24867. ** has a SHARED or RESERVED lock, then increment reference counts and
  24868. ** return SQLITE_OK.
  24869. */
  24870. if( eFileLock==SHARED_LOCK &&
  24871. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24872. assert( eFileLock==SHARED_LOCK );
  24873. assert( pFile->eFileLock==0 );
  24874. assert( pInode->nShared>0 );
  24875. pFile->eFileLock = SHARED_LOCK;
  24876. pInode->nShared++;
  24877. pInode->nLock++;
  24878. goto afp_end_lock;
  24879. }
  24880. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24881. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24882. ** be released.
  24883. */
  24884. if( eFileLock==SHARED_LOCK
  24885. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24886. ){
  24887. int failed;
  24888. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  24889. if (failed) {
  24890. rc = failed;
  24891. goto afp_end_lock;
  24892. }
  24893. }
  24894. /* If control gets to this point, then actually go ahead and make
  24895. ** operating system calls for the specified lock.
  24896. */
  24897. if( eFileLock==SHARED_LOCK ){
  24898. int lrc1, lrc2, lrc1Errno = 0;
  24899. long lk, mask;
  24900. assert( pInode->nShared==0 );
  24901. assert( pInode->eFileLock==0 );
  24902. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  24903. /* Now get the read-lock SHARED_LOCK */
  24904. /* note that the quality of the randomness doesn't matter that much */
  24905. lk = random();
  24906. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  24907. lrc1 = afpSetLock(context->dbPath, pFile,
  24908. SHARED_FIRST+pInode->sharedByte, 1, 1);
  24909. if( IS_LOCK_ERROR(lrc1) ){
  24910. lrc1Errno = pFile->lastErrno;
  24911. }
  24912. /* Drop the temporary PENDING lock */
  24913. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24914. if( IS_LOCK_ERROR(lrc1) ) {
  24915. pFile->lastErrno = lrc1Errno;
  24916. rc = lrc1;
  24917. goto afp_end_lock;
  24918. } else if( IS_LOCK_ERROR(lrc2) ){
  24919. rc = lrc2;
  24920. goto afp_end_lock;
  24921. } else if( lrc1 != SQLITE_OK ) {
  24922. rc = lrc1;
  24923. } else {
  24924. pFile->eFileLock = SHARED_LOCK;
  24925. pInode->nLock++;
  24926. pInode->nShared = 1;
  24927. }
  24928. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24929. /* We are trying for an exclusive lock but another thread in this
  24930. ** same process is still holding a shared lock. */
  24931. rc = SQLITE_BUSY;
  24932. }else{
  24933. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24934. ** assumed that there is a SHARED or greater lock on the file
  24935. ** already.
  24936. */
  24937. int failed = 0;
  24938. assert( 0!=pFile->eFileLock );
  24939. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  24940. /* Acquire a RESERVED lock */
  24941. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24942. if( !failed ){
  24943. context->reserved = 1;
  24944. }
  24945. }
  24946. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  24947. /* Acquire an EXCLUSIVE lock */
  24948. /* Remove the shared lock before trying the range. we'll need to
  24949. ** reestablish the shared lock if we can't get the afpUnlock
  24950. */
  24951. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  24952. pInode->sharedByte, 1, 0)) ){
  24953. int failed2 = SQLITE_OK;
  24954. /* now attemmpt to get the exclusive lock range */
  24955. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  24956. SHARED_SIZE, 1);
  24957. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  24958. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  24959. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  24960. ** a critical I/O error
  24961. */
  24962. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  24963. SQLITE_IOERR_LOCK;
  24964. goto afp_end_lock;
  24965. }
  24966. }else{
  24967. rc = failed;
  24968. }
  24969. }
  24970. if( failed ){
  24971. rc = failed;
  24972. }
  24973. }
  24974. if( rc==SQLITE_OK ){
  24975. pFile->eFileLock = eFileLock;
  24976. pInode->eFileLock = eFileLock;
  24977. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24978. pFile->eFileLock = PENDING_LOCK;
  24979. pInode->eFileLock = PENDING_LOCK;
  24980. }
  24981. afp_end_lock:
  24982. unixLeaveMutex();
  24983. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  24984. rc==SQLITE_OK ? "ok" : "failed"));
  24985. return rc;
  24986. }
  24987. /*
  24988. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24989. ** must be either NO_LOCK or SHARED_LOCK.
  24990. **
  24991. ** If the locking level of the file descriptor is already at or below
  24992. ** the requested locking level, this routine is a no-op.
  24993. */
  24994. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  24995. int rc = SQLITE_OK;
  24996. unixFile *pFile = (unixFile*)id;
  24997. unixInodeInfo *pInode;
  24998. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24999. int skipShared = 0;
  25000. #ifdef SQLITE_TEST
  25001. int h = pFile->h;
  25002. #endif
  25003. assert( pFile );
  25004. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  25005. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25006. getpid()));
  25007. assert( eFileLock<=SHARED_LOCK );
  25008. if( pFile->eFileLock<=eFileLock ){
  25009. return SQLITE_OK;
  25010. }
  25011. unixEnterMutex();
  25012. pInode = pFile->pInode;
  25013. assert( pInode->nShared!=0 );
  25014. if( pFile->eFileLock>SHARED_LOCK ){
  25015. assert( pInode->eFileLock==pFile->eFileLock );
  25016. SimulateIOErrorBenign(1);
  25017. SimulateIOError( h=(-1) )
  25018. SimulateIOErrorBenign(0);
  25019. #ifdef SQLITE_DEBUG
  25020. /* When reducing a lock such that other processes can start
  25021. ** reading the database file again, make sure that the
  25022. ** transaction counter was updated if any part of the database
  25023. ** file changed. If the transaction counter is not updated,
  25024. ** other connections to the same file might not realize that
  25025. ** the file has changed and hence might not know to flush their
  25026. ** cache. The use of a stale cache can lead to database corruption.
  25027. */
  25028. assert( pFile->inNormalWrite==0
  25029. || pFile->dbUpdate==0
  25030. || pFile->transCntrChng==1 );
  25031. pFile->inNormalWrite = 0;
  25032. #endif
  25033. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  25034. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  25035. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  25036. /* only re-establish the shared lock if necessary */
  25037. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25038. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  25039. } else {
  25040. skipShared = 1;
  25041. }
  25042. }
  25043. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  25044. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  25045. }
  25046. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  25047. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  25048. if( !rc ){
  25049. context->reserved = 0;
  25050. }
  25051. }
  25052. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  25053. pInode->eFileLock = SHARED_LOCK;
  25054. }
  25055. }
  25056. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  25057. /* Decrement the shared lock counter. Release the lock using an
  25058. ** OS call only when all threads in this same process have released
  25059. ** the lock.
  25060. */
  25061. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25062. pInode->nShared--;
  25063. if( pInode->nShared==0 ){
  25064. SimulateIOErrorBenign(1);
  25065. SimulateIOError( h=(-1) )
  25066. SimulateIOErrorBenign(0);
  25067. if( !skipShared ){
  25068. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  25069. }
  25070. if( !rc ){
  25071. pInode->eFileLock = NO_LOCK;
  25072. pFile->eFileLock = NO_LOCK;
  25073. }
  25074. }
  25075. if( rc==SQLITE_OK ){
  25076. pInode->nLock--;
  25077. assert( pInode->nLock>=0 );
  25078. if( pInode->nLock==0 ){
  25079. closePendingFds(pFile);
  25080. }
  25081. }
  25082. }
  25083. unixLeaveMutex();
  25084. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25085. return rc;
  25086. }
  25087. /*
  25088. ** Close a file & cleanup AFP specific locking context
  25089. */
  25090. static int afpClose(sqlite3_file *id) {
  25091. int rc = SQLITE_OK;
  25092. if( id ){
  25093. unixFile *pFile = (unixFile*)id;
  25094. afpUnlock(id, NO_LOCK);
  25095. unixEnterMutex();
  25096. if( pFile->pInode && pFile->pInode->nLock ){
  25097. /* If there are outstanding locks, do not actually close the file just
  25098. ** yet because that would clear those locks. Instead, add the file
  25099. ** descriptor to pInode->aPending. It will be automatically closed when
  25100. ** the last lock is cleared.
  25101. */
  25102. setPendingFd(pFile);
  25103. }
  25104. releaseInodeInfo(pFile);
  25105. sqlite3_free(pFile->lockingContext);
  25106. rc = closeUnixFile(id);
  25107. unixLeaveMutex();
  25108. }
  25109. return rc;
  25110. }
  25111. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25112. /*
  25113. ** The code above is the AFP lock implementation. The code is specific
  25114. ** to MacOSX and does not work on other unix platforms. No alternative
  25115. ** is available. If you don't compile for a mac, then the "unix-afp"
  25116. ** VFS is not available.
  25117. **
  25118. ********************* End of the AFP lock implementation **********************
  25119. ******************************************************************************/
  25120. /******************************************************************************
  25121. *************************** Begin NFS Locking ********************************/
  25122. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25123. /*
  25124. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25125. ** must be either NO_LOCK or SHARED_LOCK.
  25126. **
  25127. ** If the locking level of the file descriptor is already at or below
  25128. ** the requested locking level, this routine is a no-op.
  25129. */
  25130. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  25131. return posixUnlock(id, eFileLock, 1);
  25132. }
  25133. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25134. /*
  25135. ** The code above is the NFS lock implementation. The code is specific
  25136. ** to MacOSX and does not work on other unix platforms. No alternative
  25137. ** is available.
  25138. **
  25139. ********************* End of the NFS lock implementation **********************
  25140. ******************************************************************************/
  25141. /******************************************************************************
  25142. **************** Non-locking sqlite3_file methods *****************************
  25143. **
  25144. ** The next division contains implementations for all methods of the
  25145. ** sqlite3_file object other than the locking methods. The locking
  25146. ** methods were defined in divisions above (one locking method per
  25147. ** division). Those methods that are common to all locking modes
  25148. ** are gather together into this division.
  25149. */
  25150. /*
  25151. ** Seek to the offset passed as the second argument, then read cnt
  25152. ** bytes into pBuf. Return the number of bytes actually read.
  25153. **
  25154. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  25155. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  25156. ** one system to another. Since SQLite does not define USE_PREAD
  25157. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  25158. ** See tickets #2741 and #2681.
  25159. **
  25160. ** To avoid stomping the errno value on a failed read the lastErrno value
  25161. ** is set before returning.
  25162. */
  25163. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  25164. int got;
  25165. int prior = 0;
  25166. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  25167. i64 newOffset;
  25168. #endif
  25169. TIMER_START;
  25170. assert( cnt==(cnt&0x1ffff) );
  25171. assert( id->h>2 );
  25172. cnt &= 0x1ffff;
  25173. do{
  25174. #if defined(USE_PREAD)
  25175. got = osPread(id->h, pBuf, cnt, offset);
  25176. SimulateIOError( got = -1 );
  25177. #elif defined(USE_PREAD64)
  25178. got = osPread64(id->h, pBuf, cnt, offset);
  25179. SimulateIOError( got = -1 );
  25180. #else
  25181. newOffset = lseek(id->h, offset, SEEK_SET);
  25182. SimulateIOError( newOffset-- );
  25183. if( newOffset!=offset ){
  25184. if( newOffset == -1 ){
  25185. ((unixFile*)id)->lastErrno = errno;
  25186. }else{
  25187. ((unixFile*)id)->lastErrno = 0;
  25188. }
  25189. return -1;
  25190. }
  25191. got = osRead(id->h, pBuf, cnt);
  25192. #endif
  25193. if( got==cnt ) break;
  25194. if( got<0 ){
  25195. if( errno==EINTR ){ got = 1; continue; }
  25196. prior = 0;
  25197. ((unixFile*)id)->lastErrno = errno;
  25198. break;
  25199. }else if( got>0 ){
  25200. cnt -= got;
  25201. offset += got;
  25202. prior += got;
  25203. pBuf = (void*)(got + (char*)pBuf);
  25204. }
  25205. }while( got>0 );
  25206. TIMER_END;
  25207. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  25208. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  25209. return got+prior;
  25210. }
  25211. /*
  25212. ** Read data from a file into a buffer. Return SQLITE_OK if all
  25213. ** bytes were read successfully and SQLITE_IOERR if anything goes
  25214. ** wrong.
  25215. */
  25216. static int unixRead(
  25217. sqlite3_file *id,
  25218. void *pBuf,
  25219. int amt,
  25220. sqlite3_int64 offset
  25221. ){
  25222. unixFile *pFile = (unixFile *)id;
  25223. int got;
  25224. assert( id );
  25225. assert( offset>=0 );
  25226. assert( amt>0 );
  25227. /* If this is a database file (not a journal, master-journal or temp
  25228. ** file), the bytes in the locking range should never be read or written. */
  25229. #if 0
  25230. assert( pFile->pUnused==0
  25231. || offset>=PENDING_BYTE+512
  25232. || offset+amt<=PENDING_BYTE
  25233. );
  25234. #endif
  25235. #if SQLITE_MAX_MMAP_SIZE>0
  25236. /* Deal with as much of this read request as possible by transfering
  25237. ** data from the memory mapping using memcpy(). */
  25238. if( offset<pFile->mmapSize ){
  25239. if( offset+amt <= pFile->mmapSize ){
  25240. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  25241. return SQLITE_OK;
  25242. }else{
  25243. int nCopy = pFile->mmapSize - offset;
  25244. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  25245. pBuf = &((u8 *)pBuf)[nCopy];
  25246. amt -= nCopy;
  25247. offset += nCopy;
  25248. }
  25249. }
  25250. #endif
  25251. got = seekAndRead(pFile, offset, pBuf, amt);
  25252. if( got==amt ){
  25253. return SQLITE_OK;
  25254. }else if( got<0 ){
  25255. /* lastErrno set by seekAndRead */
  25256. return SQLITE_IOERR_READ;
  25257. }else{
  25258. pFile->lastErrno = 0; /* not a system error */
  25259. /* Unread parts of the buffer must be zero-filled */
  25260. memset(&((char*)pBuf)[got], 0, amt-got);
  25261. return SQLITE_IOERR_SHORT_READ;
  25262. }
  25263. }
  25264. /*
  25265. ** Attempt to seek the file-descriptor passed as the first argument to
  25266. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  25267. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  25268. ** return the actual number of bytes written (which may be less than
  25269. ** nBuf).
  25270. */
  25271. static int seekAndWriteFd(
  25272. int fd, /* File descriptor to write to */
  25273. i64 iOff, /* File offset to begin writing at */
  25274. const void *pBuf, /* Copy data from this buffer to the file */
  25275. int nBuf, /* Size of buffer pBuf in bytes */
  25276. int *piErrno /* OUT: Error number if error occurs */
  25277. ){
  25278. int rc = 0; /* Value returned by system call */
  25279. assert( nBuf==(nBuf&0x1ffff) );
  25280. assert( fd>2 );
  25281. nBuf &= 0x1ffff;
  25282. TIMER_START;
  25283. #if defined(USE_PREAD)
  25284. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  25285. #elif defined(USE_PREAD64)
  25286. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  25287. #else
  25288. do{
  25289. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  25290. SimulateIOError( iSeek-- );
  25291. if( iSeek!=iOff ){
  25292. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  25293. return -1;
  25294. }
  25295. rc = osWrite(fd, pBuf, nBuf);
  25296. }while( rc<0 && errno==EINTR );
  25297. #endif
  25298. TIMER_END;
  25299. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  25300. if( rc<0 && piErrno ) *piErrno = errno;
  25301. return rc;
  25302. }
  25303. /*
  25304. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  25305. ** Return the number of bytes actually read. Update the offset.
  25306. **
  25307. ** To avoid stomping the errno value on a failed write the lastErrno value
  25308. ** is set before returning.
  25309. */
  25310. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  25311. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  25312. }
  25313. /*
  25314. ** Write data from a buffer into a file. Return SQLITE_OK on success
  25315. ** or some other error code on failure.
  25316. */
  25317. static int unixWrite(
  25318. sqlite3_file *id,
  25319. const void *pBuf,
  25320. int amt,
  25321. sqlite3_int64 offset
  25322. ){
  25323. unixFile *pFile = (unixFile*)id;
  25324. int wrote = 0;
  25325. assert( id );
  25326. assert( amt>0 );
  25327. /* If this is a database file (not a journal, master-journal or temp
  25328. ** file), the bytes in the locking range should never be read or written. */
  25329. #if 0
  25330. assert( pFile->pUnused==0
  25331. || offset>=PENDING_BYTE+512
  25332. || offset+amt<=PENDING_BYTE
  25333. );
  25334. #endif
  25335. #ifdef SQLITE_DEBUG
  25336. /* If we are doing a normal write to a database file (as opposed to
  25337. ** doing a hot-journal rollback or a write to some file other than a
  25338. ** normal database file) then record the fact that the database
  25339. ** has changed. If the transaction counter is modified, record that
  25340. ** fact too.
  25341. */
  25342. if( pFile->inNormalWrite ){
  25343. pFile->dbUpdate = 1; /* The database has been modified */
  25344. if( offset<=24 && offset+amt>=27 ){
  25345. int rc;
  25346. char oldCntr[4];
  25347. SimulateIOErrorBenign(1);
  25348. rc = seekAndRead(pFile, 24, oldCntr, 4);
  25349. SimulateIOErrorBenign(0);
  25350. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  25351. pFile->transCntrChng = 1; /* The transaction counter has changed */
  25352. }
  25353. }
  25354. }
  25355. #endif
  25356. #if SQLITE_MAX_MMAP_SIZE>0
  25357. /* Deal with as much of this write request as possible by transfering
  25358. ** data from the memory mapping using memcpy(). */
  25359. if( offset<pFile->mmapSize ){
  25360. if( offset+amt <= pFile->mmapSize ){
  25361. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  25362. return SQLITE_OK;
  25363. }else{
  25364. int nCopy = pFile->mmapSize - offset;
  25365. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  25366. pBuf = &((u8 *)pBuf)[nCopy];
  25367. amt -= nCopy;
  25368. offset += nCopy;
  25369. }
  25370. }
  25371. #endif
  25372. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  25373. amt -= wrote;
  25374. offset += wrote;
  25375. pBuf = &((char*)pBuf)[wrote];
  25376. }
  25377. SimulateIOError(( wrote=(-1), amt=1 ));
  25378. SimulateDiskfullError(( wrote=0, amt=1 ));
  25379. if( amt>0 ){
  25380. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  25381. /* lastErrno set by seekAndWrite */
  25382. return SQLITE_IOERR_WRITE;
  25383. }else{
  25384. pFile->lastErrno = 0; /* not a system error */
  25385. return SQLITE_FULL;
  25386. }
  25387. }
  25388. return SQLITE_OK;
  25389. }
  25390. #ifdef SQLITE_TEST
  25391. /*
  25392. ** Count the number of fullsyncs and normal syncs. This is used to test
  25393. ** that syncs and fullsyncs are occurring at the right times.
  25394. */
  25395. SQLITE_API int sqlite3_sync_count = 0;
  25396. SQLITE_API int sqlite3_fullsync_count = 0;
  25397. #endif
  25398. /*
  25399. ** We do not trust systems to provide a working fdatasync(). Some do.
  25400. ** Others do no. To be safe, we will stick with the (slightly slower)
  25401. ** fsync(). If you know that your system does support fdatasync() correctly,
  25402. ** then simply compile with -Dfdatasync=fdatasync
  25403. */
  25404. #if !defined(fdatasync)
  25405. # define fdatasync fsync
  25406. #endif
  25407. /*
  25408. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  25409. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  25410. ** only available on Mac OS X. But that could change.
  25411. */
  25412. #ifdef F_FULLFSYNC
  25413. # define HAVE_FULLFSYNC 1
  25414. #else
  25415. # define HAVE_FULLFSYNC 0
  25416. #endif
  25417. /*
  25418. ** The fsync() system call does not work as advertised on many
  25419. ** unix systems. The following procedure is an attempt to make
  25420. ** it work better.
  25421. **
  25422. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  25423. ** for testing when we want to run through the test suite quickly.
  25424. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  25425. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  25426. ** or power failure will likely corrupt the database file.
  25427. **
  25428. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  25429. ** The idea behind dataOnly is that it should only write the file content
  25430. ** to disk, not the inode. We only set dataOnly if the file size is
  25431. ** unchanged since the file size is part of the inode. However,
  25432. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  25433. ** file size has changed. The only real difference between fdatasync()
  25434. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  25435. ** inode if the mtime or owner or other inode attributes have changed.
  25436. ** We only care about the file size, not the other file attributes, so
  25437. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  25438. ** So, we always use fdatasync() if it is available, regardless of
  25439. ** the value of the dataOnly flag.
  25440. */
  25441. static int full_fsync(int fd, int fullSync, int dataOnly){
  25442. int rc;
  25443. /* The following "ifdef/elif/else/" block has the same structure as
  25444. ** the one below. It is replicated here solely to avoid cluttering
  25445. ** up the real code with the UNUSED_PARAMETER() macros.
  25446. */
  25447. #ifdef SQLITE_NO_SYNC
  25448. UNUSED_PARAMETER(fd);
  25449. UNUSED_PARAMETER(fullSync);
  25450. UNUSED_PARAMETER(dataOnly);
  25451. #elif HAVE_FULLFSYNC
  25452. UNUSED_PARAMETER(dataOnly);
  25453. #else
  25454. UNUSED_PARAMETER(fullSync);
  25455. UNUSED_PARAMETER(dataOnly);
  25456. #endif
  25457. /* Record the number of times that we do a normal fsync() and
  25458. ** FULLSYNC. This is used during testing to verify that this procedure
  25459. ** gets called with the correct arguments.
  25460. */
  25461. #ifdef SQLITE_TEST
  25462. if( fullSync ) sqlite3_fullsync_count++;
  25463. sqlite3_sync_count++;
  25464. #endif
  25465. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25466. ** no-op
  25467. */
  25468. #ifdef SQLITE_NO_SYNC
  25469. rc = SQLITE_OK;
  25470. #elif HAVE_FULLFSYNC
  25471. if( fullSync ){
  25472. rc = osFcntl(fd, F_FULLFSYNC, 0);
  25473. }else{
  25474. rc = 1;
  25475. }
  25476. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  25477. ** It shouldn't be possible for fullfsync to fail on the local
  25478. ** file system (on OSX), so failure indicates that FULLFSYNC
  25479. ** isn't supported for this file system. So, attempt an fsync
  25480. ** and (for now) ignore the overhead of a superfluous fcntl call.
  25481. ** It'd be better to detect fullfsync support once and avoid
  25482. ** the fcntl call every time sync is called.
  25483. */
  25484. if( rc ) rc = fsync(fd);
  25485. #elif defined(__APPLE__)
  25486. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  25487. ** so currently we default to the macro that redefines fdatasync to fsync
  25488. */
  25489. rc = fsync(fd);
  25490. #else
  25491. rc = fdatasync(fd);
  25492. #if OS_VXWORKS
  25493. if( rc==-1 && errno==ENOTSUP ){
  25494. rc = fsync(fd);
  25495. }
  25496. #endif /* OS_VXWORKS */
  25497. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  25498. if( OS_VXWORKS && rc!= -1 ){
  25499. rc = 0;
  25500. }
  25501. return rc;
  25502. }
  25503. /*
  25504. ** Open a file descriptor to the directory containing file zFilename.
  25505. ** If successful, *pFd is set to the opened file descriptor and
  25506. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  25507. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  25508. ** value.
  25509. **
  25510. ** The directory file descriptor is used for only one thing - to
  25511. ** fsync() a directory to make sure file creation and deletion events
  25512. ** are flushed to disk. Such fsyncs are not needed on newer
  25513. ** journaling filesystems, but are required on older filesystems.
  25514. **
  25515. ** This routine can be overridden using the xSetSysCall interface.
  25516. ** The ability to override this routine was added in support of the
  25517. ** chromium sandbox. Opening a directory is a security risk (we are
  25518. ** told) so making it overrideable allows the chromium sandbox to
  25519. ** replace this routine with a harmless no-op. To make this routine
  25520. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  25521. ** *pFd set to a negative number.
  25522. **
  25523. ** If SQLITE_OK is returned, the caller is responsible for closing
  25524. ** the file descriptor *pFd using close().
  25525. */
  25526. static int openDirectory(const char *zFilename, int *pFd){
  25527. int ii;
  25528. int fd = -1;
  25529. char zDirname[MAX_PATHNAME+1];
  25530. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  25531. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  25532. if( ii>0 ){
  25533. zDirname[ii] = '\0';
  25534. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  25535. if( fd>=0 ){
  25536. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  25537. }
  25538. }
  25539. *pFd = fd;
  25540. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  25541. }
  25542. /*
  25543. ** Make sure all writes to a particular file are committed to disk.
  25544. **
  25545. ** If dataOnly==0 then both the file itself and its metadata (file
  25546. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  25547. ** file data is synced.
  25548. **
  25549. ** Under Unix, also make sure that the directory entry for the file
  25550. ** has been created by fsync-ing the directory that contains the file.
  25551. ** If we do not do this and we encounter a power failure, the directory
  25552. ** entry for the journal might not exist after we reboot. The next
  25553. ** SQLite to access the file will not know that the journal exists (because
  25554. ** the directory entry for the journal was never created) and the transaction
  25555. ** will not roll back - possibly leading to database corruption.
  25556. */
  25557. static int unixSync(sqlite3_file *id, int flags){
  25558. int rc;
  25559. unixFile *pFile = (unixFile*)id;
  25560. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  25561. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  25562. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  25563. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  25564. || (flags&0x0F)==SQLITE_SYNC_FULL
  25565. );
  25566. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  25567. ** line is to test that doing so does not cause any problems.
  25568. */
  25569. SimulateDiskfullError( return SQLITE_FULL );
  25570. assert( pFile );
  25571. OSTRACE(("SYNC %-3d\n", pFile->h));
  25572. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  25573. SimulateIOError( rc=1 );
  25574. if( rc ){
  25575. pFile->lastErrno = errno;
  25576. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  25577. }
  25578. /* Also fsync the directory containing the file if the DIRSYNC flag
  25579. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  25580. ** are unable to fsync a directory, so ignore errors on the fsync.
  25581. */
  25582. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  25583. int dirfd;
  25584. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  25585. HAVE_FULLFSYNC, isFullsync));
  25586. rc = osOpenDirectory(pFile->zPath, &dirfd);
  25587. if( rc==SQLITE_OK && dirfd>=0 ){
  25588. full_fsync(dirfd, 0, 0);
  25589. robust_close(pFile, dirfd, __LINE__);
  25590. }else if( rc==SQLITE_CANTOPEN ){
  25591. rc = SQLITE_OK;
  25592. }
  25593. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  25594. }
  25595. return rc;
  25596. }
  25597. /*
  25598. ** Truncate an open file to a specified size
  25599. */
  25600. static int unixTruncate(sqlite3_file *id, i64 nByte){
  25601. unixFile *pFile = (unixFile *)id;
  25602. int rc;
  25603. assert( pFile );
  25604. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  25605. /* If the user has configured a chunk-size for this file, truncate the
  25606. ** file so that it consists of an integer number of chunks (i.e. the
  25607. ** actual file size after the operation may be larger than the requested
  25608. ** size).
  25609. */
  25610. if( pFile->szChunk>0 ){
  25611. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  25612. }
  25613. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  25614. if( rc ){
  25615. pFile->lastErrno = errno;
  25616. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25617. }else{
  25618. #ifdef SQLITE_DEBUG
  25619. /* If we are doing a normal write to a database file (as opposed to
  25620. ** doing a hot-journal rollback or a write to some file other than a
  25621. ** normal database file) and we truncate the file to zero length,
  25622. ** that effectively updates the change counter. This might happen
  25623. ** when restoring a database using the backup API from a zero-length
  25624. ** source.
  25625. */
  25626. if( pFile->inNormalWrite && nByte==0 ){
  25627. pFile->transCntrChng = 1;
  25628. }
  25629. #endif
  25630. #if SQLITE_MAX_MMAP_SIZE>0
  25631. /* If the file was just truncated to a size smaller than the currently
  25632. ** mapped region, reduce the effective mapping size as well. SQLite will
  25633. ** use read() and write() to access data beyond this point from now on.
  25634. */
  25635. if( nByte<pFile->mmapSize ){
  25636. pFile->mmapSize = nByte;
  25637. }
  25638. #endif
  25639. return SQLITE_OK;
  25640. }
  25641. }
  25642. /*
  25643. ** Determine the current size of a file in bytes
  25644. */
  25645. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  25646. int rc;
  25647. struct stat buf;
  25648. assert( id );
  25649. rc = osFstat(((unixFile*)id)->h, &buf);
  25650. SimulateIOError( rc=1 );
  25651. if( rc!=0 ){
  25652. ((unixFile*)id)->lastErrno = errno;
  25653. return SQLITE_IOERR_FSTAT;
  25654. }
  25655. *pSize = buf.st_size;
  25656. /* When opening a zero-size database, the findInodeInfo() procedure
  25657. ** writes a single byte into that file in order to work around a bug
  25658. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  25659. ** layers, we need to report this file size as zero even though it is
  25660. ** really 1. Ticket #3260.
  25661. */
  25662. if( *pSize==1 ) *pSize = 0;
  25663. return SQLITE_OK;
  25664. }
  25665. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25666. /*
  25667. ** Handler for proxy-locking file-control verbs. Defined below in the
  25668. ** proxying locking division.
  25669. */
  25670. static int proxyFileControl(sqlite3_file*,int,void*);
  25671. #endif
  25672. /*
  25673. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  25674. ** file-control operation. Enlarge the database to nBytes in size
  25675. ** (rounded up to the next chunk-size). If the database is already
  25676. ** nBytes or larger, this routine is a no-op.
  25677. */
  25678. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  25679. if( pFile->szChunk>0 ){
  25680. i64 nSize; /* Required file size */
  25681. struct stat buf; /* Used to hold return values of fstat() */
  25682. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  25683. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  25684. if( nSize>(i64)buf.st_size ){
  25685. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25686. /* The code below is handling the return value of osFallocate()
  25687. ** correctly. posix_fallocate() is defined to "returns zero on success,
  25688. ** or an error number on failure". See the manpage for details. */
  25689. int err;
  25690. do{
  25691. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  25692. }while( err==EINTR );
  25693. if( err ) return SQLITE_IOERR_WRITE;
  25694. #else
  25695. /* If the OS does not have posix_fallocate(), fake it. First use
  25696. ** ftruncate() to set the file size, then write a single byte to
  25697. ** the last byte in each block within the extended region. This
  25698. ** is the same technique used by glibc to implement posix_fallocate()
  25699. ** on systems that do not have a real fallocate() system call.
  25700. */
  25701. int nBlk = buf.st_blksize; /* File-system block size */
  25702. i64 iWrite; /* Next offset to write to */
  25703. if( robust_ftruncate(pFile->h, nSize) ){
  25704. pFile->lastErrno = errno;
  25705. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25706. }
  25707. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  25708. while( iWrite<nSize ){
  25709. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  25710. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  25711. iWrite += nBlk;
  25712. }
  25713. #endif
  25714. }
  25715. }
  25716. #if SQLITE_MAX_MMAP_SIZE>0
  25717. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  25718. int rc;
  25719. if( pFile->szChunk<=0 ){
  25720. if( robust_ftruncate(pFile->h, nByte) ){
  25721. pFile->lastErrno = errno;
  25722. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25723. }
  25724. }
  25725. rc = unixMapfile(pFile, nByte);
  25726. return rc;
  25727. }
  25728. #endif
  25729. return SQLITE_OK;
  25730. }
  25731. /*
  25732. ** If *pArg is inititially negative then this is a query. Set *pArg to
  25733. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  25734. **
  25735. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  25736. */
  25737. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  25738. if( *pArg<0 ){
  25739. *pArg = (pFile->ctrlFlags & mask)!=0;
  25740. }else if( (*pArg)==0 ){
  25741. pFile->ctrlFlags &= ~mask;
  25742. }else{
  25743. pFile->ctrlFlags |= mask;
  25744. }
  25745. }
  25746. /* Forward declaration */
  25747. static int unixGetTempname(int nBuf, char *zBuf);
  25748. /*
  25749. ** Information and control of an open file handle.
  25750. */
  25751. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  25752. unixFile *pFile = (unixFile*)id;
  25753. switch( op ){
  25754. case SQLITE_FCNTL_LOCKSTATE: {
  25755. *(int*)pArg = pFile->eFileLock;
  25756. return SQLITE_OK;
  25757. }
  25758. case SQLITE_LAST_ERRNO: {
  25759. *(int*)pArg = pFile->lastErrno;
  25760. return SQLITE_OK;
  25761. }
  25762. case SQLITE_FCNTL_CHUNK_SIZE: {
  25763. pFile->szChunk = *(int *)pArg;
  25764. return SQLITE_OK;
  25765. }
  25766. case SQLITE_FCNTL_SIZE_HINT: {
  25767. int rc;
  25768. SimulateIOErrorBenign(1);
  25769. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  25770. SimulateIOErrorBenign(0);
  25771. return rc;
  25772. }
  25773. case SQLITE_FCNTL_PERSIST_WAL: {
  25774. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  25775. return SQLITE_OK;
  25776. }
  25777. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  25778. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  25779. return SQLITE_OK;
  25780. }
  25781. case SQLITE_FCNTL_VFSNAME: {
  25782. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  25783. return SQLITE_OK;
  25784. }
  25785. case SQLITE_FCNTL_TEMPFILENAME: {
  25786. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  25787. if( zTFile ){
  25788. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  25789. *(char**)pArg = zTFile;
  25790. }
  25791. return SQLITE_OK;
  25792. }
  25793. #if SQLITE_MAX_MMAP_SIZE>0
  25794. case SQLITE_FCNTL_MMAP_SIZE: {
  25795. i64 newLimit = *(i64*)pArg;
  25796. int rc = SQLITE_OK;
  25797. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  25798. newLimit = sqlite3GlobalConfig.mxMmap;
  25799. }
  25800. *(i64*)pArg = pFile->mmapSizeMax;
  25801. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  25802. pFile->mmapSizeMax = newLimit;
  25803. if( pFile->mmapSize>0 ){
  25804. unixUnmapfile(pFile);
  25805. rc = unixMapfile(pFile, -1);
  25806. }
  25807. }
  25808. return rc;
  25809. }
  25810. #endif
  25811. #ifdef SQLITE_DEBUG
  25812. /* The pager calls this method to signal that it has done
  25813. ** a rollback and that the database is therefore unchanged and
  25814. ** it hence it is OK for the transaction change counter to be
  25815. ** unchanged.
  25816. */
  25817. case SQLITE_FCNTL_DB_UNCHANGED: {
  25818. ((unixFile*)id)->dbUpdate = 0;
  25819. return SQLITE_OK;
  25820. }
  25821. #endif
  25822. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25823. case SQLITE_SET_LOCKPROXYFILE:
  25824. case SQLITE_GET_LOCKPROXYFILE: {
  25825. return proxyFileControl(id,op,pArg);
  25826. }
  25827. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25828. }
  25829. return SQLITE_NOTFOUND;
  25830. }
  25831. /*
  25832. ** Return the sector size in bytes of the underlying block device for
  25833. ** the specified file. This is almost always 512 bytes, but may be
  25834. ** larger for some devices.
  25835. **
  25836. ** SQLite code assumes this function cannot fail. It also assumes that
  25837. ** if two files are created in the same file-system directory (i.e.
  25838. ** a database and its journal file) that the sector size will be the
  25839. ** same for both.
  25840. */
  25841. #ifndef __QNXNTO__
  25842. static int unixSectorSize(sqlite3_file *NotUsed){
  25843. UNUSED_PARAMETER(NotUsed);
  25844. return SQLITE_DEFAULT_SECTOR_SIZE;
  25845. }
  25846. #endif
  25847. /*
  25848. ** The following version of unixSectorSize() is optimized for QNX.
  25849. */
  25850. #ifdef __QNXNTO__
  25851. #include <sys/dcmd_blk.h>
  25852. #include <sys/statvfs.h>
  25853. static int unixSectorSize(sqlite3_file *id){
  25854. unixFile *pFile = (unixFile*)id;
  25855. if( pFile->sectorSize == 0 ){
  25856. struct statvfs fsInfo;
  25857. /* Set defaults for non-supported filesystems */
  25858. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25859. pFile->deviceCharacteristics = 0;
  25860. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  25861. return pFile->sectorSize;
  25862. }
  25863. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  25864. pFile->sectorSize = fsInfo.f_bsize;
  25865. pFile->deviceCharacteristics =
  25866. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  25867. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25868. ** the write succeeds */
  25869. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25870. ** so it is ordered */
  25871. 0;
  25872. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  25873. pFile->sectorSize = fsInfo.f_bsize;
  25874. pFile->deviceCharacteristics =
  25875. /* etfs cluster size writes are atomic */
  25876. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  25877. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25878. ** the write succeeds */
  25879. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25880. ** so it is ordered */
  25881. 0;
  25882. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  25883. pFile->sectorSize = fsInfo.f_bsize;
  25884. pFile->deviceCharacteristics =
  25885. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  25886. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25887. ** the write succeeds */
  25888. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25889. ** so it is ordered */
  25890. 0;
  25891. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  25892. pFile->sectorSize = fsInfo.f_bsize;
  25893. pFile->deviceCharacteristics =
  25894. /* full bitset of atomics from max sector size and smaller */
  25895. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25896. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25897. ** so it is ordered */
  25898. 0;
  25899. }else if( strstr(fsInfo.f_basetype, "dos") ){
  25900. pFile->sectorSize = fsInfo.f_bsize;
  25901. pFile->deviceCharacteristics =
  25902. /* full bitset of atomics from max sector size and smaller */
  25903. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25904. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25905. ** so it is ordered */
  25906. 0;
  25907. }else{
  25908. pFile->deviceCharacteristics =
  25909. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  25910. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25911. ** the write succeeds */
  25912. 0;
  25913. }
  25914. }
  25915. /* Last chance verification. If the sector size isn't a multiple of 512
  25916. ** then it isn't valid.*/
  25917. if( pFile->sectorSize % 512 != 0 ){
  25918. pFile->deviceCharacteristics = 0;
  25919. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25920. }
  25921. return pFile->sectorSize;
  25922. }
  25923. #endif /* __QNXNTO__ */
  25924. /*
  25925. ** Return the device characteristics for the file.
  25926. **
  25927. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  25928. ** However, that choice is contraversial since technically the underlying
  25929. ** file system does not always provide powersafe overwrites. (In other
  25930. ** words, after a power-loss event, parts of the file that were never
  25931. ** written might end up being altered.) However, non-PSOW behavior is very,
  25932. ** very rare. And asserting PSOW makes a large reduction in the amount
  25933. ** of required I/O for journaling, since a lot of padding is eliminated.
  25934. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  25935. ** available to turn it off and URI query parameter available to turn it off.
  25936. */
  25937. static int unixDeviceCharacteristics(sqlite3_file *id){
  25938. unixFile *p = (unixFile*)id;
  25939. int rc = 0;
  25940. #ifdef __QNXNTO__
  25941. if( p->sectorSize==0 ) unixSectorSize(id);
  25942. rc = p->deviceCharacteristics;
  25943. #endif
  25944. if( p->ctrlFlags & UNIXFILE_PSOW ){
  25945. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  25946. }
  25947. return rc;
  25948. }
  25949. #ifndef SQLITE_OMIT_WAL
  25950. /*
  25951. ** Object used to represent an shared memory buffer.
  25952. **
  25953. ** When multiple threads all reference the same wal-index, each thread
  25954. ** has its own unixShm object, but they all point to a single instance
  25955. ** of this unixShmNode object. In other words, each wal-index is opened
  25956. ** only once per process.
  25957. **
  25958. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25959. ** We could coalesce this object into unixInodeInfo, but that would mean
  25960. ** every open file that does not use shared memory (in other words, most
  25961. ** open files) would have to carry around this extra information. So
  25962. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25963. ** and the unixShmNode object is created only when needed.
  25964. **
  25965. ** unixMutexHeld() must be true when creating or destroying
  25966. ** this object or while reading or writing the following fields:
  25967. **
  25968. ** nRef
  25969. **
  25970. ** The following fields are read-only after the object is created:
  25971. **
  25972. ** fid
  25973. ** zFilename
  25974. **
  25975. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25976. ** unixMutexHeld() is true when reading or writing any other field
  25977. ** in this structure.
  25978. */
  25979. struct unixShmNode {
  25980. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25981. sqlite3_mutex *mutex; /* Mutex to access this object */
  25982. char *zFilename; /* Name of the mmapped file */
  25983. int h; /* Open file descriptor */
  25984. int szRegion; /* Size of shared-memory regions */
  25985. u16 nRegion; /* Size of array apRegion */
  25986. u8 isReadonly; /* True if read-only */
  25987. char **apRegion; /* Array of mapped shared-memory regions */
  25988. int nRef; /* Number of unixShm objects pointing to this */
  25989. unixShm *pFirst; /* All unixShm objects pointing to this */
  25990. #ifdef SQLITE_DEBUG
  25991. u8 exclMask; /* Mask of exclusive locks held */
  25992. u8 sharedMask; /* Mask of shared locks held */
  25993. u8 nextShmId; /* Next available unixShm.id value */
  25994. #endif
  25995. };
  25996. /*
  25997. ** Structure used internally by this VFS to record the state of an
  25998. ** open shared memory connection.
  25999. **
  26000. ** The following fields are initialized when this object is created and
  26001. ** are read-only thereafter:
  26002. **
  26003. ** unixShm.pFile
  26004. ** unixShm.id
  26005. **
  26006. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  26007. ** while accessing any read/write fields.
  26008. */
  26009. struct unixShm {
  26010. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  26011. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  26012. u8 hasMutex; /* True if holding the unixShmNode mutex */
  26013. u8 id; /* Id of this connection within its unixShmNode */
  26014. u16 sharedMask; /* Mask of shared locks held */
  26015. u16 exclMask; /* Mask of exclusive locks held */
  26016. };
  26017. /*
  26018. ** Constants used for locking
  26019. */
  26020. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  26021. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  26022. /*
  26023. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  26024. **
  26025. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  26026. ** otherwise.
  26027. */
  26028. static int unixShmSystemLock(
  26029. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  26030. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  26031. int ofst, /* First byte of the locking range */
  26032. int n /* Number of bytes to lock */
  26033. ){
  26034. struct flock f; /* The posix advisory locking structure */
  26035. int rc = SQLITE_OK; /* Result code form fcntl() */
  26036. /* Access to the unixShmNode object is serialized by the caller */
  26037. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  26038. /* Shared locks never span more than one byte */
  26039. assert( n==1 || lockType!=F_RDLCK );
  26040. /* Locks are within range */
  26041. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  26042. if( pShmNode->h>=0 ){
  26043. /* Initialize the locking parameters */
  26044. memset(&f, 0, sizeof(f));
  26045. f.l_type = lockType;
  26046. f.l_whence = SEEK_SET;
  26047. f.l_start = ofst;
  26048. f.l_len = n;
  26049. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  26050. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  26051. }
  26052. /* Update the global lock state and do debug tracing */
  26053. #ifdef SQLITE_DEBUG
  26054. { u16 mask;
  26055. OSTRACE(("SHM-LOCK "));
  26056. mask = (1<<(ofst+n)) - (1<<ofst);
  26057. if( rc==SQLITE_OK ){
  26058. if( lockType==F_UNLCK ){
  26059. OSTRACE(("unlock %d ok", ofst));
  26060. pShmNode->exclMask &= ~mask;
  26061. pShmNode->sharedMask &= ~mask;
  26062. }else if( lockType==F_RDLCK ){
  26063. OSTRACE(("read-lock %d ok", ofst));
  26064. pShmNode->exclMask &= ~mask;
  26065. pShmNode->sharedMask |= mask;
  26066. }else{
  26067. assert( lockType==F_WRLCK );
  26068. OSTRACE(("write-lock %d ok", ofst));
  26069. pShmNode->exclMask |= mask;
  26070. pShmNode->sharedMask &= ~mask;
  26071. }
  26072. }else{
  26073. if( lockType==F_UNLCK ){
  26074. OSTRACE(("unlock %d failed", ofst));
  26075. }else if( lockType==F_RDLCK ){
  26076. OSTRACE(("read-lock failed"));
  26077. }else{
  26078. assert( lockType==F_WRLCK );
  26079. OSTRACE(("write-lock %d failed", ofst));
  26080. }
  26081. }
  26082. OSTRACE((" - afterwards %03x,%03x\n",
  26083. pShmNode->sharedMask, pShmNode->exclMask));
  26084. }
  26085. #endif
  26086. return rc;
  26087. }
  26088. /*
  26089. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  26090. **
  26091. ** This is not a VFS shared-memory method; it is a utility function called
  26092. ** by VFS shared-memory methods.
  26093. */
  26094. static void unixShmPurge(unixFile *pFd){
  26095. unixShmNode *p = pFd->pInode->pShmNode;
  26096. assert( unixMutexHeld() );
  26097. if( p && p->nRef==0 ){
  26098. int i;
  26099. assert( p->pInode==pFd->pInode );
  26100. sqlite3_mutex_free(p->mutex);
  26101. for(i=0; i<p->nRegion; i++){
  26102. if( p->h>=0 ){
  26103. osMunmap(p->apRegion[i], p->szRegion);
  26104. }else{
  26105. sqlite3_free(p->apRegion[i]);
  26106. }
  26107. }
  26108. sqlite3_free(p->apRegion);
  26109. if( p->h>=0 ){
  26110. robust_close(pFd, p->h, __LINE__);
  26111. p->h = -1;
  26112. }
  26113. p->pInode->pShmNode = 0;
  26114. sqlite3_free(p);
  26115. }
  26116. }
  26117. /*
  26118. ** Open a shared-memory area associated with open database file pDbFd.
  26119. ** This particular implementation uses mmapped files.
  26120. **
  26121. ** The file used to implement shared-memory is in the same directory
  26122. ** as the open database file and has the same name as the open database
  26123. ** file with the "-shm" suffix added. For example, if the database file
  26124. ** is "/home/user1/config.db" then the file that is created and mmapped
  26125. ** for shared memory will be called "/home/user1/config.db-shm".
  26126. **
  26127. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  26128. ** some other tmpfs mount. But if a file in a different directory
  26129. ** from the database file is used, then differing access permissions
  26130. ** or a chroot() might cause two different processes on the same
  26131. ** database to end up using different files for shared memory -
  26132. ** meaning that their memory would not really be shared - resulting
  26133. ** in database corruption. Nevertheless, this tmpfs file usage
  26134. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  26135. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  26136. ** option results in an incompatible build of SQLite; builds of SQLite
  26137. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  26138. ** same database file at the same time, database corruption will likely
  26139. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  26140. ** "unsupported" and may go away in a future SQLite release.
  26141. **
  26142. ** When opening a new shared-memory file, if no other instances of that
  26143. ** file are currently open, in this process or in other processes, then
  26144. ** the file must be truncated to zero length or have its header cleared.
  26145. **
  26146. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  26147. ** that means that an exclusive lock is held on the database file and
  26148. ** that no other processes are able to read or write the database. In
  26149. ** that case, we do not really need shared memory. No shared memory
  26150. ** file is created. The shared memory will be simulated with heap memory.
  26151. */
  26152. static int unixOpenSharedMemory(unixFile *pDbFd){
  26153. struct unixShm *p = 0; /* The connection to be opened */
  26154. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  26155. int rc; /* Result code */
  26156. unixInodeInfo *pInode; /* The inode of fd */
  26157. char *zShmFilename; /* Name of the file used for SHM */
  26158. int nShmFilename; /* Size of the SHM filename in bytes */
  26159. /* Allocate space for the new unixShm object. */
  26160. p = sqlite3_malloc( sizeof(*p) );
  26161. if( p==0 ) return SQLITE_NOMEM;
  26162. memset(p, 0, sizeof(*p));
  26163. assert( pDbFd->pShm==0 );
  26164. /* Check to see if a unixShmNode object already exists. Reuse an existing
  26165. ** one if present. Create a new one if necessary.
  26166. */
  26167. unixEnterMutex();
  26168. pInode = pDbFd->pInode;
  26169. pShmNode = pInode->pShmNode;
  26170. if( pShmNode==0 ){
  26171. struct stat sStat; /* fstat() info for database file */
  26172. /* Call fstat() to figure out the permissions on the database file. If
  26173. ** a new *-shm file is created, an attempt will be made to create it
  26174. ** with the same permissions.
  26175. */
  26176. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  26177. rc = SQLITE_IOERR_FSTAT;
  26178. goto shm_open_err;
  26179. }
  26180. #ifdef SQLITE_SHM_DIRECTORY
  26181. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  26182. #else
  26183. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  26184. #endif
  26185. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  26186. if( pShmNode==0 ){
  26187. rc = SQLITE_NOMEM;
  26188. goto shm_open_err;
  26189. }
  26190. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  26191. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  26192. #ifdef SQLITE_SHM_DIRECTORY
  26193. sqlite3_snprintf(nShmFilename, zShmFilename,
  26194. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  26195. (u32)sStat.st_ino, (u32)sStat.st_dev);
  26196. #else
  26197. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  26198. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  26199. #endif
  26200. pShmNode->h = -1;
  26201. pDbFd->pInode->pShmNode = pShmNode;
  26202. pShmNode->pInode = pDbFd->pInode;
  26203. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  26204. if( pShmNode->mutex==0 ){
  26205. rc = SQLITE_NOMEM;
  26206. goto shm_open_err;
  26207. }
  26208. if( pInode->bProcessLock==0 ){
  26209. int openFlags = O_RDWR | O_CREAT;
  26210. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  26211. openFlags = O_RDONLY;
  26212. pShmNode->isReadonly = 1;
  26213. }
  26214. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  26215. if( pShmNode->h<0 ){
  26216. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  26217. goto shm_open_err;
  26218. }
  26219. /* If this process is running as root, make sure that the SHM file
  26220. ** is owned by the same user that owns the original database. Otherwise,
  26221. ** the original owner will not be able to connect.
  26222. */
  26223. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  26224. /* Check to see if another process is holding the dead-man switch.
  26225. ** If not, truncate the file to zero length.
  26226. */
  26227. rc = SQLITE_OK;
  26228. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  26229. if( robust_ftruncate(pShmNode->h, 0) ){
  26230. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  26231. }
  26232. }
  26233. if( rc==SQLITE_OK ){
  26234. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  26235. }
  26236. if( rc ) goto shm_open_err;
  26237. }
  26238. }
  26239. /* Make the new connection a child of the unixShmNode */
  26240. p->pShmNode = pShmNode;
  26241. #ifdef SQLITE_DEBUG
  26242. p->id = pShmNode->nextShmId++;
  26243. #endif
  26244. pShmNode->nRef++;
  26245. pDbFd->pShm = p;
  26246. unixLeaveMutex();
  26247. /* The reference count on pShmNode has already been incremented under
  26248. ** the cover of the unixEnterMutex() mutex and the pointer from the
  26249. ** new (struct unixShm) object to the pShmNode has been set. All that is
  26250. ** left to do is to link the new object into the linked list starting
  26251. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  26252. ** mutex.
  26253. */
  26254. sqlite3_mutex_enter(pShmNode->mutex);
  26255. p->pNext = pShmNode->pFirst;
  26256. pShmNode->pFirst = p;
  26257. sqlite3_mutex_leave(pShmNode->mutex);
  26258. return SQLITE_OK;
  26259. /* Jump here on any error */
  26260. shm_open_err:
  26261. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  26262. sqlite3_free(p);
  26263. unixLeaveMutex();
  26264. return rc;
  26265. }
  26266. /*
  26267. ** This function is called to obtain a pointer to region iRegion of the
  26268. ** shared-memory associated with the database file fd. Shared-memory regions
  26269. ** are numbered starting from zero. Each shared-memory region is szRegion
  26270. ** bytes in size.
  26271. **
  26272. ** If an error occurs, an error code is returned and *pp is set to NULL.
  26273. **
  26274. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  26275. ** region has not been allocated (by any client, including one running in a
  26276. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  26277. ** bExtend is non-zero and the requested shared-memory region has not yet
  26278. ** been allocated, it is allocated by this function.
  26279. **
  26280. ** If the shared-memory region has already been allocated or is allocated by
  26281. ** this call as described above, then it is mapped into this processes
  26282. ** address space (if it is not already), *pp is set to point to the mapped
  26283. ** memory and SQLITE_OK returned.
  26284. */
  26285. static int unixShmMap(
  26286. sqlite3_file *fd, /* Handle open on database file */
  26287. int iRegion, /* Region to retrieve */
  26288. int szRegion, /* Size of regions */
  26289. int bExtend, /* True to extend file if necessary */
  26290. void volatile **pp /* OUT: Mapped memory */
  26291. ){
  26292. unixFile *pDbFd = (unixFile*)fd;
  26293. unixShm *p;
  26294. unixShmNode *pShmNode;
  26295. int rc = SQLITE_OK;
  26296. /* If the shared-memory file has not yet been opened, open it now. */
  26297. if( pDbFd->pShm==0 ){
  26298. rc = unixOpenSharedMemory(pDbFd);
  26299. if( rc!=SQLITE_OK ) return rc;
  26300. }
  26301. p = pDbFd->pShm;
  26302. pShmNode = p->pShmNode;
  26303. sqlite3_mutex_enter(pShmNode->mutex);
  26304. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  26305. assert( pShmNode->pInode==pDbFd->pInode );
  26306. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26307. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26308. if( pShmNode->nRegion<=iRegion ){
  26309. char **apNew; /* New apRegion[] array */
  26310. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  26311. struct stat sStat; /* Used by fstat() */
  26312. pShmNode->szRegion = szRegion;
  26313. if( pShmNode->h>=0 ){
  26314. /* The requested region is not mapped into this processes address space.
  26315. ** Check to see if it has been allocated (i.e. if the wal-index file is
  26316. ** large enough to contain the requested region).
  26317. */
  26318. if( osFstat(pShmNode->h, &sStat) ){
  26319. rc = SQLITE_IOERR_SHMSIZE;
  26320. goto shmpage_out;
  26321. }
  26322. if( sStat.st_size<nByte ){
  26323. /* The requested memory region does not exist. If bExtend is set to
  26324. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  26325. */
  26326. if( !bExtend ){
  26327. goto shmpage_out;
  26328. }
  26329. /* Alternatively, if bExtend is true, extend the file. Do this by
  26330. ** writing a single byte to the end of each (OS) page being
  26331. ** allocated or extended. Technically, we need only write to the
  26332. ** last page in order to extend the file. But writing to all new
  26333. ** pages forces the OS to allocate them immediately, which reduces
  26334. ** the chances of SIGBUS while accessing the mapped region later on.
  26335. */
  26336. else{
  26337. static const int pgsz = 4096;
  26338. int iPg;
  26339. /* Write to the last byte of each newly allocated or extended page */
  26340. assert( (nByte % pgsz)==0 );
  26341. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  26342. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  26343. const char *zFile = pShmNode->zFilename;
  26344. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  26345. goto shmpage_out;
  26346. }
  26347. }
  26348. }
  26349. }
  26350. }
  26351. /* Map the requested memory region into this processes address space. */
  26352. apNew = (char **)sqlite3_realloc(
  26353. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  26354. );
  26355. if( !apNew ){
  26356. rc = SQLITE_IOERR_NOMEM;
  26357. goto shmpage_out;
  26358. }
  26359. pShmNode->apRegion = apNew;
  26360. while(pShmNode->nRegion<=iRegion){
  26361. void *pMem;
  26362. if( pShmNode->h>=0 ){
  26363. pMem = osMmap(0, szRegion,
  26364. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  26365. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  26366. );
  26367. if( pMem==MAP_FAILED ){
  26368. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  26369. goto shmpage_out;
  26370. }
  26371. }else{
  26372. pMem = sqlite3_malloc(szRegion);
  26373. if( pMem==0 ){
  26374. rc = SQLITE_NOMEM;
  26375. goto shmpage_out;
  26376. }
  26377. memset(pMem, 0, szRegion);
  26378. }
  26379. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  26380. pShmNode->nRegion++;
  26381. }
  26382. }
  26383. shmpage_out:
  26384. if( pShmNode->nRegion>iRegion ){
  26385. *pp = pShmNode->apRegion[iRegion];
  26386. }else{
  26387. *pp = 0;
  26388. }
  26389. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  26390. sqlite3_mutex_leave(pShmNode->mutex);
  26391. return rc;
  26392. }
  26393. /*
  26394. ** Change the lock state for a shared-memory segment.
  26395. **
  26396. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  26397. ** different here than in posix. In xShmLock(), one can go from unlocked
  26398. ** to shared and back or from unlocked to exclusive and back. But one may
  26399. ** not go from shared to exclusive or from exclusive to shared.
  26400. */
  26401. static int unixShmLock(
  26402. sqlite3_file *fd, /* Database file holding the shared memory */
  26403. int ofst, /* First lock to acquire or release */
  26404. int n, /* Number of locks to acquire or release */
  26405. int flags /* What to do with the lock */
  26406. ){
  26407. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  26408. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  26409. unixShm *pX; /* For looping over all siblings */
  26410. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  26411. int rc = SQLITE_OK; /* Result code */
  26412. u16 mask; /* Mask of locks to take or release */
  26413. assert( pShmNode==pDbFd->pInode->pShmNode );
  26414. assert( pShmNode->pInode==pDbFd->pInode );
  26415. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  26416. assert( n>=1 );
  26417. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  26418. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  26419. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  26420. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  26421. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  26422. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26423. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26424. mask = (1<<(ofst+n)) - (1<<ofst);
  26425. assert( n>1 || mask==(1<<ofst) );
  26426. sqlite3_mutex_enter(pShmNode->mutex);
  26427. if( flags & SQLITE_SHM_UNLOCK ){
  26428. u16 allMask = 0; /* Mask of locks held by siblings */
  26429. /* See if any siblings hold this same lock */
  26430. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26431. if( pX==p ) continue;
  26432. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  26433. allMask |= pX->sharedMask;
  26434. }
  26435. /* Unlock the system-level locks */
  26436. if( (mask & allMask)==0 ){
  26437. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  26438. }else{
  26439. rc = SQLITE_OK;
  26440. }
  26441. /* Undo the local locks */
  26442. if( rc==SQLITE_OK ){
  26443. p->exclMask &= ~mask;
  26444. p->sharedMask &= ~mask;
  26445. }
  26446. }else if( flags & SQLITE_SHM_SHARED ){
  26447. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  26448. /* Find out which shared locks are already held by sibling connections.
  26449. ** If any sibling already holds an exclusive lock, go ahead and return
  26450. ** SQLITE_BUSY.
  26451. */
  26452. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26453. if( (pX->exclMask & mask)!=0 ){
  26454. rc = SQLITE_BUSY;
  26455. break;
  26456. }
  26457. allShared |= pX->sharedMask;
  26458. }
  26459. /* Get shared locks at the system level, if necessary */
  26460. if( rc==SQLITE_OK ){
  26461. if( (allShared & mask)==0 ){
  26462. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  26463. }else{
  26464. rc = SQLITE_OK;
  26465. }
  26466. }
  26467. /* Get the local shared locks */
  26468. if( rc==SQLITE_OK ){
  26469. p->sharedMask |= mask;
  26470. }
  26471. }else{
  26472. /* Make sure no sibling connections hold locks that will block this
  26473. ** lock. If any do, return SQLITE_BUSY right away.
  26474. */
  26475. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26476. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  26477. rc = SQLITE_BUSY;
  26478. break;
  26479. }
  26480. }
  26481. /* Get the exclusive locks at the system level. Then if successful
  26482. ** also mark the local connection as being locked.
  26483. */
  26484. if( rc==SQLITE_OK ){
  26485. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  26486. if( rc==SQLITE_OK ){
  26487. assert( (p->sharedMask & mask)==0 );
  26488. p->exclMask |= mask;
  26489. }
  26490. }
  26491. }
  26492. sqlite3_mutex_leave(pShmNode->mutex);
  26493. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  26494. p->id, getpid(), p->sharedMask, p->exclMask));
  26495. return rc;
  26496. }
  26497. /*
  26498. ** Implement a memory barrier or memory fence on shared memory.
  26499. **
  26500. ** All loads and stores begun before the barrier must complete before
  26501. ** any load or store begun after the barrier.
  26502. */
  26503. static void unixShmBarrier(
  26504. sqlite3_file *fd /* Database file holding the shared memory */
  26505. ){
  26506. UNUSED_PARAMETER(fd);
  26507. unixEnterMutex();
  26508. unixLeaveMutex();
  26509. }
  26510. /*
  26511. ** Close a connection to shared-memory. Delete the underlying
  26512. ** storage if deleteFlag is true.
  26513. **
  26514. ** If there is no shared memory associated with the connection then this
  26515. ** routine is a harmless no-op.
  26516. */
  26517. static int unixShmUnmap(
  26518. sqlite3_file *fd, /* The underlying database file */
  26519. int deleteFlag /* Delete shared-memory if true */
  26520. ){
  26521. unixShm *p; /* The connection to be closed */
  26522. unixShmNode *pShmNode; /* The underlying shared-memory file */
  26523. unixShm **pp; /* For looping over sibling connections */
  26524. unixFile *pDbFd; /* The underlying database file */
  26525. pDbFd = (unixFile*)fd;
  26526. p = pDbFd->pShm;
  26527. if( p==0 ) return SQLITE_OK;
  26528. pShmNode = p->pShmNode;
  26529. assert( pShmNode==pDbFd->pInode->pShmNode );
  26530. assert( pShmNode->pInode==pDbFd->pInode );
  26531. /* Remove connection p from the set of connections associated
  26532. ** with pShmNode */
  26533. sqlite3_mutex_enter(pShmNode->mutex);
  26534. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  26535. *pp = p->pNext;
  26536. /* Free the connection p */
  26537. sqlite3_free(p);
  26538. pDbFd->pShm = 0;
  26539. sqlite3_mutex_leave(pShmNode->mutex);
  26540. /* If pShmNode->nRef has reached 0, then close the underlying
  26541. ** shared-memory file, too */
  26542. unixEnterMutex();
  26543. assert( pShmNode->nRef>0 );
  26544. pShmNode->nRef--;
  26545. if( pShmNode->nRef==0 ){
  26546. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  26547. unixShmPurge(pDbFd);
  26548. }
  26549. unixLeaveMutex();
  26550. return SQLITE_OK;
  26551. }
  26552. #else
  26553. # define unixShmMap 0
  26554. # define unixShmLock 0
  26555. # define unixShmBarrier 0
  26556. # define unixShmUnmap 0
  26557. #endif /* #ifndef SQLITE_OMIT_WAL */
  26558. #if SQLITE_MAX_MMAP_SIZE>0
  26559. /*
  26560. ** If it is currently memory mapped, unmap file pFd.
  26561. */
  26562. static void unixUnmapfile(unixFile *pFd){
  26563. assert( pFd->nFetchOut==0 );
  26564. if( pFd->pMapRegion ){
  26565. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  26566. pFd->pMapRegion = 0;
  26567. pFd->mmapSize = 0;
  26568. pFd->mmapSizeActual = 0;
  26569. }
  26570. }
  26571. /*
  26572. ** Return the system page size.
  26573. */
  26574. static int unixGetPagesize(void){
  26575. #if HAVE_MREMAP
  26576. return 512;
  26577. #elif defined(_BSD_SOURCE)
  26578. return getpagesize();
  26579. #else
  26580. return (int)sysconf(_SC_PAGESIZE);
  26581. #endif
  26582. }
  26583. /*
  26584. ** Attempt to set the size of the memory mapping maintained by file
  26585. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  26586. **
  26587. ** If successful, this function sets the following variables:
  26588. **
  26589. ** unixFile.pMapRegion
  26590. ** unixFile.mmapSize
  26591. ** unixFile.mmapSizeActual
  26592. **
  26593. ** If unsuccessful, an error message is logged via sqlite3_log() and
  26594. ** the three variables above are zeroed. In this case SQLite should
  26595. ** continue accessing the database using the xRead() and xWrite()
  26596. ** methods.
  26597. */
  26598. static void unixRemapfile(
  26599. unixFile *pFd, /* File descriptor object */
  26600. i64 nNew /* Required mapping size */
  26601. ){
  26602. const char *zErr = "mmap";
  26603. int h = pFd->h; /* File descriptor open on db file */
  26604. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  26605. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  26606. u8 *pNew = 0; /* Location of new mapping */
  26607. int flags = PROT_READ; /* Flags to pass to mmap() */
  26608. assert( pFd->nFetchOut==0 );
  26609. assert( nNew>pFd->mmapSize );
  26610. assert( nNew<=pFd->mmapSizeMax );
  26611. assert( nNew>0 );
  26612. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  26613. assert( MAP_FAILED!=0 );
  26614. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  26615. if( pOrig ){
  26616. const int szSyspage = unixGetPagesize();
  26617. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  26618. u8 *pReq = &pOrig[nReuse];
  26619. /* Unmap any pages of the existing mapping that cannot be reused. */
  26620. if( nReuse!=nOrig ){
  26621. osMunmap(pReq, nOrig-nReuse);
  26622. }
  26623. #if HAVE_MREMAP
  26624. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  26625. zErr = "mremap";
  26626. #else
  26627. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  26628. if( pNew!=MAP_FAILED ){
  26629. if( pNew!=pReq ){
  26630. osMunmap(pNew, nNew - nReuse);
  26631. pNew = 0;
  26632. }else{
  26633. pNew = pOrig;
  26634. }
  26635. }
  26636. #endif
  26637. /* The attempt to extend the existing mapping failed. Free it. */
  26638. if( pNew==MAP_FAILED || pNew==0 ){
  26639. osMunmap(pOrig, nReuse);
  26640. }
  26641. }
  26642. /* If pNew is still NULL, try to create an entirely new mapping. */
  26643. if( pNew==0 ){
  26644. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  26645. }
  26646. if( pNew==MAP_FAILED ){
  26647. pNew = 0;
  26648. nNew = 0;
  26649. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  26650. /* If the mmap() above failed, assume that all subsequent mmap() calls
  26651. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  26652. ** in this case. */
  26653. pFd->mmapSizeMax = 0;
  26654. }
  26655. pFd->pMapRegion = (void *)pNew;
  26656. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  26657. }
  26658. /*
  26659. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  26660. ** is already mapped, the existing mapping is replaced by the new). Or, if
  26661. ** there already exists a mapping for this file, and there are still
  26662. ** outstanding xFetch() references to it, this function is a no-op.
  26663. **
  26664. ** If parameter nByte is non-negative, then it is the requested size of
  26665. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  26666. ** requested size is the size of the file on disk. The actual size of the
  26667. ** created mapping is either the requested size or the value configured
  26668. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  26669. **
  26670. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  26671. ** recreated as a result of outstanding references) or an SQLite error
  26672. ** code otherwise.
  26673. */
  26674. static int unixMapfile(unixFile *pFd, i64 nByte){
  26675. i64 nMap = nByte;
  26676. int rc;
  26677. assert( nMap>=0 || pFd->nFetchOut==0 );
  26678. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  26679. if( nMap<0 ){
  26680. struct stat statbuf; /* Low-level file information */
  26681. rc = osFstat(pFd->h, &statbuf);
  26682. if( rc!=SQLITE_OK ){
  26683. return SQLITE_IOERR_FSTAT;
  26684. }
  26685. nMap = statbuf.st_size;
  26686. }
  26687. if( nMap>pFd->mmapSizeMax ){
  26688. nMap = pFd->mmapSizeMax;
  26689. }
  26690. if( nMap!=pFd->mmapSize ){
  26691. if( nMap>0 ){
  26692. unixRemapfile(pFd, nMap);
  26693. }else{
  26694. unixUnmapfile(pFd);
  26695. }
  26696. }
  26697. return SQLITE_OK;
  26698. }
  26699. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  26700. /*
  26701. ** If possible, return a pointer to a mapping of file fd starting at offset
  26702. ** iOff. The mapping must be valid for at least nAmt bytes.
  26703. **
  26704. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  26705. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  26706. ** Finally, if an error does occur, return an SQLite error code. The final
  26707. ** value of *pp is undefined in this case.
  26708. **
  26709. ** If this function does return a pointer, the caller must eventually
  26710. ** release the reference by calling unixUnfetch().
  26711. */
  26712. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  26713. #if SQLITE_MAX_MMAP_SIZE>0
  26714. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26715. #endif
  26716. *pp = 0;
  26717. #if SQLITE_MAX_MMAP_SIZE>0
  26718. if( pFd->mmapSizeMax>0 ){
  26719. if( pFd->pMapRegion==0 ){
  26720. int rc = unixMapfile(pFd, -1);
  26721. if( rc!=SQLITE_OK ) return rc;
  26722. }
  26723. if( pFd->mmapSize >= iOff+nAmt ){
  26724. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  26725. pFd->nFetchOut++;
  26726. }
  26727. }
  26728. #endif
  26729. return SQLITE_OK;
  26730. }
  26731. /*
  26732. ** If the third argument is non-NULL, then this function releases a
  26733. ** reference obtained by an earlier call to unixFetch(). The second
  26734. ** argument passed to this function must be the same as the corresponding
  26735. ** argument that was passed to the unixFetch() invocation.
  26736. **
  26737. ** Or, if the third argument is NULL, then this function is being called
  26738. ** to inform the VFS layer that, according to POSIX, any existing mapping
  26739. ** may now be invalid and should be unmapped.
  26740. */
  26741. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  26742. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26743. UNUSED_PARAMETER(iOff);
  26744. #if SQLITE_MAX_MMAP_SIZE>0
  26745. /* If p==0 (unmap the entire file) then there must be no outstanding
  26746. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  26747. ** then there must be at least one outstanding. */
  26748. assert( (p==0)==(pFd->nFetchOut==0) );
  26749. /* If p!=0, it must match the iOff value. */
  26750. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  26751. if( p ){
  26752. pFd->nFetchOut--;
  26753. }else{
  26754. unixUnmapfile(pFd);
  26755. }
  26756. assert( pFd->nFetchOut>=0 );
  26757. #endif
  26758. return SQLITE_OK;
  26759. }
  26760. /*
  26761. ** Here ends the implementation of all sqlite3_file methods.
  26762. **
  26763. ********************** End sqlite3_file Methods *******************************
  26764. ******************************************************************************/
  26765. /*
  26766. ** This division contains definitions of sqlite3_io_methods objects that
  26767. ** implement various file locking strategies. It also contains definitions
  26768. ** of "finder" functions. A finder-function is used to locate the appropriate
  26769. ** sqlite3_io_methods object for a particular database file. The pAppData
  26770. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  26771. ** the correct finder-function for that VFS.
  26772. **
  26773. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  26774. ** object. The only interesting finder-function is autolockIoFinder, which
  26775. ** looks at the filesystem type and tries to guess the best locking
  26776. ** strategy from that.
  26777. **
  26778. ** For finder-funtion F, two objects are created:
  26779. **
  26780. ** (1) The real finder-function named "FImpt()".
  26781. **
  26782. ** (2) A constant pointer to this function named just "F".
  26783. **
  26784. **
  26785. ** A pointer to the F pointer is used as the pAppData value for VFS
  26786. ** objects. We have to do this instead of letting pAppData point
  26787. ** directly at the finder-function since C90 rules prevent a void*
  26788. ** from be cast into a function pointer.
  26789. **
  26790. **
  26791. ** Each instance of this macro generates two objects:
  26792. **
  26793. ** * A constant sqlite3_io_methods object call METHOD that has locking
  26794. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  26795. **
  26796. ** * An I/O method finder function called FINDER that returns a pointer
  26797. ** to the METHOD object in the previous bullet.
  26798. */
  26799. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  26800. static const sqlite3_io_methods METHOD = { \
  26801. VERSION, /* iVersion */ \
  26802. CLOSE, /* xClose */ \
  26803. unixRead, /* xRead */ \
  26804. unixWrite, /* xWrite */ \
  26805. unixTruncate, /* xTruncate */ \
  26806. unixSync, /* xSync */ \
  26807. unixFileSize, /* xFileSize */ \
  26808. LOCK, /* xLock */ \
  26809. UNLOCK, /* xUnlock */ \
  26810. CKLOCK, /* xCheckReservedLock */ \
  26811. unixFileControl, /* xFileControl */ \
  26812. unixSectorSize, /* xSectorSize */ \
  26813. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  26814. unixShmMap, /* xShmMap */ \
  26815. unixShmLock, /* xShmLock */ \
  26816. unixShmBarrier, /* xShmBarrier */ \
  26817. unixShmUnmap, /* xShmUnmap */ \
  26818. unixFetch, /* xFetch */ \
  26819. unixUnfetch, /* xUnfetch */ \
  26820. }; \
  26821. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  26822. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  26823. return &METHOD; \
  26824. } \
  26825. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  26826. = FINDER##Impl;
  26827. /*
  26828. ** Here are all of the sqlite3_io_methods objects for each of the
  26829. ** locking strategies. Functions that return pointers to these methods
  26830. ** are also created.
  26831. */
  26832. IOMETHODS(
  26833. posixIoFinder, /* Finder function name */
  26834. posixIoMethods, /* sqlite3_io_methods object name */
  26835. 3, /* shared memory and mmap are enabled */
  26836. unixClose, /* xClose method */
  26837. unixLock, /* xLock method */
  26838. unixUnlock, /* xUnlock method */
  26839. unixCheckReservedLock /* xCheckReservedLock method */
  26840. )
  26841. IOMETHODS(
  26842. nolockIoFinder, /* Finder function name */
  26843. nolockIoMethods, /* sqlite3_io_methods object name */
  26844. 1, /* shared memory is disabled */
  26845. nolockClose, /* xClose method */
  26846. nolockLock, /* xLock method */
  26847. nolockUnlock, /* xUnlock method */
  26848. nolockCheckReservedLock /* xCheckReservedLock method */
  26849. )
  26850. IOMETHODS(
  26851. dotlockIoFinder, /* Finder function name */
  26852. dotlockIoMethods, /* sqlite3_io_methods object name */
  26853. 1, /* shared memory is disabled */
  26854. dotlockClose, /* xClose method */
  26855. dotlockLock, /* xLock method */
  26856. dotlockUnlock, /* xUnlock method */
  26857. dotlockCheckReservedLock /* xCheckReservedLock method */
  26858. )
  26859. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  26860. IOMETHODS(
  26861. flockIoFinder, /* Finder function name */
  26862. flockIoMethods, /* sqlite3_io_methods object name */
  26863. 1, /* shared memory is disabled */
  26864. flockClose, /* xClose method */
  26865. flockLock, /* xLock method */
  26866. flockUnlock, /* xUnlock method */
  26867. flockCheckReservedLock /* xCheckReservedLock method */
  26868. )
  26869. #endif
  26870. #if OS_VXWORKS
  26871. IOMETHODS(
  26872. semIoFinder, /* Finder function name */
  26873. semIoMethods, /* sqlite3_io_methods object name */
  26874. 1, /* shared memory is disabled */
  26875. semClose, /* xClose method */
  26876. semLock, /* xLock method */
  26877. semUnlock, /* xUnlock method */
  26878. semCheckReservedLock /* xCheckReservedLock method */
  26879. )
  26880. #endif
  26881. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26882. IOMETHODS(
  26883. afpIoFinder, /* Finder function name */
  26884. afpIoMethods, /* sqlite3_io_methods object name */
  26885. 1, /* shared memory is disabled */
  26886. afpClose, /* xClose method */
  26887. afpLock, /* xLock method */
  26888. afpUnlock, /* xUnlock method */
  26889. afpCheckReservedLock /* xCheckReservedLock method */
  26890. )
  26891. #endif
  26892. /*
  26893. ** The proxy locking method is a "super-method" in the sense that it
  26894. ** opens secondary file descriptors for the conch and lock files and
  26895. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  26896. ** secondary files. For this reason, the division that implements
  26897. ** proxy locking is located much further down in the file. But we need
  26898. ** to go ahead and define the sqlite3_io_methods and finder function
  26899. ** for proxy locking here. So we forward declare the I/O methods.
  26900. */
  26901. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26902. static int proxyClose(sqlite3_file*);
  26903. static int proxyLock(sqlite3_file*, int);
  26904. static int proxyUnlock(sqlite3_file*, int);
  26905. static int proxyCheckReservedLock(sqlite3_file*, int*);
  26906. IOMETHODS(
  26907. proxyIoFinder, /* Finder function name */
  26908. proxyIoMethods, /* sqlite3_io_methods object name */
  26909. 1, /* shared memory is disabled */
  26910. proxyClose, /* xClose method */
  26911. proxyLock, /* xLock method */
  26912. proxyUnlock, /* xUnlock method */
  26913. proxyCheckReservedLock /* xCheckReservedLock method */
  26914. )
  26915. #endif
  26916. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  26917. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26918. IOMETHODS(
  26919. nfsIoFinder, /* Finder function name */
  26920. nfsIoMethods, /* sqlite3_io_methods object name */
  26921. 1, /* shared memory is disabled */
  26922. unixClose, /* xClose method */
  26923. unixLock, /* xLock method */
  26924. nfsUnlock, /* xUnlock method */
  26925. unixCheckReservedLock /* xCheckReservedLock method */
  26926. )
  26927. #endif
  26928. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26929. /*
  26930. ** This "finder" function attempts to determine the best locking strategy
  26931. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26932. ** object that implements that strategy.
  26933. **
  26934. ** This is for MacOSX only.
  26935. */
  26936. static const sqlite3_io_methods *autolockIoFinderImpl(
  26937. const char *filePath, /* name of the database file */
  26938. unixFile *pNew /* open file object for the database file */
  26939. ){
  26940. static const struct Mapping {
  26941. const char *zFilesystem; /* Filesystem type name */
  26942. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  26943. } aMap[] = {
  26944. { "hfs", &posixIoMethods },
  26945. { "ufs", &posixIoMethods },
  26946. { "afpfs", &afpIoMethods },
  26947. { "smbfs", &afpIoMethods },
  26948. { "webdav", &nolockIoMethods },
  26949. { 0, 0 }
  26950. };
  26951. int i;
  26952. struct statfs fsInfo;
  26953. struct flock lockInfo;
  26954. if( !filePath ){
  26955. /* If filePath==NULL that means we are dealing with a transient file
  26956. ** that does not need to be locked. */
  26957. return &nolockIoMethods;
  26958. }
  26959. if( statfs(filePath, &fsInfo) != -1 ){
  26960. if( fsInfo.f_flags & MNT_RDONLY ){
  26961. return &nolockIoMethods;
  26962. }
  26963. for(i=0; aMap[i].zFilesystem; i++){
  26964. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  26965. return aMap[i].pMethods;
  26966. }
  26967. }
  26968. }
  26969. /* Default case. Handles, amongst others, "nfs".
  26970. ** Test byte-range lock using fcntl(). If the call succeeds,
  26971. ** assume that the file-system supports POSIX style locks.
  26972. */
  26973. lockInfo.l_len = 1;
  26974. lockInfo.l_start = 0;
  26975. lockInfo.l_whence = SEEK_SET;
  26976. lockInfo.l_type = F_RDLCK;
  26977. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26978. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  26979. return &nfsIoMethods;
  26980. } else {
  26981. return &posixIoMethods;
  26982. }
  26983. }else{
  26984. return &dotlockIoMethods;
  26985. }
  26986. }
  26987. static const sqlite3_io_methods
  26988. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26989. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26990. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  26991. /*
  26992. ** This "finder" function attempts to determine the best locking strategy
  26993. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26994. ** object that implements that strategy.
  26995. **
  26996. ** This is for VXWorks only.
  26997. */
  26998. static const sqlite3_io_methods *autolockIoFinderImpl(
  26999. const char *filePath, /* name of the database file */
  27000. unixFile *pNew /* the open file object */
  27001. ){
  27002. struct flock lockInfo;
  27003. if( !filePath ){
  27004. /* If filePath==NULL that means we are dealing with a transient file
  27005. ** that does not need to be locked. */
  27006. return &nolockIoMethods;
  27007. }
  27008. /* Test if fcntl() is supported and use POSIX style locks.
  27009. ** Otherwise fall back to the named semaphore method.
  27010. */
  27011. lockInfo.l_len = 1;
  27012. lockInfo.l_start = 0;
  27013. lockInfo.l_whence = SEEK_SET;
  27014. lockInfo.l_type = F_RDLCK;
  27015. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  27016. return &posixIoMethods;
  27017. }else{
  27018. return &semIoMethods;
  27019. }
  27020. }
  27021. static const sqlite3_io_methods
  27022. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  27023. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  27024. /*
  27025. ** An abstract type for a pointer to a IO method finder function:
  27026. */
  27027. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  27028. /****************************************************************************
  27029. **************************** sqlite3_vfs methods ****************************
  27030. **
  27031. ** This division contains the implementation of methods on the
  27032. ** sqlite3_vfs object.
  27033. */
  27034. /*
  27035. ** Initialize the contents of the unixFile structure pointed to by pId.
  27036. */
  27037. static int fillInUnixFile(
  27038. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27039. int h, /* Open file descriptor of file being opened */
  27040. sqlite3_file *pId, /* Write to the unixFile structure here */
  27041. const char *zFilename, /* Name of the file being opened */
  27042. int ctrlFlags /* Zero or more UNIXFILE_* values */
  27043. ){
  27044. const sqlite3_io_methods *pLockingStyle;
  27045. unixFile *pNew = (unixFile *)pId;
  27046. int rc = SQLITE_OK;
  27047. assert( pNew->pInode==NULL );
  27048. /* Usually the path zFilename should not be a relative pathname. The
  27049. ** exception is when opening the proxy "conch" file in builds that
  27050. ** include the special Apple locking styles.
  27051. */
  27052. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27053. assert( zFilename==0 || zFilename[0]=='/'
  27054. || pVfs->pAppData==(void*)&autolockIoFinder );
  27055. #else
  27056. assert( zFilename==0 || zFilename[0]=='/' );
  27057. #endif
  27058. /* No locking occurs in temporary files */
  27059. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  27060. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  27061. pNew->h = h;
  27062. pNew->pVfs = pVfs;
  27063. pNew->zPath = zFilename;
  27064. pNew->ctrlFlags = (u8)ctrlFlags;
  27065. #if SQLITE_MAX_MMAP_SIZE>0
  27066. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  27067. #endif
  27068. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  27069. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  27070. pNew->ctrlFlags |= UNIXFILE_PSOW;
  27071. }
  27072. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  27073. pNew->ctrlFlags |= UNIXFILE_EXCL;
  27074. }
  27075. #if OS_VXWORKS
  27076. pNew->pId = vxworksFindFileId(zFilename);
  27077. if( pNew->pId==0 ){
  27078. ctrlFlags |= UNIXFILE_NOLOCK;
  27079. rc = SQLITE_NOMEM;
  27080. }
  27081. #endif
  27082. if( ctrlFlags & UNIXFILE_NOLOCK ){
  27083. pLockingStyle = &nolockIoMethods;
  27084. }else{
  27085. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  27086. #if SQLITE_ENABLE_LOCKING_STYLE
  27087. /* Cache zFilename in the locking context (AFP and dotlock override) for
  27088. ** proxyLock activation is possible (remote proxy is based on db name)
  27089. ** zFilename remains valid until file is closed, to support */
  27090. pNew->lockingContext = (void*)zFilename;
  27091. #endif
  27092. }
  27093. if( pLockingStyle == &posixIoMethods
  27094. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27095. || pLockingStyle == &nfsIoMethods
  27096. #endif
  27097. ){
  27098. unixEnterMutex();
  27099. rc = findInodeInfo(pNew, &pNew->pInode);
  27100. if( rc!=SQLITE_OK ){
  27101. /* If an error occurred in findInodeInfo(), close the file descriptor
  27102. ** immediately, before releasing the mutex. findInodeInfo() may fail
  27103. ** in two scenarios:
  27104. **
  27105. ** (a) A call to fstat() failed.
  27106. ** (b) A malloc failed.
  27107. **
  27108. ** Scenario (b) may only occur if the process is holding no other
  27109. ** file descriptors open on the same file. If there were other file
  27110. ** descriptors on this file, then no malloc would be required by
  27111. ** findInodeInfo(). If this is the case, it is quite safe to close
  27112. ** handle h - as it is guaranteed that no posix locks will be released
  27113. ** by doing so.
  27114. **
  27115. ** If scenario (a) caused the error then things are not so safe. The
  27116. ** implicit assumption here is that if fstat() fails, things are in
  27117. ** such bad shape that dropping a lock or two doesn't matter much.
  27118. */
  27119. robust_close(pNew, h, __LINE__);
  27120. h = -1;
  27121. }
  27122. unixLeaveMutex();
  27123. }
  27124. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27125. else if( pLockingStyle == &afpIoMethods ){
  27126. /* AFP locking uses the file path so it needs to be included in
  27127. ** the afpLockingContext.
  27128. */
  27129. afpLockingContext *pCtx;
  27130. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  27131. if( pCtx==0 ){
  27132. rc = SQLITE_NOMEM;
  27133. }else{
  27134. /* NB: zFilename exists and remains valid until the file is closed
  27135. ** according to requirement F11141. So we do not need to make a
  27136. ** copy of the filename. */
  27137. pCtx->dbPath = zFilename;
  27138. pCtx->reserved = 0;
  27139. srandomdev();
  27140. unixEnterMutex();
  27141. rc = findInodeInfo(pNew, &pNew->pInode);
  27142. if( rc!=SQLITE_OK ){
  27143. sqlite3_free(pNew->lockingContext);
  27144. robust_close(pNew, h, __LINE__);
  27145. h = -1;
  27146. }
  27147. unixLeaveMutex();
  27148. }
  27149. }
  27150. #endif
  27151. else if( pLockingStyle == &dotlockIoMethods ){
  27152. /* Dotfile locking uses the file path so it needs to be included in
  27153. ** the dotlockLockingContext
  27154. */
  27155. char *zLockFile;
  27156. int nFilename;
  27157. assert( zFilename!=0 );
  27158. nFilename = (int)strlen(zFilename) + 6;
  27159. zLockFile = (char *)sqlite3_malloc(nFilename);
  27160. if( zLockFile==0 ){
  27161. rc = SQLITE_NOMEM;
  27162. }else{
  27163. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  27164. }
  27165. pNew->lockingContext = zLockFile;
  27166. }
  27167. #if OS_VXWORKS
  27168. else if( pLockingStyle == &semIoMethods ){
  27169. /* Named semaphore locking uses the file path so it needs to be
  27170. ** included in the semLockingContext
  27171. */
  27172. unixEnterMutex();
  27173. rc = findInodeInfo(pNew, &pNew->pInode);
  27174. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  27175. char *zSemName = pNew->pInode->aSemName;
  27176. int n;
  27177. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  27178. pNew->pId->zCanonicalName);
  27179. for( n=1; zSemName[n]; n++ )
  27180. if( zSemName[n]=='/' ) zSemName[n] = '_';
  27181. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  27182. if( pNew->pInode->pSem == SEM_FAILED ){
  27183. rc = SQLITE_NOMEM;
  27184. pNew->pInode->aSemName[0] = '\0';
  27185. }
  27186. }
  27187. unixLeaveMutex();
  27188. }
  27189. #endif
  27190. pNew->lastErrno = 0;
  27191. #if OS_VXWORKS
  27192. if( rc!=SQLITE_OK ){
  27193. if( h>=0 ) robust_close(pNew, h, __LINE__);
  27194. h = -1;
  27195. osUnlink(zFilename);
  27196. pNew->ctrlFlags |= UNIXFILE_DELETE;
  27197. }
  27198. #endif
  27199. if( rc!=SQLITE_OK ){
  27200. if( h>=0 ) robust_close(pNew, h, __LINE__);
  27201. }else{
  27202. pNew->pMethod = pLockingStyle;
  27203. OpenCounter(+1);
  27204. verifyDbFile(pNew);
  27205. }
  27206. return rc;
  27207. }
  27208. /*
  27209. ** Return the name of a directory in which to put temporary files.
  27210. ** If no suitable temporary file directory can be found, return NULL.
  27211. */
  27212. static const char *unixTempFileDir(void){
  27213. static const char *azDirs[] = {
  27214. 0,
  27215. 0,
  27216. 0,
  27217. "/var/tmp",
  27218. "/usr/tmp",
  27219. "/tmp",
  27220. 0 /* List terminator */
  27221. };
  27222. unsigned int i;
  27223. struct stat buf;
  27224. const char *zDir = 0;
  27225. azDirs[0] = sqlite3_temp_directory;
  27226. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  27227. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  27228. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  27229. if( zDir==0 ) continue;
  27230. if( osStat(zDir, &buf) ) continue;
  27231. if( !S_ISDIR(buf.st_mode) ) continue;
  27232. if( osAccess(zDir, 07) ) continue;
  27233. break;
  27234. }
  27235. return zDir;
  27236. }
  27237. /*
  27238. ** Create a temporary file name in zBuf. zBuf must be allocated
  27239. ** by the calling process and must be big enough to hold at least
  27240. ** pVfs->mxPathname bytes.
  27241. */
  27242. static int unixGetTempname(int nBuf, char *zBuf){
  27243. static const unsigned char zChars[] =
  27244. "abcdefghijklmnopqrstuvwxyz"
  27245. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  27246. "0123456789";
  27247. unsigned int i, j;
  27248. const char *zDir;
  27249. /* It's odd to simulate an io-error here, but really this is just
  27250. ** using the io-error infrastructure to test that SQLite handles this
  27251. ** function failing.
  27252. */
  27253. SimulateIOError( return SQLITE_IOERR );
  27254. zDir = unixTempFileDir();
  27255. if( zDir==0 ) zDir = ".";
  27256. /* Check that the output buffer is large enough for the temporary file
  27257. ** name. If it is not, return SQLITE_ERROR.
  27258. */
  27259. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  27260. return SQLITE_ERROR;
  27261. }
  27262. do{
  27263. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  27264. j = (int)strlen(zBuf);
  27265. sqlite3_randomness(15, &zBuf[j]);
  27266. for(i=0; i<15; i++, j++){
  27267. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  27268. }
  27269. zBuf[j] = 0;
  27270. zBuf[j+1] = 0;
  27271. }while( osAccess(zBuf,0)==0 );
  27272. return SQLITE_OK;
  27273. }
  27274. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27275. /*
  27276. ** Routine to transform a unixFile into a proxy-locking unixFile.
  27277. ** Implementation in the proxy-lock division, but used by unixOpen()
  27278. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  27279. */
  27280. static int proxyTransformUnixFile(unixFile*, const char*);
  27281. #endif
  27282. /*
  27283. ** Search for an unused file descriptor that was opened on the database
  27284. ** file (not a journal or master-journal file) identified by pathname
  27285. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  27286. ** argument to this function.
  27287. **
  27288. ** Such a file descriptor may exist if a database connection was closed
  27289. ** but the associated file descriptor could not be closed because some
  27290. ** other file descriptor open on the same file is holding a file-lock.
  27291. ** Refer to comments in the unixClose() function and the lengthy comment
  27292. ** describing "Posix Advisory Locking" at the start of this file for
  27293. ** further details. Also, ticket #4018.
  27294. **
  27295. ** If a suitable file descriptor is found, then it is returned. If no
  27296. ** such file descriptor is located, -1 is returned.
  27297. */
  27298. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  27299. UnixUnusedFd *pUnused = 0;
  27300. /* Do not search for an unused file descriptor on vxworks. Not because
  27301. ** vxworks would not benefit from the change (it might, we're not sure),
  27302. ** but because no way to test it is currently available. It is better
  27303. ** not to risk breaking vxworks support for the sake of such an obscure
  27304. ** feature. */
  27305. #if !OS_VXWORKS
  27306. struct stat sStat; /* Results of stat() call */
  27307. /* A stat() call may fail for various reasons. If this happens, it is
  27308. ** almost certain that an open() call on the same path will also fail.
  27309. ** For this reason, if an error occurs in the stat() call here, it is
  27310. ** ignored and -1 is returned. The caller will try to open a new file
  27311. ** descriptor on the same path, fail, and return an error to SQLite.
  27312. **
  27313. ** Even if a subsequent open() call does succeed, the consequences of
  27314. ** not searching for a resusable file descriptor are not dire. */
  27315. if( 0==osStat(zPath, &sStat) ){
  27316. unixInodeInfo *pInode;
  27317. unixEnterMutex();
  27318. pInode = inodeList;
  27319. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  27320. || pInode->fileId.ino!=sStat.st_ino) ){
  27321. pInode = pInode->pNext;
  27322. }
  27323. if( pInode ){
  27324. UnixUnusedFd **pp;
  27325. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  27326. pUnused = *pp;
  27327. if( pUnused ){
  27328. *pp = pUnused->pNext;
  27329. }
  27330. }
  27331. unixLeaveMutex();
  27332. }
  27333. #endif /* if !OS_VXWORKS */
  27334. return pUnused;
  27335. }
  27336. /*
  27337. ** This function is called by unixOpen() to determine the unix permissions
  27338. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  27339. ** and a value suitable for passing as the third argument to open(2) is
  27340. ** written to *pMode. If an IO error occurs, an SQLite error code is
  27341. ** returned and the value of *pMode is not modified.
  27342. **
  27343. ** In most cases cases, this routine sets *pMode to 0, which will become
  27344. ** an indication to robust_open() to create the file using
  27345. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  27346. ** But if the file being opened is a WAL or regular journal file, then
  27347. ** this function queries the file-system for the permissions on the
  27348. ** corresponding database file and sets *pMode to this value. Whenever
  27349. ** possible, WAL and journal files are created using the same permissions
  27350. ** as the associated database file.
  27351. **
  27352. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  27353. ** original filename is unavailable. But 8_3_NAMES is only used for
  27354. ** FAT filesystems and permissions do not matter there, so just use
  27355. ** the default permissions.
  27356. */
  27357. static int findCreateFileMode(
  27358. const char *zPath, /* Path of file (possibly) being created */
  27359. int flags, /* Flags passed as 4th argument to xOpen() */
  27360. mode_t *pMode, /* OUT: Permissions to open file with */
  27361. uid_t *pUid, /* OUT: uid to set on the file */
  27362. gid_t *pGid /* OUT: gid to set on the file */
  27363. ){
  27364. int rc = SQLITE_OK; /* Return Code */
  27365. *pMode = 0;
  27366. *pUid = 0;
  27367. *pGid = 0;
  27368. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27369. char zDb[MAX_PATHNAME+1]; /* Database file path */
  27370. int nDb; /* Number of valid bytes in zDb */
  27371. struct stat sStat; /* Output of stat() on database file */
  27372. /* zPath is a path to a WAL or journal file. The following block derives
  27373. ** the path to the associated database file from zPath. This block handles
  27374. ** the following naming conventions:
  27375. **
  27376. ** "<path to db>-journal"
  27377. ** "<path to db>-wal"
  27378. ** "<path to db>-journalNN"
  27379. ** "<path to db>-walNN"
  27380. **
  27381. ** where NN is a decimal number. The NN naming schemes are
  27382. ** used by the test_multiplex.c module.
  27383. */
  27384. nDb = sqlite3Strlen30(zPath) - 1;
  27385. #ifdef SQLITE_ENABLE_8_3_NAMES
  27386. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  27387. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  27388. #else
  27389. while( zPath[nDb]!='-' ){
  27390. assert( nDb>0 );
  27391. assert( zPath[nDb]!='\n' );
  27392. nDb--;
  27393. }
  27394. #endif
  27395. memcpy(zDb, zPath, nDb);
  27396. zDb[nDb] = '\0';
  27397. if( 0==osStat(zDb, &sStat) ){
  27398. *pMode = sStat.st_mode & 0777;
  27399. *pUid = sStat.st_uid;
  27400. *pGid = sStat.st_gid;
  27401. }else{
  27402. rc = SQLITE_IOERR_FSTAT;
  27403. }
  27404. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  27405. *pMode = 0600;
  27406. }
  27407. return rc;
  27408. }
  27409. /*
  27410. ** Open the file zPath.
  27411. **
  27412. ** Previously, the SQLite OS layer used three functions in place of this
  27413. ** one:
  27414. **
  27415. ** sqlite3OsOpenReadWrite();
  27416. ** sqlite3OsOpenReadOnly();
  27417. ** sqlite3OsOpenExclusive();
  27418. **
  27419. ** These calls correspond to the following combinations of flags:
  27420. **
  27421. ** ReadWrite() -> (READWRITE | CREATE)
  27422. ** ReadOnly() -> (READONLY)
  27423. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  27424. **
  27425. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  27426. ** true, the file was configured to be automatically deleted when the
  27427. ** file handle closed. To achieve the same effect using this new
  27428. ** interface, add the DELETEONCLOSE flag to those specified above for
  27429. ** OpenExclusive().
  27430. */
  27431. static int unixOpen(
  27432. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  27433. const char *zPath, /* Pathname of file to be opened */
  27434. sqlite3_file *pFile, /* The file descriptor to be filled in */
  27435. int flags, /* Input flags to control the opening */
  27436. int *pOutFlags /* Output flags returned to SQLite core */
  27437. ){
  27438. unixFile *p = (unixFile *)pFile;
  27439. int fd = -1; /* File descriptor returned by open() */
  27440. int openFlags = 0; /* Flags to pass to open() */
  27441. int eType = flags&0xFFFFFF00; /* Type of file to open */
  27442. int noLock; /* True to omit locking primitives */
  27443. int rc = SQLITE_OK; /* Function Return Code */
  27444. int ctrlFlags = 0; /* UNIXFILE_* flags */
  27445. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  27446. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  27447. int isCreate = (flags & SQLITE_OPEN_CREATE);
  27448. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  27449. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  27450. #if SQLITE_ENABLE_LOCKING_STYLE
  27451. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  27452. #endif
  27453. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27454. struct statfs fsInfo;
  27455. #endif
  27456. /* If creating a master or main-file journal, this function will open
  27457. ** a file-descriptor on the directory too. The first time unixSync()
  27458. ** is called the directory file descriptor will be fsync()ed and close()d.
  27459. */
  27460. int syncDir = (isCreate && (
  27461. eType==SQLITE_OPEN_MASTER_JOURNAL
  27462. || eType==SQLITE_OPEN_MAIN_JOURNAL
  27463. || eType==SQLITE_OPEN_WAL
  27464. ));
  27465. /* If argument zPath is a NULL pointer, this function is required to open
  27466. ** a temporary file. Use this buffer to store the file name in.
  27467. */
  27468. char zTmpname[MAX_PATHNAME+2];
  27469. const char *zName = zPath;
  27470. /* Check the following statements are true:
  27471. **
  27472. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  27473. ** (b) if CREATE is set, then READWRITE must also be set, and
  27474. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  27475. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  27476. */
  27477. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  27478. assert(isCreate==0 || isReadWrite);
  27479. assert(isExclusive==0 || isCreate);
  27480. assert(isDelete==0 || isCreate);
  27481. /* The main DB, main journal, WAL file and master journal are never
  27482. ** automatically deleted. Nor are they ever temporary files. */
  27483. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  27484. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  27485. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  27486. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  27487. /* Assert that the upper layer has set one of the "file-type" flags. */
  27488. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  27489. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  27490. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  27491. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  27492. );
  27493. memset(p, 0, sizeof(unixFile));
  27494. if( eType==SQLITE_OPEN_MAIN_DB ){
  27495. UnixUnusedFd *pUnused;
  27496. pUnused = findReusableFd(zName, flags);
  27497. if( pUnused ){
  27498. fd = pUnused->fd;
  27499. }else{
  27500. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27501. if( !pUnused ){
  27502. return SQLITE_NOMEM;
  27503. }
  27504. }
  27505. p->pUnused = pUnused;
  27506. /* Database filenames are double-zero terminated if they are not
  27507. ** URIs with parameters. Hence, they can always be passed into
  27508. ** sqlite3_uri_parameter(). */
  27509. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  27510. }else if( !zName ){
  27511. /* If zName is NULL, the upper layer is requesting a temp file. */
  27512. assert(isDelete && !syncDir);
  27513. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  27514. if( rc!=SQLITE_OK ){
  27515. return rc;
  27516. }
  27517. zName = zTmpname;
  27518. /* Generated temporary filenames are always double-zero terminated
  27519. ** for use by sqlite3_uri_parameter(). */
  27520. assert( zName[strlen(zName)+1]==0 );
  27521. }
  27522. /* Determine the value of the flags parameter passed to POSIX function
  27523. ** open(). These must be calculated even if open() is not called, as
  27524. ** they may be stored as part of the file handle and used by the
  27525. ** 'conch file' locking functions later on. */
  27526. if( isReadonly ) openFlags |= O_RDONLY;
  27527. if( isReadWrite ) openFlags |= O_RDWR;
  27528. if( isCreate ) openFlags |= O_CREAT;
  27529. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  27530. openFlags |= (O_LARGEFILE|O_BINARY);
  27531. if( fd<0 ){
  27532. mode_t openMode; /* Permissions to create file with */
  27533. uid_t uid; /* Userid for the file */
  27534. gid_t gid; /* Groupid for the file */
  27535. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  27536. if( rc!=SQLITE_OK ){
  27537. assert( !p->pUnused );
  27538. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  27539. return rc;
  27540. }
  27541. fd = robust_open(zName, openFlags, openMode);
  27542. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  27543. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  27544. /* Failed to open the file for read/write access. Try read-only. */
  27545. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  27546. openFlags &= ~(O_RDWR|O_CREAT);
  27547. flags |= SQLITE_OPEN_READONLY;
  27548. openFlags |= O_RDONLY;
  27549. isReadonly = 1;
  27550. fd = robust_open(zName, openFlags, openMode);
  27551. }
  27552. if( fd<0 ){
  27553. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  27554. goto open_finished;
  27555. }
  27556. /* If this process is running as root and if creating a new rollback
  27557. ** journal or WAL file, set the ownership of the journal or WAL to be
  27558. ** the same as the original database.
  27559. */
  27560. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27561. osFchown(fd, uid, gid);
  27562. }
  27563. }
  27564. assert( fd>=0 );
  27565. if( pOutFlags ){
  27566. *pOutFlags = flags;
  27567. }
  27568. if( p->pUnused ){
  27569. p->pUnused->fd = fd;
  27570. p->pUnused->flags = flags;
  27571. }
  27572. if( isDelete ){
  27573. #if OS_VXWORKS
  27574. zPath = zName;
  27575. #else
  27576. osUnlink(zName);
  27577. #endif
  27578. }
  27579. #if SQLITE_ENABLE_LOCKING_STYLE
  27580. else{
  27581. p->openFlags = openFlags;
  27582. }
  27583. #endif
  27584. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  27585. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27586. if( fstatfs(fd, &fsInfo) == -1 ){
  27587. ((unixFile*)pFile)->lastErrno = errno;
  27588. robust_close(p, fd, __LINE__);
  27589. return SQLITE_IOERR_ACCESS;
  27590. }
  27591. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  27592. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  27593. }
  27594. #endif
  27595. /* Set up appropriate ctrlFlags */
  27596. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  27597. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  27598. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  27599. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  27600. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  27601. #if SQLITE_ENABLE_LOCKING_STYLE
  27602. #if SQLITE_PREFER_PROXY_LOCKING
  27603. isAutoProxy = 1;
  27604. #endif
  27605. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  27606. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  27607. int useProxy = 0;
  27608. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  27609. ** never use proxy, NULL means use proxy for non-local files only. */
  27610. if( envforce!=NULL ){
  27611. useProxy = atoi(envforce)>0;
  27612. }else{
  27613. if( statfs(zPath, &fsInfo) == -1 ){
  27614. /* In theory, the close(fd) call is sub-optimal. If the file opened
  27615. ** with fd is a database file, and there are other connections open
  27616. ** on that file that are currently holding advisory locks on it,
  27617. ** then the call to close() will cancel those locks. In practice,
  27618. ** we're assuming that statfs() doesn't fail very often. At least
  27619. ** not while other file descriptors opened by the same process on
  27620. ** the same file are working. */
  27621. p->lastErrno = errno;
  27622. robust_close(p, fd, __LINE__);
  27623. rc = SQLITE_IOERR_ACCESS;
  27624. goto open_finished;
  27625. }
  27626. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  27627. }
  27628. if( useProxy ){
  27629. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27630. if( rc==SQLITE_OK ){
  27631. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  27632. if( rc!=SQLITE_OK ){
  27633. /* Use unixClose to clean up the resources added in fillInUnixFile
  27634. ** and clear all the structure's references. Specifically,
  27635. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  27636. */
  27637. unixClose(pFile);
  27638. return rc;
  27639. }
  27640. }
  27641. goto open_finished;
  27642. }
  27643. }
  27644. #endif
  27645. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27646. open_finished:
  27647. if( rc!=SQLITE_OK ){
  27648. sqlite3_free(p->pUnused);
  27649. }
  27650. return rc;
  27651. }
  27652. /*
  27653. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  27654. ** the directory after deleting the file.
  27655. */
  27656. static int unixDelete(
  27657. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  27658. const char *zPath, /* Name of file to be deleted */
  27659. int dirSync /* If true, fsync() directory after deleting file */
  27660. ){
  27661. int rc = SQLITE_OK;
  27662. UNUSED_PARAMETER(NotUsed);
  27663. SimulateIOError(return SQLITE_IOERR_DELETE);
  27664. if( osUnlink(zPath)==(-1) ){
  27665. if( errno==ENOENT ){
  27666. rc = SQLITE_IOERR_DELETE_NOENT;
  27667. }else{
  27668. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  27669. }
  27670. return rc;
  27671. }
  27672. #ifndef SQLITE_DISABLE_DIRSYNC
  27673. if( (dirSync & 1)!=0 ){
  27674. int fd;
  27675. rc = osOpenDirectory(zPath, &fd);
  27676. if( rc==SQLITE_OK ){
  27677. #if OS_VXWORKS
  27678. if( fsync(fd)==-1 )
  27679. #else
  27680. if( fsync(fd) )
  27681. #endif
  27682. {
  27683. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  27684. }
  27685. robust_close(0, fd, __LINE__);
  27686. }else if( rc==SQLITE_CANTOPEN ){
  27687. rc = SQLITE_OK;
  27688. }
  27689. }
  27690. #endif
  27691. return rc;
  27692. }
  27693. /*
  27694. ** Test the existence of or access permissions of file zPath. The
  27695. ** test performed depends on the value of flags:
  27696. **
  27697. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  27698. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  27699. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  27700. **
  27701. ** Otherwise return 0.
  27702. */
  27703. static int unixAccess(
  27704. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  27705. const char *zPath, /* Path of the file to examine */
  27706. int flags, /* What do we want to learn about the zPath file? */
  27707. int *pResOut /* Write result boolean here */
  27708. ){
  27709. int amode = 0;
  27710. UNUSED_PARAMETER(NotUsed);
  27711. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  27712. switch( flags ){
  27713. case SQLITE_ACCESS_EXISTS:
  27714. amode = F_OK;
  27715. break;
  27716. case SQLITE_ACCESS_READWRITE:
  27717. amode = W_OK|R_OK;
  27718. break;
  27719. case SQLITE_ACCESS_READ:
  27720. amode = R_OK;
  27721. break;
  27722. default:
  27723. assert(!"Invalid flags argument");
  27724. }
  27725. *pResOut = (osAccess(zPath, amode)==0);
  27726. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  27727. struct stat buf;
  27728. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  27729. *pResOut = 0;
  27730. }
  27731. }
  27732. return SQLITE_OK;
  27733. }
  27734. /*
  27735. ** Turn a relative pathname into a full pathname. The relative path
  27736. ** is stored as a nul-terminated string in the buffer pointed to by
  27737. ** zPath.
  27738. **
  27739. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  27740. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  27741. ** this buffer before returning.
  27742. */
  27743. static int unixFullPathname(
  27744. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27745. const char *zPath, /* Possibly relative input path */
  27746. int nOut, /* Size of output buffer in bytes */
  27747. char *zOut /* Output buffer */
  27748. ){
  27749. /* It's odd to simulate an io-error here, but really this is just
  27750. ** using the io-error infrastructure to test that SQLite handles this
  27751. ** function failing. This function could fail if, for example, the
  27752. ** current working directory has been unlinked.
  27753. */
  27754. SimulateIOError( return SQLITE_ERROR );
  27755. assert( pVfs->mxPathname==MAX_PATHNAME );
  27756. UNUSED_PARAMETER(pVfs);
  27757. zOut[nOut-1] = '\0';
  27758. if( zPath[0]=='/' ){
  27759. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  27760. }else{
  27761. int nCwd;
  27762. if( osGetcwd(zOut, nOut-1)==0 ){
  27763. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  27764. }
  27765. nCwd = (int)strlen(zOut);
  27766. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  27767. }
  27768. return SQLITE_OK;
  27769. }
  27770. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  27771. /*
  27772. ** Interfaces for opening a shared library, finding entry points
  27773. ** within the shared library, and closing the shared library.
  27774. */
  27775. #include <dlfcn.h>
  27776. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  27777. UNUSED_PARAMETER(NotUsed);
  27778. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  27779. }
  27780. /*
  27781. ** SQLite calls this function immediately after a call to unixDlSym() or
  27782. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  27783. ** message is available, it is written to zBufOut. If no error message
  27784. ** is available, zBufOut is left unmodified and SQLite uses a default
  27785. ** error message.
  27786. */
  27787. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  27788. const char *zErr;
  27789. UNUSED_PARAMETER(NotUsed);
  27790. unixEnterMutex();
  27791. zErr = dlerror();
  27792. if( zErr ){
  27793. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  27794. }
  27795. unixLeaveMutex();
  27796. }
  27797. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  27798. /*
  27799. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  27800. ** cast into a pointer to a function. And yet the library dlsym() routine
  27801. ** returns a void* which is really a pointer to a function. So how do we
  27802. ** use dlsym() with -pedantic-errors?
  27803. **
  27804. ** Variable x below is defined to be a pointer to a function taking
  27805. ** parameters void* and const char* and returning a pointer to a function.
  27806. ** We initialize x by assigning it a pointer to the dlsym() function.
  27807. ** (That assignment requires a cast.) Then we call the function that
  27808. ** x points to.
  27809. **
  27810. ** This work-around is unlikely to work correctly on any system where
  27811. ** you really cannot cast a function pointer into void*. But then, on the
  27812. ** other hand, dlsym() will not work on such a system either, so we have
  27813. ** not really lost anything.
  27814. */
  27815. void (*(*x)(void*,const char*))(void);
  27816. UNUSED_PARAMETER(NotUsed);
  27817. x = (void(*(*)(void*,const char*))(void))dlsym;
  27818. return (*x)(p, zSym);
  27819. }
  27820. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  27821. UNUSED_PARAMETER(NotUsed);
  27822. dlclose(pHandle);
  27823. }
  27824. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  27825. #define unixDlOpen 0
  27826. #define unixDlError 0
  27827. #define unixDlSym 0
  27828. #define unixDlClose 0
  27829. #endif
  27830. /*
  27831. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  27832. */
  27833. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  27834. UNUSED_PARAMETER(NotUsed);
  27835. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  27836. /* We have to initialize zBuf to prevent valgrind from reporting
  27837. ** errors. The reports issued by valgrind are incorrect - we would
  27838. ** prefer that the randomness be increased by making use of the
  27839. ** uninitialized space in zBuf - but valgrind errors tend to worry
  27840. ** some users. Rather than argue, it seems easier just to initialize
  27841. ** the whole array and silence valgrind, even if that means less randomness
  27842. ** in the random seed.
  27843. **
  27844. ** When testing, initializing zBuf[] to zero is all we do. That means
  27845. ** that we always use the same random number sequence. This makes the
  27846. ** tests repeatable.
  27847. */
  27848. memset(zBuf, 0, nBuf);
  27849. #if !defined(SQLITE_TEST)
  27850. {
  27851. int pid, fd, got;
  27852. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  27853. if( fd<0 ){
  27854. time_t t;
  27855. time(&t);
  27856. memcpy(zBuf, &t, sizeof(t));
  27857. pid = getpid();
  27858. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  27859. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  27860. nBuf = sizeof(t) + sizeof(pid);
  27861. }else{
  27862. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  27863. robust_close(0, fd, __LINE__);
  27864. }
  27865. }
  27866. #endif
  27867. return nBuf;
  27868. }
  27869. /*
  27870. ** Sleep for a little while. Return the amount of time slept.
  27871. ** The argument is the number of microseconds we want to sleep.
  27872. ** The return value is the number of microseconds of sleep actually
  27873. ** requested from the underlying operating system, a number which
  27874. ** might be greater than or equal to the argument, but not less
  27875. ** than the argument.
  27876. */
  27877. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  27878. #if OS_VXWORKS
  27879. struct timespec sp;
  27880. sp.tv_sec = microseconds / 1000000;
  27881. sp.tv_nsec = (microseconds % 1000000) * 1000;
  27882. nanosleep(&sp, NULL);
  27883. UNUSED_PARAMETER(NotUsed);
  27884. return microseconds;
  27885. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  27886. usleep(microseconds);
  27887. UNUSED_PARAMETER(NotUsed);
  27888. return microseconds;
  27889. #else
  27890. int seconds = (microseconds+999999)/1000000;
  27891. sleep(seconds);
  27892. UNUSED_PARAMETER(NotUsed);
  27893. return seconds*1000000;
  27894. #endif
  27895. }
  27896. /*
  27897. ** The following variable, if set to a non-zero value, is interpreted as
  27898. ** the number of seconds since 1970 and is used to set the result of
  27899. ** sqlite3OsCurrentTime() during testing.
  27900. */
  27901. #ifdef SQLITE_TEST
  27902. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  27903. #endif
  27904. /*
  27905. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  27906. ** the current time and date as a Julian Day number times 86_400_000. In
  27907. ** other words, write into *piNow the number of milliseconds since the Julian
  27908. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  27909. ** proleptic Gregorian calendar.
  27910. **
  27911. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  27912. ** cannot be found.
  27913. */
  27914. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  27915. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  27916. int rc = SQLITE_OK;
  27917. #if defined(NO_GETTOD)
  27918. time_t t;
  27919. time(&t);
  27920. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  27921. #elif OS_VXWORKS
  27922. struct timespec sNow;
  27923. clock_gettime(CLOCK_REALTIME, &sNow);
  27924. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  27925. #else
  27926. struct timeval sNow;
  27927. if( gettimeofday(&sNow, 0)==0 ){
  27928. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  27929. }else{
  27930. rc = SQLITE_ERROR;
  27931. }
  27932. #endif
  27933. #ifdef SQLITE_TEST
  27934. if( sqlite3_current_time ){
  27935. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  27936. }
  27937. #endif
  27938. UNUSED_PARAMETER(NotUsed);
  27939. return rc;
  27940. }
  27941. /*
  27942. ** Find the current time (in Universal Coordinated Time). Write the
  27943. ** current time and date as a Julian Day number into *prNow and
  27944. ** return 0. Return 1 if the time and date cannot be found.
  27945. */
  27946. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  27947. sqlite3_int64 i = 0;
  27948. int rc;
  27949. UNUSED_PARAMETER(NotUsed);
  27950. rc = unixCurrentTimeInt64(0, &i);
  27951. *prNow = i/86400000.0;
  27952. return rc;
  27953. }
  27954. /*
  27955. ** We added the xGetLastError() method with the intention of providing
  27956. ** better low-level error messages when operating-system problems come up
  27957. ** during SQLite operation. But so far, none of that has been implemented
  27958. ** in the core. So this routine is never called. For now, it is merely
  27959. ** a place-holder.
  27960. */
  27961. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  27962. UNUSED_PARAMETER(NotUsed);
  27963. UNUSED_PARAMETER(NotUsed2);
  27964. UNUSED_PARAMETER(NotUsed3);
  27965. return 0;
  27966. }
  27967. /*
  27968. ************************ End of sqlite3_vfs methods ***************************
  27969. ******************************************************************************/
  27970. /******************************************************************************
  27971. ************************** Begin Proxy Locking ********************************
  27972. **
  27973. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  27974. ** other locking methods on secondary lock files. Proxy locking is a
  27975. ** meta-layer over top of the primitive locking implemented above. For
  27976. ** this reason, the division that implements of proxy locking is deferred
  27977. ** until late in the file (here) after all of the other I/O methods have
  27978. ** been defined - so that the primitive locking methods are available
  27979. ** as services to help with the implementation of proxy locking.
  27980. **
  27981. ****
  27982. **
  27983. ** The default locking schemes in SQLite use byte-range locks on the
  27984. ** database file to coordinate safe, concurrent access by multiple readers
  27985. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  27986. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  27987. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  27988. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  27989. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  27990. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  27991. ** address in the shared range is taken for a SHARED lock, the entire
  27992. ** shared range is taken for an EXCLUSIVE lock):
  27993. **
  27994. ** PENDING_BYTE 0x40000000
  27995. ** RESERVED_BYTE 0x40000001
  27996. ** SHARED_RANGE 0x40000002 -> 0x40000200
  27997. **
  27998. ** This works well on the local file system, but shows a nearly 100x
  27999. ** slowdown in read performance on AFP because the AFP client disables
  28000. ** the read cache when byte-range locks are present. Enabling the read
  28001. ** cache exposes a cache coherency problem that is present on all OS X
  28002. ** supported network file systems. NFS and AFP both observe the
  28003. ** close-to-open semantics for ensuring cache coherency
  28004. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  28005. ** address the requirements for concurrent database access by multiple
  28006. ** readers and writers
  28007. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  28008. **
  28009. ** To address the performance and cache coherency issues, proxy file locking
  28010. ** changes the way database access is controlled by limiting access to a
  28011. ** single host at a time and moving file locks off of the database file
  28012. ** and onto a proxy file on the local file system.
  28013. **
  28014. **
  28015. ** Using proxy locks
  28016. ** -----------------
  28017. **
  28018. ** C APIs
  28019. **
  28020. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  28021. ** <proxy_path> | ":auto:");
  28022. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  28023. **
  28024. **
  28025. ** SQL pragmas
  28026. **
  28027. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  28028. ** PRAGMA [database.]lock_proxy_file
  28029. **
  28030. ** Specifying ":auto:" means that if there is a conch file with a matching
  28031. ** host ID in it, the proxy path in the conch file will be used, otherwise
  28032. ** a proxy path based on the user's temp dir
  28033. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  28034. ** actual proxy file name is generated from the name and path of the
  28035. ** database file. For example:
  28036. **
  28037. ** For database path "/Users/me/foo.db"
  28038. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  28039. **
  28040. ** Once a lock proxy is configured for a database connection, it can not
  28041. ** be removed, however it may be switched to a different proxy path via
  28042. ** the above APIs (assuming the conch file is not being held by another
  28043. ** connection or process).
  28044. **
  28045. **
  28046. ** How proxy locking works
  28047. ** -----------------------
  28048. **
  28049. ** Proxy file locking relies primarily on two new supporting files:
  28050. **
  28051. ** * conch file to limit access to the database file to a single host
  28052. ** at a time
  28053. **
  28054. ** * proxy file to act as a proxy for the advisory locks normally
  28055. ** taken on the database
  28056. **
  28057. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  28058. ** by taking an sqlite-style shared lock on the conch file, reading the
  28059. ** contents and comparing the host's unique host ID (see below) and lock
  28060. ** proxy path against the values stored in the conch. The conch file is
  28061. ** stored in the same directory as the database file and the file name
  28062. ** is patterned after the database file name as ".<databasename>-conch".
  28063. ** If the conch file does not exist, or it's contents do not match the
  28064. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  28065. ** lock and the conch file contents is updated with the host ID and proxy
  28066. ** path and the lock is downgraded to a shared lock again. If the conch
  28067. ** is held by another process (with a shared lock), the exclusive lock
  28068. ** will fail and SQLITE_BUSY is returned.
  28069. **
  28070. ** The proxy file - a single-byte file used for all advisory file locks
  28071. ** normally taken on the database file. This allows for safe sharing
  28072. ** of the database file for multiple readers and writers on the same
  28073. ** host (the conch ensures that they all use the same local lock file).
  28074. **
  28075. ** Requesting the lock proxy does not immediately take the conch, it is
  28076. ** only taken when the first request to lock database file is made.
  28077. ** This matches the semantics of the traditional locking behavior, where
  28078. ** opening a connection to a database file does not take a lock on it.
  28079. ** The shared lock and an open file descriptor are maintained until
  28080. ** the connection to the database is closed.
  28081. **
  28082. ** The proxy file and the lock file are never deleted so they only need
  28083. ** to be created the first time they are used.
  28084. **
  28085. ** Configuration options
  28086. ** ---------------------
  28087. **
  28088. ** SQLITE_PREFER_PROXY_LOCKING
  28089. **
  28090. ** Database files accessed on non-local file systems are
  28091. ** automatically configured for proxy locking, lock files are
  28092. ** named automatically using the same logic as
  28093. ** PRAGMA lock_proxy_file=":auto:"
  28094. **
  28095. ** SQLITE_PROXY_DEBUG
  28096. **
  28097. ** Enables the logging of error messages during host id file
  28098. ** retrieval and creation
  28099. **
  28100. ** LOCKPROXYDIR
  28101. **
  28102. ** Overrides the default directory used for lock proxy files that
  28103. ** are named automatically via the ":auto:" setting
  28104. **
  28105. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  28106. **
  28107. ** Permissions to use when creating a directory for storing the
  28108. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  28109. **
  28110. **
  28111. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  28112. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  28113. ** force proxy locking to be used for every database file opened, and 0
  28114. ** will force automatic proxy locking to be disabled for all database
  28115. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  28116. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  28117. */
  28118. /*
  28119. ** Proxy locking is only available on MacOSX
  28120. */
  28121. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28122. /*
  28123. ** The proxyLockingContext has the path and file structures for the remote
  28124. ** and local proxy files in it
  28125. */
  28126. typedef struct proxyLockingContext proxyLockingContext;
  28127. struct proxyLockingContext {
  28128. unixFile *conchFile; /* Open conch file */
  28129. char *conchFilePath; /* Name of the conch file */
  28130. unixFile *lockProxy; /* Open proxy lock file */
  28131. char *lockProxyPath; /* Name of the proxy lock file */
  28132. char *dbPath; /* Name of the open file */
  28133. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  28134. void *oldLockingContext; /* Original lockingcontext to restore on close */
  28135. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  28136. };
  28137. /*
  28138. ** The proxy lock file path for the database at dbPath is written into lPath,
  28139. ** which must point to valid, writable memory large enough for a maxLen length
  28140. ** file path.
  28141. */
  28142. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  28143. int len;
  28144. int dbLen;
  28145. int i;
  28146. #ifdef LOCKPROXYDIR
  28147. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  28148. #else
  28149. # ifdef _CS_DARWIN_USER_TEMP_DIR
  28150. {
  28151. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  28152. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  28153. lPath, errno, getpid()));
  28154. return SQLITE_IOERR_LOCK;
  28155. }
  28156. len = strlcat(lPath, "sqliteplocks", maxLen);
  28157. }
  28158. # else
  28159. len = strlcpy(lPath, "/tmp/", maxLen);
  28160. # endif
  28161. #endif
  28162. if( lPath[len-1]!='/' ){
  28163. len = strlcat(lPath, "/", maxLen);
  28164. }
  28165. /* transform the db path to a unique cache name */
  28166. dbLen = (int)strlen(dbPath);
  28167. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  28168. char c = dbPath[i];
  28169. lPath[i+len] = (c=='/')?'_':c;
  28170. }
  28171. lPath[i+len]='\0';
  28172. strlcat(lPath, ":auto:", maxLen);
  28173. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  28174. return SQLITE_OK;
  28175. }
  28176. /*
  28177. ** Creates the lock file and any missing directories in lockPath
  28178. */
  28179. static int proxyCreateLockPath(const char *lockPath){
  28180. int i, len;
  28181. char buf[MAXPATHLEN];
  28182. int start = 0;
  28183. assert(lockPath!=NULL);
  28184. /* try to create all the intermediate directories */
  28185. len = (int)strlen(lockPath);
  28186. buf[0] = lockPath[0];
  28187. for( i=1; i<len; i++ ){
  28188. if( lockPath[i] == '/' && (i - start > 0) ){
  28189. /* only mkdir if leaf dir != "." or "/" or ".." */
  28190. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  28191. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  28192. buf[i]='\0';
  28193. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  28194. int err=errno;
  28195. if( err!=EEXIST ) {
  28196. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  28197. "'%s' proxy lock path=%s pid=%d\n",
  28198. buf, strerror(err), lockPath, getpid()));
  28199. return err;
  28200. }
  28201. }
  28202. }
  28203. start=i+1;
  28204. }
  28205. buf[i] = lockPath[i];
  28206. }
  28207. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  28208. return 0;
  28209. }
  28210. /*
  28211. ** Create a new VFS file descriptor (stored in memory obtained from
  28212. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  28213. **
  28214. ** The caller is responsible not only for closing the file descriptor
  28215. ** but also for freeing the memory associated with the file descriptor.
  28216. */
  28217. static int proxyCreateUnixFile(
  28218. const char *path, /* path for the new unixFile */
  28219. unixFile **ppFile, /* unixFile created and returned by ref */
  28220. int islockfile /* if non zero missing dirs will be created */
  28221. ) {
  28222. int fd = -1;
  28223. unixFile *pNew;
  28224. int rc = SQLITE_OK;
  28225. int openFlags = O_RDWR | O_CREAT;
  28226. sqlite3_vfs dummyVfs;
  28227. int terrno = 0;
  28228. UnixUnusedFd *pUnused = NULL;
  28229. /* 1. first try to open/create the file
  28230. ** 2. if that fails, and this is a lock file (not-conch), try creating
  28231. ** the parent directories and then try again.
  28232. ** 3. if that fails, try to open the file read-only
  28233. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  28234. */
  28235. pUnused = findReusableFd(path, openFlags);
  28236. if( pUnused ){
  28237. fd = pUnused->fd;
  28238. }else{
  28239. pUnused = sqlite3_malloc(sizeof(*pUnused));
  28240. if( !pUnused ){
  28241. return SQLITE_NOMEM;
  28242. }
  28243. }
  28244. if( fd<0 ){
  28245. fd = robust_open(path, openFlags, 0);
  28246. terrno = errno;
  28247. if( fd<0 && errno==ENOENT && islockfile ){
  28248. if( proxyCreateLockPath(path) == SQLITE_OK ){
  28249. fd = robust_open(path, openFlags, 0);
  28250. }
  28251. }
  28252. }
  28253. if( fd<0 ){
  28254. openFlags = O_RDONLY;
  28255. fd = robust_open(path, openFlags, 0);
  28256. terrno = errno;
  28257. }
  28258. if( fd<0 ){
  28259. if( islockfile ){
  28260. return SQLITE_BUSY;
  28261. }
  28262. switch (terrno) {
  28263. case EACCES:
  28264. return SQLITE_PERM;
  28265. case EIO:
  28266. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  28267. default:
  28268. return SQLITE_CANTOPEN_BKPT;
  28269. }
  28270. }
  28271. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  28272. if( pNew==NULL ){
  28273. rc = SQLITE_NOMEM;
  28274. goto end_create_proxy;
  28275. }
  28276. memset(pNew, 0, sizeof(unixFile));
  28277. pNew->openFlags = openFlags;
  28278. memset(&dummyVfs, 0, sizeof(dummyVfs));
  28279. dummyVfs.pAppData = (void*)&autolockIoFinder;
  28280. dummyVfs.zName = "dummy";
  28281. pUnused->fd = fd;
  28282. pUnused->flags = openFlags;
  28283. pNew->pUnused = pUnused;
  28284. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  28285. if( rc==SQLITE_OK ){
  28286. *ppFile = pNew;
  28287. return SQLITE_OK;
  28288. }
  28289. end_create_proxy:
  28290. robust_close(pNew, fd, __LINE__);
  28291. sqlite3_free(pNew);
  28292. sqlite3_free(pUnused);
  28293. return rc;
  28294. }
  28295. #ifdef SQLITE_TEST
  28296. /* simulate multiple hosts by creating unique hostid file paths */
  28297. SQLITE_API int sqlite3_hostid_num = 0;
  28298. #endif
  28299. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  28300. /* Not always defined in the headers as it ought to be */
  28301. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  28302. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  28303. ** bytes of writable memory.
  28304. */
  28305. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  28306. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  28307. memset(pHostID, 0, PROXY_HOSTIDLEN);
  28308. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  28309. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  28310. {
  28311. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  28312. if( gethostuuid(pHostID, &timeout) ){
  28313. int err = errno;
  28314. if( pError ){
  28315. *pError = err;
  28316. }
  28317. return SQLITE_IOERR;
  28318. }
  28319. }
  28320. #else
  28321. UNUSED_PARAMETER(pError);
  28322. #endif
  28323. #ifdef SQLITE_TEST
  28324. /* simulate multiple hosts by creating unique hostid file paths */
  28325. if( sqlite3_hostid_num != 0){
  28326. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  28327. }
  28328. #endif
  28329. return SQLITE_OK;
  28330. }
  28331. /* The conch file contains the header, host id and lock file path
  28332. */
  28333. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  28334. #define PROXY_HEADERLEN 1 /* conch file header length */
  28335. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  28336. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  28337. /*
  28338. ** Takes an open conch file, copies the contents to a new path and then moves
  28339. ** it back. The newly created file's file descriptor is assigned to the
  28340. ** conch file structure and finally the original conch file descriptor is
  28341. ** closed. Returns zero if successful.
  28342. */
  28343. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  28344. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28345. unixFile *conchFile = pCtx->conchFile;
  28346. char tPath[MAXPATHLEN];
  28347. char buf[PROXY_MAXCONCHLEN];
  28348. char *cPath = pCtx->conchFilePath;
  28349. size_t readLen = 0;
  28350. size_t pathLen = 0;
  28351. char errmsg[64] = "";
  28352. int fd = -1;
  28353. int rc = -1;
  28354. UNUSED_PARAMETER(myHostID);
  28355. /* create a new path by replace the trailing '-conch' with '-break' */
  28356. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  28357. if( pathLen>MAXPATHLEN || pathLen<6 ||
  28358. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  28359. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  28360. goto end_breaklock;
  28361. }
  28362. /* read the conch content */
  28363. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  28364. if( readLen<PROXY_PATHINDEX ){
  28365. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  28366. goto end_breaklock;
  28367. }
  28368. /* write it out to the temporary break file */
  28369. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  28370. if( fd<0 ){
  28371. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  28372. goto end_breaklock;
  28373. }
  28374. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  28375. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  28376. goto end_breaklock;
  28377. }
  28378. if( rename(tPath, cPath) ){
  28379. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  28380. goto end_breaklock;
  28381. }
  28382. rc = 0;
  28383. fprintf(stderr, "broke stale lock on %s\n", cPath);
  28384. robust_close(pFile, conchFile->h, __LINE__);
  28385. conchFile->h = fd;
  28386. conchFile->openFlags = O_RDWR | O_CREAT;
  28387. end_breaklock:
  28388. if( rc ){
  28389. if( fd>=0 ){
  28390. osUnlink(tPath);
  28391. robust_close(pFile, fd, __LINE__);
  28392. }
  28393. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  28394. }
  28395. return rc;
  28396. }
  28397. /* Take the requested lock on the conch file and break a stale lock if the
  28398. ** host id matches.
  28399. */
  28400. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  28401. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28402. unixFile *conchFile = pCtx->conchFile;
  28403. int rc = SQLITE_OK;
  28404. int nTries = 0;
  28405. struct timespec conchModTime;
  28406. memset(&conchModTime, 0, sizeof(conchModTime));
  28407. do {
  28408. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28409. nTries ++;
  28410. if( rc==SQLITE_BUSY ){
  28411. /* If the lock failed (busy):
  28412. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  28413. * 2nd try: fail if the mod time changed or host id is different, wait
  28414. * 10 sec and try again
  28415. * 3rd try: break the lock unless the mod time has changed.
  28416. */
  28417. struct stat buf;
  28418. if( osFstat(conchFile->h, &buf) ){
  28419. pFile->lastErrno = errno;
  28420. return SQLITE_IOERR_LOCK;
  28421. }
  28422. if( nTries==1 ){
  28423. conchModTime = buf.st_mtimespec;
  28424. usleep(500000); /* wait 0.5 sec and try the lock again*/
  28425. continue;
  28426. }
  28427. assert( nTries>1 );
  28428. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  28429. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  28430. return SQLITE_BUSY;
  28431. }
  28432. if( nTries==2 ){
  28433. char tBuf[PROXY_MAXCONCHLEN];
  28434. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  28435. if( len<0 ){
  28436. pFile->lastErrno = errno;
  28437. return SQLITE_IOERR_LOCK;
  28438. }
  28439. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  28440. /* don't break the lock if the host id doesn't match */
  28441. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  28442. return SQLITE_BUSY;
  28443. }
  28444. }else{
  28445. /* don't break the lock on short read or a version mismatch */
  28446. return SQLITE_BUSY;
  28447. }
  28448. usleep(10000000); /* wait 10 sec and try the lock again */
  28449. continue;
  28450. }
  28451. assert( nTries==3 );
  28452. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  28453. rc = SQLITE_OK;
  28454. if( lockType==EXCLUSIVE_LOCK ){
  28455. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  28456. }
  28457. if( !rc ){
  28458. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28459. }
  28460. }
  28461. }
  28462. } while( rc==SQLITE_BUSY && nTries<3 );
  28463. return rc;
  28464. }
  28465. /* Takes the conch by taking a shared lock and read the contents conch, if
  28466. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  28467. ** lockPath means that the lockPath in the conch file will be used if the
  28468. ** host IDs match, or a new lock path will be generated automatically
  28469. ** and written to the conch file.
  28470. */
  28471. static int proxyTakeConch(unixFile *pFile){
  28472. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28473. if( pCtx->conchHeld!=0 ){
  28474. return SQLITE_OK;
  28475. }else{
  28476. unixFile *conchFile = pCtx->conchFile;
  28477. uuid_t myHostID;
  28478. int pError = 0;
  28479. char readBuf[PROXY_MAXCONCHLEN];
  28480. char lockPath[MAXPATHLEN];
  28481. char *tempLockPath = NULL;
  28482. int rc = SQLITE_OK;
  28483. int createConch = 0;
  28484. int hostIdMatch = 0;
  28485. int readLen = 0;
  28486. int tryOldLockPath = 0;
  28487. int forceNewLockPath = 0;
  28488. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  28489. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  28490. rc = proxyGetHostID(myHostID, &pError);
  28491. if( (rc&0xff)==SQLITE_IOERR ){
  28492. pFile->lastErrno = pError;
  28493. goto end_takeconch;
  28494. }
  28495. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  28496. if( rc!=SQLITE_OK ){
  28497. goto end_takeconch;
  28498. }
  28499. /* read the existing conch file */
  28500. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  28501. if( readLen<0 ){
  28502. /* I/O error: lastErrno set by seekAndRead */
  28503. pFile->lastErrno = conchFile->lastErrno;
  28504. rc = SQLITE_IOERR_READ;
  28505. goto end_takeconch;
  28506. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  28507. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  28508. /* a short read or version format mismatch means we need to create a new
  28509. ** conch file.
  28510. */
  28511. createConch = 1;
  28512. }
  28513. /* if the host id matches and the lock path already exists in the conch
  28514. ** we'll try to use the path there, if we can't open that path, we'll
  28515. ** retry with a new auto-generated path
  28516. */
  28517. do { /* in case we need to try again for an :auto: named lock file */
  28518. if( !createConch && !forceNewLockPath ){
  28519. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  28520. PROXY_HOSTIDLEN);
  28521. /* if the conch has data compare the contents */
  28522. if( !pCtx->lockProxyPath ){
  28523. /* for auto-named local lock file, just check the host ID and we'll
  28524. ** use the local lock file path that's already in there
  28525. */
  28526. if( hostIdMatch ){
  28527. size_t pathLen = (readLen - PROXY_PATHINDEX);
  28528. if( pathLen>=MAXPATHLEN ){
  28529. pathLen=MAXPATHLEN-1;
  28530. }
  28531. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  28532. lockPath[pathLen] = 0;
  28533. tempLockPath = lockPath;
  28534. tryOldLockPath = 1;
  28535. /* create a copy of the lock path if the conch is taken */
  28536. goto end_takeconch;
  28537. }
  28538. }else if( hostIdMatch
  28539. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  28540. readLen-PROXY_PATHINDEX)
  28541. ){
  28542. /* conch host and lock path match */
  28543. goto end_takeconch;
  28544. }
  28545. }
  28546. /* if the conch isn't writable and doesn't match, we can't take it */
  28547. if( (conchFile->openFlags&O_RDWR) == 0 ){
  28548. rc = SQLITE_BUSY;
  28549. goto end_takeconch;
  28550. }
  28551. /* either the conch didn't match or we need to create a new one */
  28552. if( !pCtx->lockProxyPath ){
  28553. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  28554. tempLockPath = lockPath;
  28555. /* create a copy of the lock path _only_ if the conch is taken */
  28556. }
  28557. /* update conch with host and path (this will fail if other process
  28558. ** has a shared lock already), if the host id matches, use the big
  28559. ** stick.
  28560. */
  28561. futimes(conchFile->h, NULL);
  28562. if( hostIdMatch && !createConch ){
  28563. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  28564. /* We are trying for an exclusive lock but another thread in this
  28565. ** same process is still holding a shared lock. */
  28566. rc = SQLITE_BUSY;
  28567. } else {
  28568. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  28569. }
  28570. }else{
  28571. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  28572. }
  28573. if( rc==SQLITE_OK ){
  28574. char writeBuffer[PROXY_MAXCONCHLEN];
  28575. int writeSize = 0;
  28576. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  28577. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  28578. if( pCtx->lockProxyPath!=NULL ){
  28579. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  28580. }else{
  28581. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  28582. }
  28583. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  28584. robust_ftruncate(conchFile->h, writeSize);
  28585. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  28586. fsync(conchFile->h);
  28587. /* If we created a new conch file (not just updated the contents of a
  28588. ** valid conch file), try to match the permissions of the database
  28589. */
  28590. if( rc==SQLITE_OK && createConch ){
  28591. struct stat buf;
  28592. int err = osFstat(pFile->h, &buf);
  28593. if( err==0 ){
  28594. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  28595. S_IROTH|S_IWOTH);
  28596. /* try to match the database file R/W permissions, ignore failure */
  28597. #ifndef SQLITE_PROXY_DEBUG
  28598. osFchmod(conchFile->h, cmode);
  28599. #else
  28600. do{
  28601. rc = osFchmod(conchFile->h, cmode);
  28602. }while( rc==(-1) && errno==EINTR );
  28603. if( rc!=0 ){
  28604. int code = errno;
  28605. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  28606. cmode, code, strerror(code));
  28607. } else {
  28608. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  28609. }
  28610. }else{
  28611. int code = errno;
  28612. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  28613. err, code, strerror(code));
  28614. #endif
  28615. }
  28616. }
  28617. }
  28618. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  28619. end_takeconch:
  28620. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  28621. if( rc==SQLITE_OK && pFile->openFlags ){
  28622. int fd;
  28623. if( pFile->h>=0 ){
  28624. robust_close(pFile, pFile->h, __LINE__);
  28625. }
  28626. pFile->h = -1;
  28627. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  28628. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  28629. if( fd>=0 ){
  28630. pFile->h = fd;
  28631. }else{
  28632. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  28633. during locking */
  28634. }
  28635. }
  28636. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  28637. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  28638. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  28639. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  28640. /* we couldn't create the proxy lock file with the old lock file path
  28641. ** so try again via auto-naming
  28642. */
  28643. forceNewLockPath = 1;
  28644. tryOldLockPath = 0;
  28645. continue; /* go back to the do {} while start point, try again */
  28646. }
  28647. }
  28648. if( rc==SQLITE_OK ){
  28649. /* Need to make a copy of path if we extracted the value
  28650. ** from the conch file or the path was allocated on the stack
  28651. */
  28652. if( tempLockPath ){
  28653. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  28654. if( !pCtx->lockProxyPath ){
  28655. rc = SQLITE_NOMEM;
  28656. }
  28657. }
  28658. }
  28659. if( rc==SQLITE_OK ){
  28660. pCtx->conchHeld = 1;
  28661. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  28662. afpLockingContext *afpCtx;
  28663. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  28664. afpCtx->dbPath = pCtx->lockProxyPath;
  28665. }
  28666. } else {
  28667. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28668. }
  28669. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  28670. rc==SQLITE_OK?"ok":"failed"));
  28671. return rc;
  28672. } while (1); /* in case we need to retry the :auto: lock file -
  28673. ** we should never get here except via the 'continue' call. */
  28674. }
  28675. }
  28676. /*
  28677. ** If pFile holds a lock on a conch file, then release that lock.
  28678. */
  28679. static int proxyReleaseConch(unixFile *pFile){
  28680. int rc = SQLITE_OK; /* Subroutine return code */
  28681. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  28682. unixFile *conchFile; /* Name of the conch file */
  28683. pCtx = (proxyLockingContext *)pFile->lockingContext;
  28684. conchFile = pCtx->conchFile;
  28685. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  28686. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  28687. getpid()));
  28688. if( pCtx->conchHeld>0 ){
  28689. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28690. }
  28691. pCtx->conchHeld = 0;
  28692. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  28693. (rc==SQLITE_OK ? "ok" : "failed")));
  28694. return rc;
  28695. }
  28696. /*
  28697. ** Given the name of a database file, compute the name of its conch file.
  28698. ** Store the conch filename in memory obtained from sqlite3_malloc().
  28699. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  28700. ** or SQLITE_NOMEM if unable to obtain memory.
  28701. **
  28702. ** The caller is responsible for ensuring that the allocated memory
  28703. ** space is eventually freed.
  28704. **
  28705. ** *pConchPath is set to NULL if a memory allocation error occurs.
  28706. */
  28707. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  28708. int i; /* Loop counter */
  28709. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  28710. char *conchPath; /* buffer in which to construct conch name */
  28711. /* Allocate space for the conch filename and initialize the name to
  28712. ** the name of the original database file. */
  28713. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  28714. if( conchPath==0 ){
  28715. return SQLITE_NOMEM;
  28716. }
  28717. memcpy(conchPath, dbPath, len+1);
  28718. /* now insert a "." before the last / character */
  28719. for( i=(len-1); i>=0; i-- ){
  28720. if( conchPath[i]=='/' ){
  28721. i++;
  28722. break;
  28723. }
  28724. }
  28725. conchPath[i]='.';
  28726. while ( i<len ){
  28727. conchPath[i+1]=dbPath[i];
  28728. i++;
  28729. }
  28730. /* append the "-conch" suffix to the file */
  28731. memcpy(&conchPath[i+1], "-conch", 7);
  28732. assert( (int)strlen(conchPath) == len+7 );
  28733. return SQLITE_OK;
  28734. }
  28735. /* Takes a fully configured proxy locking-style unix file and switches
  28736. ** the local lock file path
  28737. */
  28738. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  28739. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28740. char *oldPath = pCtx->lockProxyPath;
  28741. int rc = SQLITE_OK;
  28742. if( pFile->eFileLock!=NO_LOCK ){
  28743. return SQLITE_BUSY;
  28744. }
  28745. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  28746. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  28747. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  28748. return SQLITE_OK;
  28749. }else{
  28750. unixFile *lockProxy = pCtx->lockProxy;
  28751. pCtx->lockProxy=NULL;
  28752. pCtx->conchHeld = 0;
  28753. if( lockProxy!=NULL ){
  28754. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  28755. if( rc ) return rc;
  28756. sqlite3_free(lockProxy);
  28757. }
  28758. sqlite3_free(oldPath);
  28759. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  28760. }
  28761. return rc;
  28762. }
  28763. /*
  28764. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  28765. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  28766. **
  28767. ** This routine find the filename associated with pFile and writes it
  28768. ** int dbPath.
  28769. */
  28770. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  28771. #if defined(__APPLE__)
  28772. if( pFile->pMethod == &afpIoMethods ){
  28773. /* afp style keeps a reference to the db path in the filePath field
  28774. ** of the struct */
  28775. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28776. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  28777. } else
  28778. #endif
  28779. if( pFile->pMethod == &dotlockIoMethods ){
  28780. /* dot lock style uses the locking context to store the dot lock
  28781. ** file path */
  28782. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  28783. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  28784. }else{
  28785. /* all other styles use the locking context to store the db file path */
  28786. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28787. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  28788. }
  28789. return SQLITE_OK;
  28790. }
  28791. /*
  28792. ** Takes an already filled in unix file and alters it so all file locking
  28793. ** will be performed on the local proxy lock file. The following fields
  28794. ** are preserved in the locking context so that they can be restored and
  28795. ** the unix structure properly cleaned up at close time:
  28796. ** ->lockingContext
  28797. ** ->pMethod
  28798. */
  28799. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  28800. proxyLockingContext *pCtx;
  28801. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  28802. char *lockPath=NULL;
  28803. int rc = SQLITE_OK;
  28804. if( pFile->eFileLock!=NO_LOCK ){
  28805. return SQLITE_BUSY;
  28806. }
  28807. proxyGetDbPathForUnixFile(pFile, dbPath);
  28808. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  28809. lockPath=NULL;
  28810. }else{
  28811. lockPath=(char *)path;
  28812. }
  28813. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  28814. (lockPath ? lockPath : ":auto:"), getpid()));
  28815. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28816. if( pCtx==0 ){
  28817. return SQLITE_NOMEM;
  28818. }
  28819. memset(pCtx, 0, sizeof(*pCtx));
  28820. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  28821. if( rc==SQLITE_OK ){
  28822. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  28823. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  28824. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  28825. ** (c) the file system is read-only, then enable no-locking access.
  28826. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  28827. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  28828. */
  28829. struct statfs fsInfo;
  28830. struct stat conchInfo;
  28831. int goLockless = 0;
  28832. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  28833. int err = errno;
  28834. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  28835. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  28836. }
  28837. }
  28838. if( goLockless ){
  28839. pCtx->conchHeld = -1; /* read only FS/ lockless */
  28840. rc = SQLITE_OK;
  28841. }
  28842. }
  28843. }
  28844. if( rc==SQLITE_OK && lockPath ){
  28845. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  28846. }
  28847. if( rc==SQLITE_OK ){
  28848. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  28849. if( pCtx->dbPath==NULL ){
  28850. rc = SQLITE_NOMEM;
  28851. }
  28852. }
  28853. if( rc==SQLITE_OK ){
  28854. /* all memory is allocated, proxys are created and assigned,
  28855. ** switch the locking context and pMethod then return.
  28856. */
  28857. pCtx->oldLockingContext = pFile->lockingContext;
  28858. pFile->lockingContext = pCtx;
  28859. pCtx->pOldMethod = pFile->pMethod;
  28860. pFile->pMethod = &proxyIoMethods;
  28861. }else{
  28862. if( pCtx->conchFile ){
  28863. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  28864. sqlite3_free(pCtx->conchFile);
  28865. }
  28866. sqlite3DbFree(0, pCtx->lockProxyPath);
  28867. sqlite3_free(pCtx->conchFilePath);
  28868. sqlite3_free(pCtx);
  28869. }
  28870. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  28871. (rc==SQLITE_OK ? "ok" : "failed")));
  28872. return rc;
  28873. }
  28874. /*
  28875. ** This routine handles sqlite3_file_control() calls that are specific
  28876. ** to proxy locking.
  28877. */
  28878. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  28879. switch( op ){
  28880. case SQLITE_GET_LOCKPROXYFILE: {
  28881. unixFile *pFile = (unixFile*)id;
  28882. if( pFile->pMethod == &proxyIoMethods ){
  28883. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28884. proxyTakeConch(pFile);
  28885. if( pCtx->lockProxyPath ){
  28886. *(const char **)pArg = pCtx->lockProxyPath;
  28887. }else{
  28888. *(const char **)pArg = ":auto: (not held)";
  28889. }
  28890. } else {
  28891. *(const char **)pArg = NULL;
  28892. }
  28893. return SQLITE_OK;
  28894. }
  28895. case SQLITE_SET_LOCKPROXYFILE: {
  28896. unixFile *pFile = (unixFile*)id;
  28897. int rc = SQLITE_OK;
  28898. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  28899. if( pArg==NULL || (const char *)pArg==0 ){
  28900. if( isProxyStyle ){
  28901. /* turn off proxy locking - not supported */
  28902. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  28903. }else{
  28904. /* turn off proxy locking - already off - NOOP */
  28905. rc = SQLITE_OK;
  28906. }
  28907. }else{
  28908. const char *proxyPath = (const char *)pArg;
  28909. if( isProxyStyle ){
  28910. proxyLockingContext *pCtx =
  28911. (proxyLockingContext*)pFile->lockingContext;
  28912. if( !strcmp(pArg, ":auto:")
  28913. || (pCtx->lockProxyPath &&
  28914. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  28915. ){
  28916. rc = SQLITE_OK;
  28917. }else{
  28918. rc = switchLockProxyPath(pFile, proxyPath);
  28919. }
  28920. }else{
  28921. /* turn on proxy file locking */
  28922. rc = proxyTransformUnixFile(pFile, proxyPath);
  28923. }
  28924. }
  28925. return rc;
  28926. }
  28927. default: {
  28928. assert( 0 ); /* The call assures that only valid opcodes are sent */
  28929. }
  28930. }
  28931. /*NOTREACHED*/
  28932. return SQLITE_ERROR;
  28933. }
  28934. /*
  28935. ** Within this division (the proxying locking implementation) the procedures
  28936. ** above this point are all utilities. The lock-related methods of the
  28937. ** proxy-locking sqlite3_io_method object follow.
  28938. */
  28939. /*
  28940. ** This routine checks if there is a RESERVED lock held on the specified
  28941. ** file by this or any other process. If such a lock is held, set *pResOut
  28942. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28943. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28944. */
  28945. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28946. unixFile *pFile = (unixFile*)id;
  28947. int rc = proxyTakeConch(pFile);
  28948. if( rc==SQLITE_OK ){
  28949. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28950. if( pCtx->conchHeld>0 ){
  28951. unixFile *proxy = pCtx->lockProxy;
  28952. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  28953. }else{ /* conchHeld < 0 is lockless */
  28954. pResOut=0;
  28955. }
  28956. }
  28957. return rc;
  28958. }
  28959. /*
  28960. ** Lock the file with the lock specified by parameter eFileLock - one
  28961. ** of the following:
  28962. **
  28963. ** (1) SHARED_LOCK
  28964. ** (2) RESERVED_LOCK
  28965. ** (3) PENDING_LOCK
  28966. ** (4) EXCLUSIVE_LOCK
  28967. **
  28968. ** Sometimes when requesting one lock state, additional lock states
  28969. ** are inserted in between. The locking might fail on one of the later
  28970. ** transitions leaving the lock state different from what it started but
  28971. ** still short of its goal. The following chart shows the allowed
  28972. ** transitions and the inserted intermediate states:
  28973. **
  28974. ** UNLOCKED -> SHARED
  28975. ** SHARED -> RESERVED
  28976. ** SHARED -> (PENDING) -> EXCLUSIVE
  28977. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28978. ** PENDING -> EXCLUSIVE
  28979. **
  28980. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28981. ** routine to lower a locking level.
  28982. */
  28983. static int proxyLock(sqlite3_file *id, int eFileLock) {
  28984. unixFile *pFile = (unixFile*)id;
  28985. int rc = proxyTakeConch(pFile);
  28986. if( rc==SQLITE_OK ){
  28987. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28988. if( pCtx->conchHeld>0 ){
  28989. unixFile *proxy = pCtx->lockProxy;
  28990. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  28991. pFile->eFileLock = proxy->eFileLock;
  28992. }else{
  28993. /* conchHeld < 0 is lockless */
  28994. }
  28995. }
  28996. return rc;
  28997. }
  28998. /*
  28999. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  29000. ** must be either NO_LOCK or SHARED_LOCK.
  29001. **
  29002. ** If the locking level of the file descriptor is already at or below
  29003. ** the requested locking level, this routine is a no-op.
  29004. */
  29005. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  29006. unixFile *pFile = (unixFile*)id;
  29007. int rc = proxyTakeConch(pFile);
  29008. if( rc==SQLITE_OK ){
  29009. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29010. if( pCtx->conchHeld>0 ){
  29011. unixFile *proxy = pCtx->lockProxy;
  29012. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  29013. pFile->eFileLock = proxy->eFileLock;
  29014. }else{
  29015. /* conchHeld < 0 is lockless */
  29016. }
  29017. }
  29018. return rc;
  29019. }
  29020. /*
  29021. ** Close a file that uses proxy locks.
  29022. */
  29023. static int proxyClose(sqlite3_file *id) {
  29024. if( id ){
  29025. unixFile *pFile = (unixFile*)id;
  29026. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29027. unixFile *lockProxy = pCtx->lockProxy;
  29028. unixFile *conchFile = pCtx->conchFile;
  29029. int rc = SQLITE_OK;
  29030. if( lockProxy ){
  29031. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  29032. if( rc ) return rc;
  29033. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  29034. if( rc ) return rc;
  29035. sqlite3_free(lockProxy);
  29036. pCtx->lockProxy = 0;
  29037. }
  29038. if( conchFile ){
  29039. if( pCtx->conchHeld ){
  29040. rc = proxyReleaseConch(pFile);
  29041. if( rc ) return rc;
  29042. }
  29043. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  29044. if( rc ) return rc;
  29045. sqlite3_free(conchFile);
  29046. }
  29047. sqlite3DbFree(0, pCtx->lockProxyPath);
  29048. sqlite3_free(pCtx->conchFilePath);
  29049. sqlite3DbFree(0, pCtx->dbPath);
  29050. /* restore the original locking context and pMethod then close it */
  29051. pFile->lockingContext = pCtx->oldLockingContext;
  29052. pFile->pMethod = pCtx->pOldMethod;
  29053. sqlite3_free(pCtx);
  29054. return pFile->pMethod->xClose(id);
  29055. }
  29056. return SQLITE_OK;
  29057. }
  29058. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  29059. /*
  29060. ** The proxy locking style is intended for use with AFP filesystems.
  29061. ** And since AFP is only supported on MacOSX, the proxy locking is also
  29062. ** restricted to MacOSX.
  29063. **
  29064. **
  29065. ******************* End of the proxy lock implementation **********************
  29066. ******************************************************************************/
  29067. /*
  29068. ** Initialize the operating system interface.
  29069. **
  29070. ** This routine registers all VFS implementations for unix-like operating
  29071. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  29072. ** should be the only routines in this file that are visible from other
  29073. ** files.
  29074. **
  29075. ** This routine is called once during SQLite initialization and by a
  29076. ** single thread. The memory allocation and mutex subsystems have not
  29077. ** necessarily been initialized when this routine is called, and so they
  29078. ** should not be used.
  29079. */
  29080. SQLITE_API int sqlite3_os_init(void){
  29081. /*
  29082. ** The following macro defines an initializer for an sqlite3_vfs object.
  29083. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  29084. ** to the "finder" function. (pAppData is a pointer to a pointer because
  29085. ** silly C90 rules prohibit a void* from being cast to a function pointer
  29086. ** and so we have to go through the intermediate pointer to avoid problems
  29087. ** when compiling with -pedantic-errors on GCC.)
  29088. **
  29089. ** The FINDER parameter to this macro is the name of the pointer to the
  29090. ** finder-function. The finder-function returns a pointer to the
  29091. ** sqlite_io_methods object that implements the desired locking
  29092. ** behaviors. See the division above that contains the IOMETHODS
  29093. ** macro for addition information on finder-functions.
  29094. **
  29095. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  29096. ** object. But the "autolockIoFinder" available on MacOSX does a little
  29097. ** more than that; it looks at the filesystem type that hosts the
  29098. ** database file and tries to choose an locking method appropriate for
  29099. ** that filesystem time.
  29100. */
  29101. #define UNIXVFS(VFSNAME, FINDER) { \
  29102. 3, /* iVersion */ \
  29103. sizeof(unixFile), /* szOsFile */ \
  29104. MAX_PATHNAME, /* mxPathname */ \
  29105. 0, /* pNext */ \
  29106. VFSNAME, /* zName */ \
  29107. (void*)&FINDER, /* pAppData */ \
  29108. unixOpen, /* xOpen */ \
  29109. unixDelete, /* xDelete */ \
  29110. unixAccess, /* xAccess */ \
  29111. unixFullPathname, /* xFullPathname */ \
  29112. unixDlOpen, /* xDlOpen */ \
  29113. unixDlError, /* xDlError */ \
  29114. unixDlSym, /* xDlSym */ \
  29115. unixDlClose, /* xDlClose */ \
  29116. unixRandomness, /* xRandomness */ \
  29117. unixSleep, /* xSleep */ \
  29118. unixCurrentTime, /* xCurrentTime */ \
  29119. unixGetLastError, /* xGetLastError */ \
  29120. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  29121. unixSetSystemCall, /* xSetSystemCall */ \
  29122. unixGetSystemCall, /* xGetSystemCall */ \
  29123. unixNextSystemCall, /* xNextSystemCall */ \
  29124. }
  29125. /*
  29126. ** All default VFSes for unix are contained in the following array.
  29127. **
  29128. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  29129. ** by the SQLite core when the VFS is registered. So the following
  29130. ** array cannot be const.
  29131. */
  29132. static sqlite3_vfs aVfs[] = {
  29133. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  29134. UNIXVFS("unix", autolockIoFinder ),
  29135. #else
  29136. UNIXVFS("unix", posixIoFinder ),
  29137. #endif
  29138. UNIXVFS("unix-none", nolockIoFinder ),
  29139. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  29140. UNIXVFS("unix-excl", posixIoFinder ),
  29141. #if OS_VXWORKS
  29142. UNIXVFS("unix-namedsem", semIoFinder ),
  29143. #endif
  29144. #if SQLITE_ENABLE_LOCKING_STYLE
  29145. UNIXVFS("unix-posix", posixIoFinder ),
  29146. #if !OS_VXWORKS
  29147. UNIXVFS("unix-flock", flockIoFinder ),
  29148. #endif
  29149. #endif
  29150. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29151. UNIXVFS("unix-afp", afpIoFinder ),
  29152. UNIXVFS("unix-nfs", nfsIoFinder ),
  29153. UNIXVFS("unix-proxy", proxyIoFinder ),
  29154. #endif
  29155. };
  29156. unsigned int i; /* Loop counter */
  29157. /* Double-check that the aSyscall[] array has been constructed
  29158. ** correctly. See ticket [bb3a86e890c8e96ab] */
  29159. assert( ArraySize(aSyscall)==24 );
  29160. /* Register all VFSes defined in the aVfs[] array */
  29161. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  29162. sqlite3_vfs_register(&aVfs[i], i==0);
  29163. }
  29164. return SQLITE_OK;
  29165. }
  29166. /*
  29167. ** Shutdown the operating system interface.
  29168. **
  29169. ** Some operating systems might need to do some cleanup in this routine,
  29170. ** to release dynamically allocated objects. But not on unix.
  29171. ** This routine is a no-op for unix.
  29172. */
  29173. SQLITE_API int sqlite3_os_end(void){
  29174. return SQLITE_OK;
  29175. }
  29176. #endif /* SQLITE_OS_UNIX */
  29177. /************** End of os_unix.c *********************************************/
  29178. /************** Begin file os_win.c ******************************************/
  29179. /*
  29180. ** 2004 May 22
  29181. **
  29182. ** The author disclaims copyright to this source code. In place of
  29183. ** a legal notice, here is a blessing:
  29184. **
  29185. ** May you do good and not evil.
  29186. ** May you find forgiveness for yourself and forgive others.
  29187. ** May you share freely, never taking more than you give.
  29188. **
  29189. ******************************************************************************
  29190. **
  29191. ** This file contains code that is specific to Windows.
  29192. */
  29193. #if SQLITE_OS_WIN /* This file is used for Windows only */
  29194. #ifdef __CYGWIN__
  29195. # include <sys/cygwin.h>
  29196. # include <errno.h> /* amalgamator: keep */
  29197. #endif
  29198. /*
  29199. ** Include code that is common to all os_*.c files
  29200. */
  29201. /************** Include os_common.h in the middle of os_win.c ****************/
  29202. /************** Begin file os_common.h ***************************************/
  29203. /*
  29204. ** 2004 May 22
  29205. **
  29206. ** The author disclaims copyright to this source code. In place of
  29207. ** a legal notice, here is a blessing:
  29208. **
  29209. ** May you do good and not evil.
  29210. ** May you find forgiveness for yourself and forgive others.
  29211. ** May you share freely, never taking more than you give.
  29212. **
  29213. ******************************************************************************
  29214. **
  29215. ** This file contains macros and a little bit of code that is common to
  29216. ** all of the platform-specific files (os_*.c) and is #included into those
  29217. ** files.
  29218. **
  29219. ** This file should be #included by the os_*.c files only. It is not a
  29220. ** general purpose header file.
  29221. */
  29222. #ifndef _OS_COMMON_H_
  29223. #define _OS_COMMON_H_
  29224. /*
  29225. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  29226. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  29227. ** switch. The following code should catch this problem at compile-time.
  29228. */
  29229. #ifdef MEMORY_DEBUG
  29230. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  29231. #endif
  29232. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  29233. # ifndef SQLITE_DEBUG_OS_TRACE
  29234. # define SQLITE_DEBUG_OS_TRACE 0
  29235. # endif
  29236. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  29237. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  29238. #else
  29239. # define OSTRACE(X)
  29240. #endif
  29241. /*
  29242. ** Macros for performance tracing. Normally turned off. Only works
  29243. ** on i486 hardware.
  29244. */
  29245. #ifdef SQLITE_PERFORMANCE_TRACE
  29246. /*
  29247. ** hwtime.h contains inline assembler code for implementing
  29248. ** high-performance timing routines.
  29249. */
  29250. /************** Include hwtime.h in the middle of os_common.h ****************/
  29251. /************** Begin file hwtime.h ******************************************/
  29252. /*
  29253. ** 2008 May 27
  29254. **
  29255. ** The author disclaims copyright to this source code. In place of
  29256. ** a legal notice, here is a blessing:
  29257. **
  29258. ** May you do good and not evil.
  29259. ** May you find forgiveness for yourself and forgive others.
  29260. ** May you share freely, never taking more than you give.
  29261. **
  29262. ******************************************************************************
  29263. **
  29264. ** This file contains inline asm code for retrieving "high-performance"
  29265. ** counters for x86 class CPUs.
  29266. */
  29267. #ifndef _HWTIME_H_
  29268. #define _HWTIME_H_
  29269. /*
  29270. ** The following routine only works on pentium-class (or newer) processors.
  29271. ** It uses the RDTSC opcode to read the cycle count value out of the
  29272. ** processor and returns that value. This can be used for high-res
  29273. ** profiling.
  29274. */
  29275. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  29276. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  29277. #if defined(__GNUC__)
  29278. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29279. unsigned int lo, hi;
  29280. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  29281. return (sqlite_uint64)hi << 32 | lo;
  29282. }
  29283. #elif defined(_MSC_VER)
  29284. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  29285. __asm {
  29286. rdtsc
  29287. ret ; return value at EDX:EAX
  29288. }
  29289. }
  29290. #endif
  29291. #elif (defined(__GNUC__) && defined(__x86_64__))
  29292. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29293. unsigned long val;
  29294. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  29295. return val;
  29296. }
  29297. #elif (defined(__GNUC__) && defined(__ppc__))
  29298. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29299. unsigned long long retval;
  29300. unsigned long junk;
  29301. __asm__ __volatile__ ("\n\
  29302. 1: mftbu %1\n\
  29303. mftb %L0\n\
  29304. mftbu %0\n\
  29305. cmpw %0,%1\n\
  29306. bne 1b"
  29307. : "=r" (retval), "=r" (junk));
  29308. return retval;
  29309. }
  29310. #else
  29311. #error Need implementation of sqlite3Hwtime() for your platform.
  29312. /*
  29313. ** To compile without implementing sqlite3Hwtime() for your platform,
  29314. ** you can remove the above #error and use the following
  29315. ** stub function. You will lose timing support for many
  29316. ** of the debugging and testing utilities, but it should at
  29317. ** least compile and run.
  29318. */
  29319. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  29320. #endif
  29321. #endif /* !defined(_HWTIME_H_) */
  29322. /************** End of hwtime.h **********************************************/
  29323. /************** Continuing where we left off in os_common.h ******************/
  29324. static sqlite_uint64 g_start;
  29325. static sqlite_uint64 g_elapsed;
  29326. #define TIMER_START g_start=sqlite3Hwtime()
  29327. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  29328. #define TIMER_ELAPSED g_elapsed
  29329. #else
  29330. #define TIMER_START
  29331. #define TIMER_END
  29332. #define TIMER_ELAPSED ((sqlite_uint64)0)
  29333. #endif
  29334. /*
  29335. ** If we compile with the SQLITE_TEST macro set, then the following block
  29336. ** of code will give us the ability to simulate a disk I/O error. This
  29337. ** is used for testing the I/O recovery logic.
  29338. */
  29339. #ifdef SQLITE_TEST
  29340. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  29341. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  29342. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  29343. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  29344. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  29345. SQLITE_API int sqlite3_diskfull_pending = 0;
  29346. SQLITE_API int sqlite3_diskfull = 0;
  29347. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  29348. #define SimulateIOError(CODE) \
  29349. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29350. || sqlite3_io_error_pending-- == 1 ) \
  29351. { local_ioerr(); CODE; }
  29352. static void local_ioerr(){
  29353. IOTRACE(("IOERR\n"));
  29354. sqlite3_io_error_hit++;
  29355. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29356. }
  29357. #define SimulateDiskfullError(CODE) \
  29358. if( sqlite3_diskfull_pending ){ \
  29359. if( sqlite3_diskfull_pending == 1 ){ \
  29360. local_ioerr(); \
  29361. sqlite3_diskfull = 1; \
  29362. sqlite3_io_error_hit = 1; \
  29363. CODE; \
  29364. }else{ \
  29365. sqlite3_diskfull_pending--; \
  29366. } \
  29367. }
  29368. #else
  29369. #define SimulateIOErrorBenign(X)
  29370. #define SimulateIOError(A)
  29371. #define SimulateDiskfullError(A)
  29372. #endif
  29373. /*
  29374. ** When testing, keep a count of the number of open files.
  29375. */
  29376. #ifdef SQLITE_TEST
  29377. SQLITE_API int sqlite3_open_file_count = 0;
  29378. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29379. #else
  29380. #define OpenCounter(X)
  29381. #endif
  29382. #endif /* !defined(_OS_COMMON_H_) */
  29383. /************** End of os_common.h *******************************************/
  29384. /************** Continuing where we left off in os_win.c *********************/
  29385. /*
  29386. ** Compiling and using WAL mode requires several APIs that are only
  29387. ** available in Windows platforms based on the NT kernel.
  29388. */
  29389. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  29390. # error "WAL mode requires support from the Windows NT kernel, compile\
  29391. with SQLITE_OMIT_WAL."
  29392. #endif
  29393. /*
  29394. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  29395. ** based on the sub-platform)?
  29396. */
  29397. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  29398. # define SQLITE_WIN32_HAS_ANSI
  29399. #endif
  29400. /*
  29401. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  29402. ** based on the sub-platform)?
  29403. */
  29404. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  29405. !defined(SQLITE_WIN32_NO_WIDE)
  29406. # define SQLITE_WIN32_HAS_WIDE
  29407. #endif
  29408. /*
  29409. ** Make sure at least one set of Win32 APIs is available.
  29410. */
  29411. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  29412. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  29413. must be defined."
  29414. #endif
  29415. /*
  29416. ** Maximum pathname length (in chars) for Win32. This should normally be
  29417. ** MAX_PATH.
  29418. */
  29419. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  29420. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  29421. #endif
  29422. /*
  29423. ** Maximum pathname length (in chars) for WinNT. This should normally be
  29424. ** 32767.
  29425. */
  29426. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  29427. # define SQLITE_WINNT_MAX_PATH_CHARS (32767)
  29428. #endif
  29429. /*
  29430. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  29431. ** characters, so we allocate 3 bytes per character assuming worst-case of
  29432. ** 4-bytes-per-character for UTF8.
  29433. */
  29434. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  29435. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  29436. #endif
  29437. /*
  29438. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  29439. ** 32767 * sizeof(WCHAR).
  29440. */
  29441. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  29442. # define SQLITE_WINNT_MAX_PATH_BYTES \
  29443. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  29444. #endif
  29445. /*
  29446. ** Maximum error message length (in chars) for WinRT.
  29447. */
  29448. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  29449. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  29450. #endif
  29451. /*
  29452. ** Returns non-zero if the character should be treated as a directory
  29453. ** separator.
  29454. */
  29455. #ifndef winIsDirSep
  29456. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  29457. #endif
  29458. /*
  29459. ** This macro is used when a local variable is set to a value that is
  29460. ** [sometimes] not used by the code (e.g. via conditional compilation).
  29461. */
  29462. #ifndef UNUSED_VARIABLE_VALUE
  29463. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  29464. #endif
  29465. /*
  29466. ** Returns the string that should be used as the directory separator.
  29467. */
  29468. #ifndef winGetDirDep
  29469. # ifdef __CYGWIN__
  29470. # define winGetDirDep() "/"
  29471. # else
  29472. # define winGetDirDep() "\\"
  29473. # endif
  29474. #endif
  29475. /*
  29476. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  29477. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  29478. ** are not present in the header file)?
  29479. */
  29480. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  29481. /*
  29482. ** Two of the file mapping APIs are different under WinRT. Figure out which
  29483. ** set we need.
  29484. */
  29485. #if SQLITE_OS_WINRT
  29486. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  29487. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  29488. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  29489. #else
  29490. #if defined(SQLITE_WIN32_HAS_ANSI)
  29491. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  29492. DWORD, DWORD, DWORD, LPCSTR);
  29493. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  29494. #if defined(SQLITE_WIN32_HAS_WIDE)
  29495. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  29496. DWORD, DWORD, DWORD, LPCWSTR);
  29497. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  29498. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  29499. #endif /* SQLITE_OS_WINRT */
  29500. /*
  29501. ** This file mapping API is common to both Win32 and WinRT.
  29502. */
  29503. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  29504. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  29505. /*
  29506. ** Some Microsoft compilers lack this definition.
  29507. */
  29508. #ifndef INVALID_FILE_ATTRIBUTES
  29509. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  29510. #endif
  29511. #ifndef FILE_FLAG_MASK
  29512. # define FILE_FLAG_MASK (0xFF3C0000)
  29513. #endif
  29514. #ifndef FILE_ATTRIBUTE_MASK
  29515. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  29516. #endif
  29517. #ifndef SQLITE_OMIT_WAL
  29518. /* Forward references to structures used for WAL */
  29519. typedef struct winShm winShm; /* A connection to shared-memory */
  29520. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  29521. #endif
  29522. /*
  29523. ** WinCE lacks native support for file locking so we have to fake it
  29524. ** with some code of our own.
  29525. */
  29526. #if SQLITE_OS_WINCE
  29527. typedef struct winceLock {
  29528. int nReaders; /* Number of reader locks obtained */
  29529. BOOL bPending; /* Indicates a pending lock has been obtained */
  29530. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  29531. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  29532. } winceLock;
  29533. #endif
  29534. /*
  29535. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  29536. ** portability layer.
  29537. */
  29538. typedef struct winFile winFile;
  29539. struct winFile {
  29540. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  29541. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  29542. HANDLE h; /* Handle for accessing the file */
  29543. u8 locktype; /* Type of lock currently held on this file */
  29544. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  29545. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  29546. DWORD lastErrno; /* The Windows errno from the last I/O error */
  29547. #ifndef SQLITE_OMIT_WAL
  29548. winShm *pShm; /* Instance of shared memory on this file */
  29549. #endif
  29550. const char *zPath; /* Full pathname of this file */
  29551. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  29552. #if SQLITE_OS_WINCE
  29553. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  29554. HANDLE hMutex; /* Mutex used to control access to shared lock */
  29555. HANDLE hShared; /* Shared memory segment used for locking */
  29556. winceLock local; /* Locks obtained by this instance of winFile */
  29557. winceLock *shared; /* Global shared lock memory for the file */
  29558. #endif
  29559. #if SQLITE_MAX_MMAP_SIZE>0
  29560. int nFetchOut; /* Number of outstanding xFetch references */
  29561. HANDLE hMap; /* Handle for accessing memory mapping */
  29562. void *pMapRegion; /* Area memory mapped */
  29563. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  29564. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  29565. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  29566. #endif
  29567. };
  29568. /*
  29569. ** Allowed values for winFile.ctrlFlags
  29570. */
  29571. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  29572. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  29573. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  29574. /*
  29575. * The size of the buffer used by sqlite3_win32_write_debug().
  29576. */
  29577. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  29578. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  29579. #endif
  29580. /*
  29581. * The value used with sqlite3_win32_set_directory() to specify that
  29582. * the data directory should be changed.
  29583. */
  29584. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  29585. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  29586. #endif
  29587. /*
  29588. * The value used with sqlite3_win32_set_directory() to specify that
  29589. * the temporary directory should be changed.
  29590. */
  29591. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  29592. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  29593. #endif
  29594. /*
  29595. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  29596. * various Win32 API heap functions instead of our own.
  29597. */
  29598. #ifdef SQLITE_WIN32_MALLOC
  29599. /*
  29600. * If this is non-zero, an isolated heap will be created by the native Win32
  29601. * allocator subsystem; otherwise, the default process heap will be used. This
  29602. * setting has no effect when compiling for WinRT. By default, this is enabled
  29603. * and an isolated heap will be created to store all allocated data.
  29604. *
  29605. ******************************************************************************
  29606. * WARNING: It is important to note that when this setting is non-zero and the
  29607. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  29608. * function), all data that was allocated using the isolated heap will
  29609. * be freed immediately and any attempt to access any of that freed
  29610. * data will almost certainly result in an immediate access violation.
  29611. ******************************************************************************
  29612. */
  29613. #ifndef SQLITE_WIN32_HEAP_CREATE
  29614. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  29615. #endif
  29616. /*
  29617. * The initial size of the Win32-specific heap. This value may be zero.
  29618. */
  29619. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  29620. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  29621. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  29622. #endif
  29623. /*
  29624. * The maximum size of the Win32-specific heap. This value may be zero.
  29625. */
  29626. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  29627. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  29628. #endif
  29629. /*
  29630. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  29631. * zero for the default behavior.
  29632. */
  29633. #ifndef SQLITE_WIN32_HEAP_FLAGS
  29634. # define SQLITE_WIN32_HEAP_FLAGS (0)
  29635. #endif
  29636. /*
  29637. ** The winMemData structure stores information required by the Win32-specific
  29638. ** sqlite3_mem_methods implementation.
  29639. */
  29640. typedef struct winMemData winMemData;
  29641. struct winMemData {
  29642. #ifndef NDEBUG
  29643. u32 magic; /* Magic number to detect structure corruption. */
  29644. #endif
  29645. HANDLE hHeap; /* The handle to our heap. */
  29646. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  29647. };
  29648. #ifndef NDEBUG
  29649. #define WINMEM_MAGIC 0x42b2830b
  29650. #endif
  29651. static struct winMemData win_mem_data = {
  29652. #ifndef NDEBUG
  29653. WINMEM_MAGIC,
  29654. #endif
  29655. NULL, FALSE
  29656. };
  29657. #ifndef NDEBUG
  29658. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  29659. #else
  29660. #define winMemAssertMagic()
  29661. #endif
  29662. #define winMemGetHeap() win_mem_data.hHeap
  29663. static void *winMemMalloc(int nBytes);
  29664. static void winMemFree(void *pPrior);
  29665. static void *winMemRealloc(void *pPrior, int nBytes);
  29666. static int winMemSize(void *p);
  29667. static int winMemRoundup(int n);
  29668. static int winMemInit(void *pAppData);
  29669. static void winMemShutdown(void *pAppData);
  29670. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  29671. #endif /* SQLITE_WIN32_MALLOC */
  29672. /*
  29673. ** The following variable is (normally) set once and never changes
  29674. ** thereafter. It records whether the operating system is Win9x
  29675. ** or WinNT.
  29676. **
  29677. ** 0: Operating system unknown.
  29678. ** 1: Operating system is Win9x.
  29679. ** 2: Operating system is WinNT.
  29680. **
  29681. ** In order to facilitate testing on a WinNT system, the test fixture
  29682. ** can manually set this value to 1 to emulate Win98 behavior.
  29683. */
  29684. #ifdef SQLITE_TEST
  29685. SQLITE_API int sqlite3_os_type = 0;
  29686. #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  29687. defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
  29688. static int sqlite3_os_type = 0;
  29689. #endif
  29690. #ifndef SYSCALL
  29691. # define SYSCALL sqlite3_syscall_ptr
  29692. #endif
  29693. /*
  29694. ** This function is not available on Windows CE or WinRT.
  29695. */
  29696. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29697. # define osAreFileApisANSI() 1
  29698. #endif
  29699. /*
  29700. ** Many system calls are accessed through pointer-to-functions so that
  29701. ** they may be overridden at runtime to facilitate fault injection during
  29702. ** testing and sandboxing. The following array holds the names and pointers
  29703. ** to all overrideable system calls.
  29704. */
  29705. static struct win_syscall {
  29706. const char *zName; /* Name of the system call */
  29707. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  29708. sqlite3_syscall_ptr pDefault; /* Default value */
  29709. } aSyscall[] = {
  29710. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29711. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  29712. #else
  29713. { "AreFileApisANSI", (SYSCALL)0, 0 },
  29714. #endif
  29715. #ifndef osAreFileApisANSI
  29716. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  29717. #endif
  29718. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29719. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  29720. #else
  29721. { "CharLowerW", (SYSCALL)0, 0 },
  29722. #endif
  29723. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  29724. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29725. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  29726. #else
  29727. { "CharUpperW", (SYSCALL)0, 0 },
  29728. #endif
  29729. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  29730. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  29731. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  29732. #if defined(SQLITE_WIN32_HAS_ANSI)
  29733. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  29734. #else
  29735. { "CreateFileA", (SYSCALL)0, 0 },
  29736. #endif
  29737. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  29738. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  29739. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29740. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  29741. #else
  29742. { "CreateFileW", (SYSCALL)0, 0 },
  29743. #endif
  29744. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  29745. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  29746. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  29747. !defined(SQLITE_OMIT_WAL))
  29748. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  29749. #else
  29750. { "CreateFileMappingA", (SYSCALL)0, 0 },
  29751. #endif
  29752. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29753. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  29754. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29755. !defined(SQLITE_OMIT_WAL))
  29756. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  29757. #else
  29758. { "CreateFileMappingW", (SYSCALL)0, 0 },
  29759. #endif
  29760. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29761. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  29762. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29763. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  29764. #else
  29765. { "CreateMutexW", (SYSCALL)0, 0 },
  29766. #endif
  29767. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  29768. LPCWSTR))aSyscall[8].pCurrent)
  29769. #if defined(SQLITE_WIN32_HAS_ANSI)
  29770. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  29771. #else
  29772. { "DeleteFileA", (SYSCALL)0, 0 },
  29773. #endif
  29774. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  29775. #if defined(SQLITE_WIN32_HAS_WIDE)
  29776. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  29777. #else
  29778. { "DeleteFileW", (SYSCALL)0, 0 },
  29779. #endif
  29780. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  29781. #if SQLITE_OS_WINCE
  29782. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  29783. #else
  29784. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  29785. #endif
  29786. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29787. LPFILETIME))aSyscall[11].pCurrent)
  29788. #if SQLITE_OS_WINCE
  29789. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  29790. #else
  29791. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  29792. #endif
  29793. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29794. LPSYSTEMTIME))aSyscall[12].pCurrent)
  29795. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  29796. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  29797. #if defined(SQLITE_WIN32_HAS_ANSI)
  29798. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  29799. #else
  29800. { "FormatMessageA", (SYSCALL)0, 0 },
  29801. #endif
  29802. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  29803. DWORD,va_list*))aSyscall[14].pCurrent)
  29804. #if defined(SQLITE_WIN32_HAS_WIDE)
  29805. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  29806. #else
  29807. { "FormatMessageW", (SYSCALL)0, 0 },
  29808. #endif
  29809. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  29810. DWORD,va_list*))aSyscall[15].pCurrent)
  29811. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29812. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  29813. #else
  29814. { "FreeLibrary", (SYSCALL)0, 0 },
  29815. #endif
  29816. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  29817. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  29818. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  29819. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29820. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  29821. #else
  29822. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  29823. #endif
  29824. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  29825. LPDWORD))aSyscall[18].pCurrent)
  29826. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29827. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  29828. #else
  29829. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  29830. #endif
  29831. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  29832. LPDWORD))aSyscall[19].pCurrent)
  29833. #if defined(SQLITE_WIN32_HAS_ANSI)
  29834. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  29835. #else
  29836. { "GetFileAttributesA", (SYSCALL)0, 0 },
  29837. #endif
  29838. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  29839. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29840. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  29841. #else
  29842. { "GetFileAttributesW", (SYSCALL)0, 0 },
  29843. #endif
  29844. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  29845. #if defined(SQLITE_WIN32_HAS_WIDE)
  29846. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  29847. #else
  29848. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  29849. #endif
  29850. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  29851. LPVOID))aSyscall[22].pCurrent)
  29852. #if !SQLITE_OS_WINRT
  29853. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  29854. #else
  29855. { "GetFileSize", (SYSCALL)0, 0 },
  29856. #endif
  29857. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  29858. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29859. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  29860. #else
  29861. { "GetFullPathNameA", (SYSCALL)0, 0 },
  29862. #endif
  29863. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  29864. LPSTR*))aSyscall[24].pCurrent)
  29865. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29866. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  29867. #else
  29868. { "GetFullPathNameW", (SYSCALL)0, 0 },
  29869. #endif
  29870. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  29871. LPWSTR*))aSyscall[25].pCurrent)
  29872. { "GetLastError", (SYSCALL)GetLastError, 0 },
  29873. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  29874. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29875. #if SQLITE_OS_WINCE
  29876. /* The GetProcAddressA() routine is only available on Windows CE. */
  29877. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  29878. #else
  29879. /* All other Windows platforms expect GetProcAddress() to take
  29880. ** an ANSI string regardless of the _UNICODE setting */
  29881. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  29882. #endif
  29883. #else
  29884. { "GetProcAddressA", (SYSCALL)0, 0 },
  29885. #endif
  29886. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  29887. LPCSTR))aSyscall[27].pCurrent)
  29888. #if !SQLITE_OS_WINRT
  29889. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  29890. #else
  29891. { "GetSystemInfo", (SYSCALL)0, 0 },
  29892. #endif
  29893. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  29894. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  29895. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  29896. #if !SQLITE_OS_WINCE
  29897. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  29898. #else
  29899. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  29900. #endif
  29901. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  29902. LPFILETIME))aSyscall[30].pCurrent)
  29903. #if defined(SQLITE_WIN32_HAS_ANSI)
  29904. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  29905. #else
  29906. { "GetTempPathA", (SYSCALL)0, 0 },
  29907. #endif
  29908. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  29909. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29910. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  29911. #else
  29912. { "GetTempPathW", (SYSCALL)0, 0 },
  29913. #endif
  29914. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  29915. #if !SQLITE_OS_WINRT
  29916. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  29917. #else
  29918. { "GetTickCount", (SYSCALL)0, 0 },
  29919. #endif
  29920. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  29921. #if defined(SQLITE_WIN32_HAS_ANSI)
  29922. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  29923. #else
  29924. { "GetVersionExA", (SYSCALL)0, 0 },
  29925. #endif
  29926. #define osGetVersionExA ((BOOL(WINAPI*)( \
  29927. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  29928. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29929. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  29930. #else
  29931. { "GetVersionExW", (SYSCALL)0, 0 },
  29932. #endif
  29933. #define osGetVersionExW ((BOOL(WINAPI*)( \
  29934. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  29935. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  29936. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  29937. SIZE_T))aSyscall[36].pCurrent)
  29938. #if !SQLITE_OS_WINRT
  29939. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  29940. #else
  29941. { "HeapCreate", (SYSCALL)0, 0 },
  29942. #endif
  29943. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  29944. SIZE_T))aSyscall[37].pCurrent)
  29945. #if !SQLITE_OS_WINRT
  29946. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  29947. #else
  29948. { "HeapDestroy", (SYSCALL)0, 0 },
  29949. #endif
  29950. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  29951. { "HeapFree", (SYSCALL)HeapFree, 0 },
  29952. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  29953. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  29954. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  29955. SIZE_T))aSyscall[40].pCurrent)
  29956. { "HeapSize", (SYSCALL)HeapSize, 0 },
  29957. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  29958. LPCVOID))aSyscall[41].pCurrent)
  29959. #if !SQLITE_OS_WINRT
  29960. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  29961. #else
  29962. { "HeapValidate", (SYSCALL)0, 0 },
  29963. #endif
  29964. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  29965. LPCVOID))aSyscall[42].pCurrent)
  29966. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29967. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  29968. #else
  29969. { "LoadLibraryA", (SYSCALL)0, 0 },
  29970. #endif
  29971. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent)
  29972. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29973. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29974. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  29975. #else
  29976. { "LoadLibraryW", (SYSCALL)0, 0 },
  29977. #endif
  29978. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent)
  29979. #if !SQLITE_OS_WINRT
  29980. { "LocalFree", (SYSCALL)LocalFree, 0 },
  29981. #else
  29982. { "LocalFree", (SYSCALL)0, 0 },
  29983. #endif
  29984. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent)
  29985. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29986. { "LockFile", (SYSCALL)LockFile, 0 },
  29987. #else
  29988. { "LockFile", (SYSCALL)0, 0 },
  29989. #endif
  29990. #ifndef osLockFile
  29991. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29992. DWORD))aSyscall[46].pCurrent)
  29993. #endif
  29994. #if !SQLITE_OS_WINCE
  29995. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  29996. #else
  29997. { "LockFileEx", (SYSCALL)0, 0 },
  29998. #endif
  29999. #ifndef osLockFileEx
  30000. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  30001. LPOVERLAPPED))aSyscall[47].pCurrent)
  30002. #endif
  30003. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  30004. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  30005. #else
  30006. { "MapViewOfFile", (SYSCALL)0, 0 },
  30007. #endif
  30008. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30009. SIZE_T))aSyscall[48].pCurrent)
  30010. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  30011. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  30012. int))aSyscall[49].pCurrent)
  30013. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  30014. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  30015. LARGE_INTEGER*))aSyscall[50].pCurrent)
  30016. { "ReadFile", (SYSCALL)ReadFile, 0 },
  30017. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  30018. LPOVERLAPPED))aSyscall[51].pCurrent)
  30019. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  30020. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent)
  30021. #if !SQLITE_OS_WINRT
  30022. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  30023. #else
  30024. { "SetFilePointer", (SYSCALL)0, 0 },
  30025. #endif
  30026. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  30027. DWORD))aSyscall[53].pCurrent)
  30028. #if !SQLITE_OS_WINRT
  30029. { "Sleep", (SYSCALL)Sleep, 0 },
  30030. #else
  30031. { "Sleep", (SYSCALL)0, 0 },
  30032. #endif
  30033. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent)
  30034. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  30035. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  30036. LPFILETIME))aSyscall[55].pCurrent)
  30037. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  30038. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  30039. #else
  30040. { "UnlockFile", (SYSCALL)0, 0 },
  30041. #endif
  30042. #ifndef osUnlockFile
  30043. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30044. DWORD))aSyscall[56].pCurrent)
  30045. #endif
  30046. #if !SQLITE_OS_WINCE
  30047. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  30048. #else
  30049. { "UnlockFileEx", (SYSCALL)0, 0 },
  30050. #endif
  30051. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30052. LPOVERLAPPED))aSyscall[57].pCurrent)
  30053. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  30054. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  30055. #else
  30056. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  30057. #endif
  30058. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent)
  30059. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  30060. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  30061. LPCSTR,LPBOOL))aSyscall[59].pCurrent)
  30062. { "WriteFile", (SYSCALL)WriteFile, 0 },
  30063. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  30064. LPOVERLAPPED))aSyscall[60].pCurrent)
  30065. #if SQLITE_OS_WINRT
  30066. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  30067. #else
  30068. { "CreateEventExW", (SYSCALL)0, 0 },
  30069. #endif
  30070. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  30071. DWORD,DWORD))aSyscall[61].pCurrent)
  30072. #if !SQLITE_OS_WINRT
  30073. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  30074. #else
  30075. { "WaitForSingleObject", (SYSCALL)0, 0 },
  30076. #endif
  30077. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  30078. DWORD))aSyscall[62].pCurrent)
  30079. #if SQLITE_OS_WINRT
  30080. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  30081. #else
  30082. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  30083. #endif
  30084. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  30085. BOOL))aSyscall[63].pCurrent)
  30086. #if SQLITE_OS_WINRT
  30087. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  30088. #else
  30089. { "SetFilePointerEx", (SYSCALL)0, 0 },
  30090. #endif
  30091. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  30092. PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent)
  30093. #if SQLITE_OS_WINRT
  30094. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  30095. #else
  30096. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  30097. #endif
  30098. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  30099. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent)
  30100. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  30101. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  30102. #else
  30103. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  30104. #endif
  30105. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  30106. SIZE_T))aSyscall[66].pCurrent)
  30107. #if SQLITE_OS_WINRT
  30108. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  30109. #else
  30110. { "CreateFile2", (SYSCALL)0, 0 },
  30111. #endif
  30112. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  30113. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent)
  30114. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  30115. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  30116. #else
  30117. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  30118. #endif
  30119. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  30120. DWORD))aSyscall[68].pCurrent)
  30121. #if SQLITE_OS_WINRT
  30122. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  30123. #else
  30124. { "GetTickCount64", (SYSCALL)0, 0 },
  30125. #endif
  30126. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent)
  30127. #if SQLITE_OS_WINRT
  30128. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  30129. #else
  30130. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  30131. #endif
  30132. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  30133. LPSYSTEM_INFO))aSyscall[70].pCurrent)
  30134. #if defined(SQLITE_WIN32_HAS_ANSI)
  30135. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  30136. #else
  30137. { "OutputDebugStringA", (SYSCALL)0, 0 },
  30138. #endif
  30139. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent)
  30140. #if defined(SQLITE_WIN32_HAS_WIDE)
  30141. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  30142. #else
  30143. { "OutputDebugStringW", (SYSCALL)0, 0 },
  30144. #endif
  30145. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent)
  30146. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  30147. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent)
  30148. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  30149. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  30150. #else
  30151. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  30152. #endif
  30153. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  30154. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent)
  30155. }; /* End of the overrideable system calls */
  30156. /*
  30157. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  30158. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  30159. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  30160. ** system call named zName.
  30161. */
  30162. static int winSetSystemCall(
  30163. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  30164. const char *zName, /* Name of system call to override */
  30165. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  30166. ){
  30167. unsigned int i;
  30168. int rc = SQLITE_NOTFOUND;
  30169. UNUSED_PARAMETER(pNotUsed);
  30170. if( zName==0 ){
  30171. /* If no zName is given, restore all system calls to their default
  30172. ** settings and return NULL
  30173. */
  30174. rc = SQLITE_OK;
  30175. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30176. if( aSyscall[i].pDefault ){
  30177. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  30178. }
  30179. }
  30180. }else{
  30181. /* If zName is specified, operate on only the one system call
  30182. ** specified.
  30183. */
  30184. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30185. if( strcmp(zName, aSyscall[i].zName)==0 ){
  30186. if( aSyscall[i].pDefault==0 ){
  30187. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  30188. }
  30189. rc = SQLITE_OK;
  30190. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  30191. aSyscall[i].pCurrent = pNewFunc;
  30192. break;
  30193. }
  30194. }
  30195. }
  30196. return rc;
  30197. }
  30198. /*
  30199. ** Return the value of a system call. Return NULL if zName is not a
  30200. ** recognized system call name. NULL is also returned if the system call
  30201. ** is currently undefined.
  30202. */
  30203. static sqlite3_syscall_ptr winGetSystemCall(
  30204. sqlite3_vfs *pNotUsed,
  30205. const char *zName
  30206. ){
  30207. unsigned int i;
  30208. UNUSED_PARAMETER(pNotUsed);
  30209. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30210. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  30211. }
  30212. return 0;
  30213. }
  30214. /*
  30215. ** Return the name of the first system call after zName. If zName==NULL
  30216. ** then return the name of the first system call. Return NULL if zName
  30217. ** is the last system call or if zName is not the name of a valid
  30218. ** system call.
  30219. */
  30220. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  30221. int i = -1;
  30222. UNUSED_PARAMETER(p);
  30223. if( zName ){
  30224. for(i=0; i<ArraySize(aSyscall)-1; i++){
  30225. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  30226. }
  30227. }
  30228. for(i++; i<ArraySize(aSyscall); i++){
  30229. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  30230. }
  30231. return 0;
  30232. }
  30233. /*
  30234. ** This function outputs the specified (ANSI) string to the Win32 debugger
  30235. ** (if available).
  30236. */
  30237. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  30238. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  30239. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  30240. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  30241. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  30242. #if defined(SQLITE_WIN32_HAS_ANSI)
  30243. if( nMin>0 ){
  30244. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30245. memcpy(zDbgBuf, zBuf, nMin);
  30246. osOutputDebugStringA(zDbgBuf);
  30247. }else{
  30248. osOutputDebugStringA(zBuf);
  30249. }
  30250. #elif defined(SQLITE_WIN32_HAS_WIDE)
  30251. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30252. if ( osMultiByteToWideChar(
  30253. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  30254. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  30255. return;
  30256. }
  30257. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  30258. #else
  30259. if( nMin>0 ){
  30260. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30261. memcpy(zDbgBuf, zBuf, nMin);
  30262. fprintf(stderr, "%s", zDbgBuf);
  30263. }else{
  30264. fprintf(stderr, "%s", zBuf);
  30265. }
  30266. #endif
  30267. }
  30268. /*
  30269. ** The following routine suspends the current thread for at least ms
  30270. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  30271. */
  30272. #if SQLITE_OS_WINRT
  30273. static HANDLE sleepObj = NULL;
  30274. #endif
  30275. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  30276. #if SQLITE_OS_WINRT
  30277. if ( sleepObj==NULL ){
  30278. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  30279. SYNCHRONIZE);
  30280. }
  30281. assert( sleepObj!=NULL );
  30282. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  30283. #else
  30284. osSleep(milliseconds);
  30285. #endif
  30286. }
  30287. /*
  30288. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  30289. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  30290. **
  30291. ** Here is an interesting observation: Win95, Win98, and WinME lack
  30292. ** the LockFileEx() API. But we can still statically link against that
  30293. ** API as long as we don't call it when running Win95/98/ME. A call to
  30294. ** this routine is used to determine if the host is Win95/98/ME or
  30295. ** WinNT/2K/XP so that we will know whether or not we can safely call
  30296. ** the LockFileEx() API.
  30297. */
  30298. #ifndef NTDDI_WIN8
  30299. # define NTDDI_WIN8 0x06020000
  30300. #endif
  30301. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  30302. # define osIsNT() (1)
  30303. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  30304. # define osIsNT() (0)
  30305. #else
  30306. static int osIsNT(void){
  30307. if( sqlite3_os_type==0 ){
  30308. #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
  30309. OSVERSIONINFOW sInfo;
  30310. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  30311. osGetVersionExW(&sInfo);
  30312. #else
  30313. OSVERSIONINFOA sInfo;
  30314. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  30315. osGetVersionExA(&sInfo);
  30316. #endif
  30317. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  30318. }
  30319. return sqlite3_os_type==2;
  30320. }
  30321. #endif
  30322. #ifdef SQLITE_WIN32_MALLOC
  30323. /*
  30324. ** Allocate nBytes of memory.
  30325. */
  30326. static void *winMemMalloc(int nBytes){
  30327. HANDLE hHeap;
  30328. void *p;
  30329. winMemAssertMagic();
  30330. hHeap = winMemGetHeap();
  30331. assert( hHeap!=0 );
  30332. assert( hHeap!=INVALID_HANDLE_VALUE );
  30333. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30334. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30335. #endif
  30336. assert( nBytes>=0 );
  30337. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  30338. if( !p ){
  30339. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  30340. nBytes, osGetLastError(), (void*)hHeap);
  30341. }
  30342. return p;
  30343. }
  30344. /*
  30345. ** Free memory.
  30346. */
  30347. static void winMemFree(void *pPrior){
  30348. HANDLE hHeap;
  30349. winMemAssertMagic();
  30350. hHeap = winMemGetHeap();
  30351. assert( hHeap!=0 );
  30352. assert( hHeap!=INVALID_HANDLE_VALUE );
  30353. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30354. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30355. #endif
  30356. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  30357. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  30358. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  30359. pPrior, osGetLastError(), (void*)hHeap);
  30360. }
  30361. }
  30362. /*
  30363. ** Change the size of an existing memory allocation
  30364. */
  30365. static void *winMemRealloc(void *pPrior, int nBytes){
  30366. HANDLE hHeap;
  30367. void *p;
  30368. winMemAssertMagic();
  30369. hHeap = winMemGetHeap();
  30370. assert( hHeap!=0 );
  30371. assert( hHeap!=INVALID_HANDLE_VALUE );
  30372. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30373. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30374. #endif
  30375. assert( nBytes>=0 );
  30376. if( !pPrior ){
  30377. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  30378. }else{
  30379. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  30380. }
  30381. if( !p ){
  30382. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  30383. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  30384. (void*)hHeap);
  30385. }
  30386. return p;
  30387. }
  30388. /*
  30389. ** Return the size of an outstanding allocation, in bytes.
  30390. */
  30391. static int winMemSize(void *p){
  30392. HANDLE hHeap;
  30393. SIZE_T n;
  30394. winMemAssertMagic();
  30395. hHeap = winMemGetHeap();
  30396. assert( hHeap!=0 );
  30397. assert( hHeap!=INVALID_HANDLE_VALUE );
  30398. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30399. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30400. #endif
  30401. if( !p ) return 0;
  30402. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  30403. if( n==(SIZE_T)-1 ){
  30404. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  30405. p, osGetLastError(), (void*)hHeap);
  30406. return 0;
  30407. }
  30408. return (int)n;
  30409. }
  30410. /*
  30411. ** Round up a request size to the next valid allocation size.
  30412. */
  30413. static int winMemRoundup(int n){
  30414. return n;
  30415. }
  30416. /*
  30417. ** Initialize this module.
  30418. */
  30419. static int winMemInit(void *pAppData){
  30420. winMemData *pWinMemData = (winMemData *)pAppData;
  30421. if( !pWinMemData ) return SQLITE_ERROR;
  30422. assert( pWinMemData->magic==WINMEM_MAGIC );
  30423. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  30424. if( !pWinMemData->hHeap ){
  30425. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  30426. SQLITE_WIN32_HEAP_INIT_SIZE,
  30427. SQLITE_WIN32_HEAP_MAX_SIZE);
  30428. if( !pWinMemData->hHeap ){
  30429. sqlite3_log(SQLITE_NOMEM,
  30430. "failed to HeapCreate (%lu), flags=%u, initSize=%u, maxSize=%u",
  30431. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  30432. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  30433. return SQLITE_NOMEM;
  30434. }
  30435. pWinMemData->bOwned = TRUE;
  30436. assert( pWinMemData->bOwned );
  30437. }
  30438. #else
  30439. pWinMemData->hHeap = osGetProcessHeap();
  30440. if( !pWinMemData->hHeap ){
  30441. sqlite3_log(SQLITE_NOMEM,
  30442. "failed to GetProcessHeap (%lu)", osGetLastError());
  30443. return SQLITE_NOMEM;
  30444. }
  30445. pWinMemData->bOwned = FALSE;
  30446. assert( !pWinMemData->bOwned );
  30447. #endif
  30448. assert( pWinMemData->hHeap!=0 );
  30449. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30450. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30451. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30452. #endif
  30453. return SQLITE_OK;
  30454. }
  30455. /*
  30456. ** Deinitialize this module.
  30457. */
  30458. static void winMemShutdown(void *pAppData){
  30459. winMemData *pWinMemData = (winMemData *)pAppData;
  30460. if( !pWinMemData ) return;
  30461. if( pWinMemData->hHeap ){
  30462. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30463. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30464. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30465. #endif
  30466. if( pWinMemData->bOwned ){
  30467. if( !osHeapDestroy(pWinMemData->hHeap) ){
  30468. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  30469. osGetLastError(), (void*)pWinMemData->hHeap);
  30470. }
  30471. pWinMemData->bOwned = FALSE;
  30472. }
  30473. pWinMemData->hHeap = NULL;
  30474. }
  30475. }
  30476. /*
  30477. ** Populate the low-level memory allocation function pointers in
  30478. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  30479. ** arguments specify the block of memory to manage.
  30480. **
  30481. ** This routine is only called by sqlite3_config(), and therefore
  30482. ** is not required to be threadsafe (it is not).
  30483. */
  30484. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  30485. static const sqlite3_mem_methods winMemMethods = {
  30486. winMemMalloc,
  30487. winMemFree,
  30488. winMemRealloc,
  30489. winMemSize,
  30490. winMemRoundup,
  30491. winMemInit,
  30492. winMemShutdown,
  30493. &win_mem_data
  30494. };
  30495. return &winMemMethods;
  30496. }
  30497. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  30498. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  30499. }
  30500. #endif /* SQLITE_WIN32_MALLOC */
  30501. /*
  30502. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  30503. **
  30504. ** Space to hold the returned string is obtained from malloc.
  30505. */
  30506. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  30507. int nChar;
  30508. LPWSTR zWideFilename;
  30509. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  30510. if( nChar==0 ){
  30511. return 0;
  30512. }
  30513. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  30514. if( zWideFilename==0 ){
  30515. return 0;
  30516. }
  30517. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  30518. nChar);
  30519. if( nChar==0 ){
  30520. sqlite3_free(zWideFilename);
  30521. zWideFilename = 0;
  30522. }
  30523. return zWideFilename;
  30524. }
  30525. /*
  30526. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  30527. ** obtained from sqlite3_malloc().
  30528. */
  30529. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  30530. int nByte;
  30531. char *zFilename;
  30532. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  30533. if( nByte == 0 ){
  30534. return 0;
  30535. }
  30536. zFilename = sqlite3MallocZero( nByte );
  30537. if( zFilename==0 ){
  30538. return 0;
  30539. }
  30540. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  30541. 0, 0);
  30542. if( nByte == 0 ){
  30543. sqlite3_free(zFilename);
  30544. zFilename = 0;
  30545. }
  30546. return zFilename;
  30547. }
  30548. /*
  30549. ** Convert an ANSI string to Microsoft Unicode, based on the
  30550. ** current codepage settings for file apis.
  30551. **
  30552. ** Space to hold the returned string is obtained
  30553. ** from sqlite3_malloc.
  30554. */
  30555. static LPWSTR winMbcsToUnicode(const char *zFilename){
  30556. int nByte;
  30557. LPWSTR zMbcsFilename;
  30558. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30559. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  30560. 0)*sizeof(WCHAR);
  30561. if( nByte==0 ){
  30562. return 0;
  30563. }
  30564. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  30565. if( zMbcsFilename==0 ){
  30566. return 0;
  30567. }
  30568. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  30569. nByte);
  30570. if( nByte==0 ){
  30571. sqlite3_free(zMbcsFilename);
  30572. zMbcsFilename = 0;
  30573. }
  30574. return zMbcsFilename;
  30575. }
  30576. /*
  30577. ** Convert Microsoft Unicode to multi-byte character string, based on the
  30578. ** user's ANSI codepage.
  30579. **
  30580. ** Space to hold the returned string is obtained from
  30581. ** sqlite3_malloc().
  30582. */
  30583. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  30584. int nByte;
  30585. char *zFilename;
  30586. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30587. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  30588. if( nByte == 0 ){
  30589. return 0;
  30590. }
  30591. zFilename = sqlite3MallocZero( nByte );
  30592. if( zFilename==0 ){
  30593. return 0;
  30594. }
  30595. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  30596. nByte, 0, 0);
  30597. if( nByte == 0 ){
  30598. sqlite3_free(zFilename);
  30599. zFilename = 0;
  30600. }
  30601. return zFilename;
  30602. }
  30603. /*
  30604. ** Convert multibyte character string to UTF-8. Space to hold the
  30605. ** returned string is obtained from sqlite3_malloc().
  30606. */
  30607. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  30608. char *zFilenameUtf8;
  30609. LPWSTR zTmpWide;
  30610. zTmpWide = winMbcsToUnicode(zFilename);
  30611. if( zTmpWide==0 ){
  30612. return 0;
  30613. }
  30614. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  30615. sqlite3_free(zTmpWide);
  30616. return zFilenameUtf8;
  30617. }
  30618. /*
  30619. ** Convert UTF-8 to multibyte character string. Space to hold the
  30620. ** returned string is obtained from sqlite3_malloc().
  30621. */
  30622. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  30623. char *zFilenameMbcs;
  30624. LPWSTR zTmpWide;
  30625. zTmpWide = winUtf8ToUnicode(zFilename);
  30626. if( zTmpWide==0 ){
  30627. return 0;
  30628. }
  30629. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  30630. sqlite3_free(zTmpWide);
  30631. return zFilenameMbcs;
  30632. }
  30633. /*
  30634. ** This function sets the data directory or the temporary directory based on
  30635. ** the provided arguments. The type argument must be 1 in order to set the
  30636. ** data directory or 2 in order to set the temporary directory. The zValue
  30637. ** argument is the name of the directory to use. The return value will be
  30638. ** SQLITE_OK if successful.
  30639. */
  30640. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  30641. char **ppDirectory = 0;
  30642. #ifndef SQLITE_OMIT_AUTOINIT
  30643. int rc = sqlite3_initialize();
  30644. if( rc ) return rc;
  30645. #endif
  30646. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  30647. ppDirectory = &sqlite3_data_directory;
  30648. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  30649. ppDirectory = &sqlite3_temp_directory;
  30650. }
  30651. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30652. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30653. );
  30654. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  30655. if( ppDirectory ){
  30656. char *zValueUtf8 = 0;
  30657. if( zValue && zValue[0] ){
  30658. zValueUtf8 = winUnicodeToUtf8(zValue);
  30659. if ( zValueUtf8==0 ){
  30660. return SQLITE_NOMEM;
  30661. }
  30662. }
  30663. sqlite3_free(*ppDirectory);
  30664. *ppDirectory = zValueUtf8;
  30665. return SQLITE_OK;
  30666. }
  30667. return SQLITE_ERROR;
  30668. }
  30669. /*
  30670. ** The return value of winGetLastErrorMsg
  30671. ** is zero if the error message fits in the buffer, or non-zero
  30672. ** otherwise (if the message was truncated).
  30673. */
  30674. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  30675. /* FormatMessage returns 0 on failure. Otherwise it
  30676. ** returns the number of TCHARs written to the output
  30677. ** buffer, excluding the terminating null char.
  30678. */
  30679. DWORD dwLen = 0;
  30680. char *zOut = 0;
  30681. if( osIsNT() ){
  30682. #if SQLITE_OS_WINRT
  30683. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  30684. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  30685. FORMAT_MESSAGE_IGNORE_INSERTS,
  30686. NULL,
  30687. lastErrno,
  30688. 0,
  30689. zTempWide,
  30690. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  30691. 0);
  30692. #else
  30693. LPWSTR zTempWide = NULL;
  30694. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30695. FORMAT_MESSAGE_FROM_SYSTEM |
  30696. FORMAT_MESSAGE_IGNORE_INSERTS,
  30697. NULL,
  30698. lastErrno,
  30699. 0,
  30700. (LPWSTR) &zTempWide,
  30701. 0,
  30702. 0);
  30703. #endif
  30704. if( dwLen > 0 ){
  30705. /* allocate a buffer and convert to UTF8 */
  30706. sqlite3BeginBenignMalloc();
  30707. zOut = winUnicodeToUtf8(zTempWide);
  30708. sqlite3EndBenignMalloc();
  30709. #if !SQLITE_OS_WINRT
  30710. /* free the system buffer allocated by FormatMessage */
  30711. osLocalFree(zTempWide);
  30712. #endif
  30713. }
  30714. }
  30715. #ifdef SQLITE_WIN32_HAS_ANSI
  30716. else{
  30717. char *zTemp = NULL;
  30718. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30719. FORMAT_MESSAGE_FROM_SYSTEM |
  30720. FORMAT_MESSAGE_IGNORE_INSERTS,
  30721. NULL,
  30722. lastErrno,
  30723. 0,
  30724. (LPSTR) &zTemp,
  30725. 0,
  30726. 0);
  30727. if( dwLen > 0 ){
  30728. /* allocate a buffer and convert to UTF8 */
  30729. sqlite3BeginBenignMalloc();
  30730. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  30731. sqlite3EndBenignMalloc();
  30732. /* free the system buffer allocated by FormatMessage */
  30733. osLocalFree(zTemp);
  30734. }
  30735. }
  30736. #endif
  30737. if( 0 == dwLen ){
  30738. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  30739. }else{
  30740. /* copy a maximum of nBuf chars to output buffer */
  30741. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  30742. /* free the UTF8 buffer */
  30743. sqlite3_free(zOut);
  30744. }
  30745. return 0;
  30746. }
  30747. /*
  30748. **
  30749. ** This function - winLogErrorAtLine() - is only ever called via the macro
  30750. ** winLogError().
  30751. **
  30752. ** This routine is invoked after an error occurs in an OS function.
  30753. ** It logs a message using sqlite3_log() containing the current value of
  30754. ** error code and, if possible, the human-readable equivalent from
  30755. ** FormatMessage.
  30756. **
  30757. ** The first argument passed to the macro should be the error code that
  30758. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  30759. ** The two subsequent arguments should be the name of the OS function that
  30760. ** failed and the associated file-system path, if any.
  30761. */
  30762. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  30763. static int winLogErrorAtLine(
  30764. int errcode, /* SQLite error code */
  30765. DWORD lastErrno, /* Win32 last error */
  30766. const char *zFunc, /* Name of OS function that failed */
  30767. const char *zPath, /* File path associated with error */
  30768. int iLine /* Source line number where error occurred */
  30769. ){
  30770. char zMsg[500]; /* Human readable error text */
  30771. int i; /* Loop counter */
  30772. zMsg[0] = 0;
  30773. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  30774. assert( errcode!=SQLITE_OK );
  30775. if( zPath==0 ) zPath = "";
  30776. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  30777. zMsg[i] = 0;
  30778. sqlite3_log(errcode,
  30779. "os_win.c:%d: (%lu) %s(%s) - %s",
  30780. iLine, lastErrno, zFunc, zPath, zMsg
  30781. );
  30782. return errcode;
  30783. }
  30784. /*
  30785. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  30786. ** will be retried following a locking error - probably caused by
  30787. ** antivirus software. Also the initial delay before the first retry.
  30788. ** The delay increases linearly with each retry.
  30789. */
  30790. #ifndef SQLITE_WIN32_IOERR_RETRY
  30791. # define SQLITE_WIN32_IOERR_RETRY 10
  30792. #endif
  30793. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  30794. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  30795. #endif
  30796. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  30797. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  30798. /*
  30799. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  30800. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  30801. ** to give up with an error.
  30802. */
  30803. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  30804. DWORD e = osGetLastError();
  30805. if( *pnRetry>=winIoerrRetry ){
  30806. if( pError ){
  30807. *pError = e;
  30808. }
  30809. return 0;
  30810. }
  30811. if( e==ERROR_ACCESS_DENIED ||
  30812. e==ERROR_LOCK_VIOLATION ||
  30813. e==ERROR_SHARING_VIOLATION ){
  30814. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  30815. ++*pnRetry;
  30816. return 1;
  30817. }
  30818. if( pError ){
  30819. *pError = e;
  30820. }
  30821. return 0;
  30822. }
  30823. /*
  30824. ** Log a I/O error retry episode.
  30825. */
  30826. static void winLogIoerr(int nRetry){
  30827. if( nRetry ){
  30828. sqlite3_log(SQLITE_IOERR,
  30829. "delayed %dms for lock/sharing conflict",
  30830. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  30831. );
  30832. }
  30833. }
  30834. #if SQLITE_OS_WINCE
  30835. /*************************************************************************
  30836. ** This section contains code for WinCE only.
  30837. */
  30838. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  30839. /*
  30840. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  30841. ** create a substitute.
  30842. */
  30843. /* #include <time.h> */
  30844. struct tm *__cdecl localtime(const time_t *t)
  30845. {
  30846. static struct tm y;
  30847. FILETIME uTm, lTm;
  30848. SYSTEMTIME pTm;
  30849. sqlite3_int64 t64;
  30850. t64 = *t;
  30851. t64 = (t64 + 11644473600)*10000000;
  30852. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  30853. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  30854. osFileTimeToLocalFileTime(&uTm,&lTm);
  30855. osFileTimeToSystemTime(&lTm,&pTm);
  30856. y.tm_year = pTm.wYear - 1900;
  30857. y.tm_mon = pTm.wMonth - 1;
  30858. y.tm_wday = pTm.wDayOfWeek;
  30859. y.tm_mday = pTm.wDay;
  30860. y.tm_hour = pTm.wHour;
  30861. y.tm_min = pTm.wMinute;
  30862. y.tm_sec = pTm.wSecond;
  30863. return &y;
  30864. }
  30865. #endif
  30866. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  30867. /*
  30868. ** Acquire a lock on the handle h
  30869. */
  30870. static void winceMutexAcquire(HANDLE h){
  30871. DWORD dwErr;
  30872. do {
  30873. dwErr = osWaitForSingleObject(h, INFINITE);
  30874. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  30875. }
  30876. /*
  30877. ** Release a lock acquired by winceMutexAcquire()
  30878. */
  30879. #define winceMutexRelease(h) ReleaseMutex(h)
  30880. /*
  30881. ** Create the mutex and shared memory used for locking in the file
  30882. ** descriptor pFile
  30883. */
  30884. static int winceCreateLock(const char *zFilename, winFile *pFile){
  30885. LPWSTR zTok;
  30886. LPWSTR zName;
  30887. DWORD lastErrno;
  30888. BOOL bLogged = FALSE;
  30889. BOOL bInit = TRUE;
  30890. zName = winUtf8ToUnicode(zFilename);
  30891. if( zName==0 ){
  30892. /* out of memory */
  30893. return SQLITE_IOERR_NOMEM;
  30894. }
  30895. /* Initialize the local lockdata */
  30896. memset(&pFile->local, 0, sizeof(pFile->local));
  30897. /* Replace the backslashes from the filename and lowercase it
  30898. ** to derive a mutex name. */
  30899. zTok = osCharLowerW(zName);
  30900. for (;*zTok;zTok++){
  30901. if (*zTok == '\\') *zTok = '_';
  30902. }
  30903. /* Create/open the named mutex */
  30904. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  30905. if (!pFile->hMutex){
  30906. pFile->lastErrno = osGetLastError();
  30907. sqlite3_free(zName);
  30908. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  30909. "winceCreateLock1", zFilename);
  30910. }
  30911. /* Acquire the mutex before continuing */
  30912. winceMutexAcquire(pFile->hMutex);
  30913. /* Since the names of named mutexes, semaphores, file mappings etc are
  30914. ** case-sensitive, take advantage of that by uppercasing the mutex name
  30915. ** and using that as the shared filemapping name.
  30916. */
  30917. osCharUpperW(zName);
  30918. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  30919. PAGE_READWRITE, 0, sizeof(winceLock),
  30920. zName);
  30921. /* Set a flag that indicates we're the first to create the memory so it
  30922. ** must be zero-initialized */
  30923. lastErrno = osGetLastError();
  30924. if (lastErrno == ERROR_ALREADY_EXISTS){
  30925. bInit = FALSE;
  30926. }
  30927. sqlite3_free(zName);
  30928. /* If we succeeded in making the shared memory handle, map it. */
  30929. if( pFile->hShared ){
  30930. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  30931. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  30932. /* If mapping failed, close the shared memory handle and erase it */
  30933. if( !pFile->shared ){
  30934. pFile->lastErrno = osGetLastError();
  30935. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30936. "winceCreateLock2", zFilename);
  30937. bLogged = TRUE;
  30938. osCloseHandle(pFile->hShared);
  30939. pFile->hShared = NULL;
  30940. }
  30941. }
  30942. /* If shared memory could not be created, then close the mutex and fail */
  30943. if( pFile->hShared==NULL ){
  30944. if( !bLogged ){
  30945. pFile->lastErrno = lastErrno;
  30946. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30947. "winceCreateLock3", zFilename);
  30948. bLogged = TRUE;
  30949. }
  30950. winceMutexRelease(pFile->hMutex);
  30951. osCloseHandle(pFile->hMutex);
  30952. pFile->hMutex = NULL;
  30953. return SQLITE_IOERR;
  30954. }
  30955. /* Initialize the shared memory if we're supposed to */
  30956. if( bInit ){
  30957. memset(pFile->shared, 0, sizeof(winceLock));
  30958. }
  30959. winceMutexRelease(pFile->hMutex);
  30960. return SQLITE_OK;
  30961. }
  30962. /*
  30963. ** Destroy the part of winFile that deals with wince locks
  30964. */
  30965. static void winceDestroyLock(winFile *pFile){
  30966. if (pFile->hMutex){
  30967. /* Acquire the mutex */
  30968. winceMutexAcquire(pFile->hMutex);
  30969. /* The following blocks should probably assert in debug mode, but they
  30970. are to cleanup in case any locks remained open */
  30971. if (pFile->local.nReaders){
  30972. pFile->shared->nReaders --;
  30973. }
  30974. if (pFile->local.bReserved){
  30975. pFile->shared->bReserved = FALSE;
  30976. }
  30977. if (pFile->local.bPending){
  30978. pFile->shared->bPending = FALSE;
  30979. }
  30980. if (pFile->local.bExclusive){
  30981. pFile->shared->bExclusive = FALSE;
  30982. }
  30983. /* De-reference and close our copy of the shared memory handle */
  30984. osUnmapViewOfFile(pFile->shared);
  30985. osCloseHandle(pFile->hShared);
  30986. /* Done with the mutex */
  30987. winceMutexRelease(pFile->hMutex);
  30988. osCloseHandle(pFile->hMutex);
  30989. pFile->hMutex = NULL;
  30990. }
  30991. }
  30992. /*
  30993. ** An implementation of the LockFile() API of Windows for CE
  30994. */
  30995. static BOOL winceLockFile(
  30996. LPHANDLE phFile,
  30997. DWORD dwFileOffsetLow,
  30998. DWORD dwFileOffsetHigh,
  30999. DWORD nNumberOfBytesToLockLow,
  31000. DWORD nNumberOfBytesToLockHigh
  31001. ){
  31002. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  31003. BOOL bReturn = FALSE;
  31004. UNUSED_PARAMETER(dwFileOffsetHigh);
  31005. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  31006. if (!pFile->hMutex) return TRUE;
  31007. winceMutexAcquire(pFile->hMutex);
  31008. /* Wanting an exclusive lock? */
  31009. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  31010. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  31011. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  31012. pFile->shared->bExclusive = TRUE;
  31013. pFile->local.bExclusive = TRUE;
  31014. bReturn = TRUE;
  31015. }
  31016. }
  31017. /* Want a read-only lock? */
  31018. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  31019. nNumberOfBytesToLockLow == 1){
  31020. if (pFile->shared->bExclusive == 0){
  31021. pFile->local.nReaders ++;
  31022. if (pFile->local.nReaders == 1){
  31023. pFile->shared->nReaders ++;
  31024. }
  31025. bReturn = TRUE;
  31026. }
  31027. }
  31028. /* Want a pending lock? */
  31029. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  31030. && nNumberOfBytesToLockLow == 1){
  31031. /* If no pending lock has been acquired, then acquire it */
  31032. if (pFile->shared->bPending == 0) {
  31033. pFile->shared->bPending = TRUE;
  31034. pFile->local.bPending = TRUE;
  31035. bReturn = TRUE;
  31036. }
  31037. }
  31038. /* Want a reserved lock? */
  31039. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  31040. && nNumberOfBytesToLockLow == 1){
  31041. if (pFile->shared->bReserved == 0) {
  31042. pFile->shared->bReserved = TRUE;
  31043. pFile->local.bReserved = TRUE;
  31044. bReturn = TRUE;
  31045. }
  31046. }
  31047. winceMutexRelease(pFile->hMutex);
  31048. return bReturn;
  31049. }
  31050. /*
  31051. ** An implementation of the UnlockFile API of Windows for CE
  31052. */
  31053. static BOOL winceUnlockFile(
  31054. LPHANDLE phFile,
  31055. DWORD dwFileOffsetLow,
  31056. DWORD dwFileOffsetHigh,
  31057. DWORD nNumberOfBytesToUnlockLow,
  31058. DWORD nNumberOfBytesToUnlockHigh
  31059. ){
  31060. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  31061. BOOL bReturn = FALSE;
  31062. UNUSED_PARAMETER(dwFileOffsetHigh);
  31063. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  31064. if (!pFile->hMutex) return TRUE;
  31065. winceMutexAcquire(pFile->hMutex);
  31066. /* Releasing a reader lock or an exclusive lock */
  31067. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  31068. /* Did we have an exclusive lock? */
  31069. if (pFile->local.bExclusive){
  31070. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  31071. pFile->local.bExclusive = FALSE;
  31072. pFile->shared->bExclusive = FALSE;
  31073. bReturn = TRUE;
  31074. }
  31075. /* Did we just have a reader lock? */
  31076. else if (pFile->local.nReaders){
  31077. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  31078. || nNumberOfBytesToUnlockLow == 1);
  31079. pFile->local.nReaders --;
  31080. if (pFile->local.nReaders == 0)
  31081. {
  31082. pFile->shared->nReaders --;
  31083. }
  31084. bReturn = TRUE;
  31085. }
  31086. }
  31087. /* Releasing a pending lock */
  31088. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  31089. && nNumberOfBytesToUnlockLow == 1){
  31090. if (pFile->local.bPending){
  31091. pFile->local.bPending = FALSE;
  31092. pFile->shared->bPending = FALSE;
  31093. bReturn = TRUE;
  31094. }
  31095. }
  31096. /* Releasing a reserved lock */
  31097. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  31098. && nNumberOfBytesToUnlockLow == 1){
  31099. if (pFile->local.bReserved) {
  31100. pFile->local.bReserved = FALSE;
  31101. pFile->shared->bReserved = FALSE;
  31102. bReturn = TRUE;
  31103. }
  31104. }
  31105. winceMutexRelease(pFile->hMutex);
  31106. return bReturn;
  31107. }
  31108. /*
  31109. ** End of the special code for wince
  31110. *****************************************************************************/
  31111. #endif /* SQLITE_OS_WINCE */
  31112. /*
  31113. ** Lock a file region.
  31114. */
  31115. static BOOL winLockFile(
  31116. LPHANDLE phFile,
  31117. DWORD flags,
  31118. DWORD offsetLow,
  31119. DWORD offsetHigh,
  31120. DWORD numBytesLow,
  31121. DWORD numBytesHigh
  31122. ){
  31123. #if SQLITE_OS_WINCE
  31124. /*
  31125. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31126. ** API LockFile.
  31127. */
  31128. return winceLockFile(phFile, offsetLow, offsetHigh,
  31129. numBytesLow, numBytesHigh);
  31130. #else
  31131. if( osIsNT() ){
  31132. OVERLAPPED ovlp;
  31133. memset(&ovlp, 0, sizeof(OVERLAPPED));
  31134. ovlp.Offset = offsetLow;
  31135. ovlp.OffsetHigh = offsetHigh;
  31136. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  31137. }else{
  31138. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  31139. numBytesHigh);
  31140. }
  31141. #endif
  31142. }
  31143. /*
  31144. ** Unlock a file region.
  31145. */
  31146. static BOOL winUnlockFile(
  31147. LPHANDLE phFile,
  31148. DWORD offsetLow,
  31149. DWORD offsetHigh,
  31150. DWORD numBytesLow,
  31151. DWORD numBytesHigh
  31152. ){
  31153. #if SQLITE_OS_WINCE
  31154. /*
  31155. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31156. ** API UnlockFile.
  31157. */
  31158. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  31159. numBytesLow, numBytesHigh);
  31160. #else
  31161. if( osIsNT() ){
  31162. OVERLAPPED ovlp;
  31163. memset(&ovlp, 0, sizeof(OVERLAPPED));
  31164. ovlp.Offset = offsetLow;
  31165. ovlp.OffsetHigh = offsetHigh;
  31166. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  31167. }else{
  31168. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  31169. numBytesHigh);
  31170. }
  31171. #endif
  31172. }
  31173. /*****************************************************************************
  31174. ** The next group of routines implement the I/O methods specified
  31175. ** by the sqlite3_io_methods object.
  31176. ******************************************************************************/
  31177. /*
  31178. ** Some Microsoft compilers lack this definition.
  31179. */
  31180. #ifndef INVALID_SET_FILE_POINTER
  31181. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  31182. #endif
  31183. /*
  31184. ** Move the current position of the file handle passed as the first
  31185. ** argument to offset iOffset within the file. If successful, return 0.
  31186. ** Otherwise, set pFile->lastErrno and return non-zero.
  31187. */
  31188. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  31189. #if !SQLITE_OS_WINRT
  31190. LONG upperBits; /* Most sig. 32 bits of new offset */
  31191. LONG lowerBits; /* Least sig. 32 bits of new offset */
  31192. DWORD dwRet; /* Value returned by SetFilePointer() */
  31193. DWORD lastErrno; /* Value returned by GetLastError() */
  31194. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  31195. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  31196. lowerBits = (LONG)(iOffset & 0xffffffff);
  31197. /* API oddity: If successful, SetFilePointer() returns a dword
  31198. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  31199. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  31200. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  31201. ** whether an error has actually occurred, it is also necessary to call
  31202. ** GetLastError().
  31203. */
  31204. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  31205. if( (dwRet==INVALID_SET_FILE_POINTER
  31206. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  31207. pFile->lastErrno = lastErrno;
  31208. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  31209. "winSeekFile", pFile->zPath);
  31210. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  31211. return 1;
  31212. }
  31213. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  31214. return 0;
  31215. #else
  31216. /*
  31217. ** Same as above, except that this implementation works for WinRT.
  31218. */
  31219. LARGE_INTEGER x; /* The new offset */
  31220. BOOL bRet; /* Value returned by SetFilePointerEx() */
  31221. x.QuadPart = iOffset;
  31222. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  31223. if(!bRet){
  31224. pFile->lastErrno = osGetLastError();
  31225. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  31226. "winSeekFile", pFile->zPath);
  31227. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  31228. return 1;
  31229. }
  31230. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  31231. return 0;
  31232. #endif
  31233. }
  31234. #if SQLITE_MAX_MMAP_SIZE>0
  31235. /* Forward references to VFS helper methods used for memory mapped files */
  31236. static int winMapfile(winFile*, sqlite3_int64);
  31237. static int winUnmapfile(winFile*);
  31238. #endif
  31239. /*
  31240. ** Close a file.
  31241. **
  31242. ** It is reported that an attempt to close a handle might sometimes
  31243. ** fail. This is a very unreasonable result, but Windows is notorious
  31244. ** for being unreasonable so I do not doubt that it might happen. If
  31245. ** the close fails, we pause for 100 milliseconds and try again. As
  31246. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  31247. ** giving up and returning an error.
  31248. */
  31249. #define MX_CLOSE_ATTEMPT 3
  31250. static int winClose(sqlite3_file *id){
  31251. int rc, cnt = 0;
  31252. winFile *pFile = (winFile*)id;
  31253. assert( id!=0 );
  31254. #ifndef SQLITE_OMIT_WAL
  31255. assert( pFile->pShm==0 );
  31256. #endif
  31257. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  31258. OSTRACE(("CLOSE file=%p\n", pFile->h));
  31259. #if SQLITE_MAX_MMAP_SIZE>0
  31260. winUnmapfile(pFile);
  31261. #endif
  31262. do{
  31263. rc = osCloseHandle(pFile->h);
  31264. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  31265. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  31266. #if SQLITE_OS_WINCE
  31267. #define WINCE_DELETION_ATTEMPTS 3
  31268. winceDestroyLock(pFile);
  31269. if( pFile->zDeleteOnClose ){
  31270. int cnt = 0;
  31271. while(
  31272. osDeleteFileW(pFile->zDeleteOnClose)==0
  31273. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  31274. && cnt++ < WINCE_DELETION_ATTEMPTS
  31275. ){
  31276. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  31277. }
  31278. sqlite3_free(pFile->zDeleteOnClose);
  31279. }
  31280. #endif
  31281. if( rc ){
  31282. pFile->h = NULL;
  31283. }
  31284. OpenCounter(-1);
  31285. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  31286. return rc ? SQLITE_OK
  31287. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  31288. "winClose", pFile->zPath);
  31289. }
  31290. /*
  31291. ** Read data from a file into a buffer. Return SQLITE_OK if all
  31292. ** bytes were read successfully and SQLITE_IOERR if anything goes
  31293. ** wrong.
  31294. */
  31295. static int winRead(
  31296. sqlite3_file *id, /* File to read from */
  31297. void *pBuf, /* Write content into this buffer */
  31298. int amt, /* Number of bytes to read */
  31299. sqlite3_int64 offset /* Begin reading at this offset */
  31300. ){
  31301. #if !SQLITE_OS_WINCE
  31302. OVERLAPPED overlapped; /* The offset for ReadFile. */
  31303. #endif
  31304. winFile *pFile = (winFile*)id; /* file handle */
  31305. DWORD nRead; /* Number of bytes actually read from file */
  31306. int nRetry = 0; /* Number of retrys */
  31307. assert( id!=0 );
  31308. assert( amt>0 );
  31309. assert( offset>=0 );
  31310. SimulateIOError(return SQLITE_IOERR_READ);
  31311. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  31312. pFile->h, pBuf, amt, offset, pFile->locktype));
  31313. #if SQLITE_MAX_MMAP_SIZE>0
  31314. /* Deal with as much of this read request as possible by transfering
  31315. ** data from the memory mapping using memcpy(). */
  31316. if( offset<pFile->mmapSize ){
  31317. if( offset+amt <= pFile->mmapSize ){
  31318. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  31319. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  31320. return SQLITE_OK;
  31321. }else{
  31322. int nCopy = (int)(pFile->mmapSize - offset);
  31323. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  31324. pBuf = &((u8 *)pBuf)[nCopy];
  31325. amt -= nCopy;
  31326. offset += nCopy;
  31327. }
  31328. }
  31329. #endif
  31330. #if SQLITE_OS_WINCE
  31331. if( winSeekFile(pFile, offset) ){
  31332. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  31333. return SQLITE_FULL;
  31334. }
  31335. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  31336. #else
  31337. memset(&overlapped, 0, sizeof(OVERLAPPED));
  31338. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31339. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31340. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  31341. osGetLastError()!=ERROR_HANDLE_EOF ){
  31342. #endif
  31343. DWORD lastErrno;
  31344. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  31345. pFile->lastErrno = lastErrno;
  31346. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  31347. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  31348. "winRead", pFile->zPath);
  31349. }
  31350. winLogIoerr(nRetry);
  31351. if( nRead<(DWORD)amt ){
  31352. /* Unread parts of the buffer must be zero-filled */
  31353. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  31354. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  31355. return SQLITE_IOERR_SHORT_READ;
  31356. }
  31357. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  31358. return SQLITE_OK;
  31359. }
  31360. /*
  31361. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31362. ** or some other error code on failure.
  31363. */
  31364. static int winWrite(
  31365. sqlite3_file *id, /* File to write into */
  31366. const void *pBuf, /* The bytes to be written */
  31367. int amt, /* Number of bytes to write */
  31368. sqlite3_int64 offset /* Offset into the file to begin writing at */
  31369. ){
  31370. int rc = 0; /* True if error has occurred, else false */
  31371. winFile *pFile = (winFile*)id; /* File handle */
  31372. int nRetry = 0; /* Number of retries */
  31373. assert( amt>0 );
  31374. assert( pFile );
  31375. SimulateIOError(return SQLITE_IOERR_WRITE);
  31376. SimulateDiskfullError(return SQLITE_FULL);
  31377. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  31378. pFile->h, pBuf, amt, offset, pFile->locktype));
  31379. #if SQLITE_MAX_MMAP_SIZE>0
  31380. /* Deal with as much of this write request as possible by transfering
  31381. ** data from the memory mapping using memcpy(). */
  31382. if( offset<pFile->mmapSize ){
  31383. if( offset+amt <= pFile->mmapSize ){
  31384. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31385. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  31386. return SQLITE_OK;
  31387. }else{
  31388. int nCopy = (int)(pFile->mmapSize - offset);
  31389. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31390. pBuf = &((u8 *)pBuf)[nCopy];
  31391. amt -= nCopy;
  31392. offset += nCopy;
  31393. }
  31394. }
  31395. #endif
  31396. #if SQLITE_OS_WINCE
  31397. rc = winSeekFile(pFile, offset);
  31398. if( rc==0 ){
  31399. #else
  31400. {
  31401. #endif
  31402. #if !SQLITE_OS_WINCE
  31403. OVERLAPPED overlapped; /* The offset for WriteFile. */
  31404. #endif
  31405. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  31406. int nRem = amt; /* Number of bytes yet to be written */
  31407. DWORD nWrite; /* Bytes written by each WriteFile() call */
  31408. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  31409. #if !SQLITE_OS_WINCE
  31410. memset(&overlapped, 0, sizeof(OVERLAPPED));
  31411. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31412. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31413. #endif
  31414. while( nRem>0 ){
  31415. #if SQLITE_OS_WINCE
  31416. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  31417. #else
  31418. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  31419. #endif
  31420. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  31421. break;
  31422. }
  31423. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  31424. if( nWrite==0 || nWrite>(DWORD)nRem ){
  31425. lastErrno = osGetLastError();
  31426. break;
  31427. }
  31428. #if !SQLITE_OS_WINCE
  31429. offset += nWrite;
  31430. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31431. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31432. #endif
  31433. aRem += nWrite;
  31434. nRem -= nWrite;
  31435. }
  31436. if( nRem>0 ){
  31437. pFile->lastErrno = lastErrno;
  31438. rc = 1;
  31439. }
  31440. }
  31441. if( rc ){
  31442. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  31443. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  31444. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  31445. return winLogError(SQLITE_FULL, pFile->lastErrno,
  31446. "winWrite1", pFile->zPath);
  31447. }
  31448. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  31449. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  31450. "winWrite2", pFile->zPath);
  31451. }else{
  31452. winLogIoerr(nRetry);
  31453. }
  31454. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  31455. return SQLITE_OK;
  31456. }
  31457. /*
  31458. ** Truncate an open file to a specified size
  31459. */
  31460. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  31461. winFile *pFile = (winFile*)id; /* File handle object */
  31462. int rc = SQLITE_OK; /* Return code for this function */
  31463. DWORD lastErrno;
  31464. assert( pFile );
  31465. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  31466. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  31467. pFile->h, nByte, pFile->locktype));
  31468. /* If the user has configured a chunk-size for this file, truncate the
  31469. ** file so that it consists of an integer number of chunks (i.e. the
  31470. ** actual file size after the operation may be larger than the requested
  31471. ** size).
  31472. */
  31473. if( pFile->szChunk>0 ){
  31474. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  31475. }
  31476. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  31477. if( winSeekFile(pFile, nByte) ){
  31478. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31479. "winTruncate1", pFile->zPath);
  31480. }else if( 0==osSetEndOfFile(pFile->h) &&
  31481. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  31482. pFile->lastErrno = lastErrno;
  31483. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31484. "winTruncate2", pFile->zPath);
  31485. }
  31486. #if SQLITE_MAX_MMAP_SIZE>0
  31487. /* If the file was truncated to a size smaller than the currently
  31488. ** mapped region, reduce the effective mapping size as well. SQLite will
  31489. ** use read() and write() to access data beyond this point from now on.
  31490. */
  31491. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  31492. pFile->mmapSize = nByte;
  31493. }
  31494. #endif
  31495. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31496. return rc;
  31497. }
  31498. #ifdef SQLITE_TEST
  31499. /*
  31500. ** Count the number of fullsyncs and normal syncs. This is used to test
  31501. ** that syncs and fullsyncs are occuring at the right times.
  31502. */
  31503. SQLITE_API int sqlite3_sync_count = 0;
  31504. SQLITE_API int sqlite3_fullsync_count = 0;
  31505. #endif
  31506. /*
  31507. ** Make sure all writes to a particular file are committed to disk.
  31508. */
  31509. static int winSync(sqlite3_file *id, int flags){
  31510. #ifndef SQLITE_NO_SYNC
  31511. /*
  31512. ** Used only when SQLITE_NO_SYNC is not defined.
  31513. */
  31514. BOOL rc;
  31515. #endif
  31516. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  31517. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  31518. /*
  31519. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  31520. ** OSTRACE() macros.
  31521. */
  31522. winFile *pFile = (winFile*)id;
  31523. #else
  31524. UNUSED_PARAMETER(id);
  31525. #endif
  31526. assert( pFile );
  31527. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  31528. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31529. || (flags&0x0F)==SQLITE_SYNC_FULL
  31530. );
  31531. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31532. ** line is to test that doing so does not cause any problems.
  31533. */
  31534. SimulateDiskfullError( return SQLITE_FULL );
  31535. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  31536. pFile->h, flags, pFile->locktype));
  31537. #ifndef SQLITE_TEST
  31538. UNUSED_PARAMETER(flags);
  31539. #else
  31540. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  31541. sqlite3_fullsync_count++;
  31542. }
  31543. sqlite3_sync_count++;
  31544. #endif
  31545. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31546. ** no-op
  31547. */
  31548. #ifdef SQLITE_NO_SYNC
  31549. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  31550. return SQLITE_OK;
  31551. #else
  31552. rc = osFlushFileBuffers(pFile->h);
  31553. SimulateIOError( rc=FALSE );
  31554. if( rc ){
  31555. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  31556. return SQLITE_OK;
  31557. }else{
  31558. pFile->lastErrno = osGetLastError();
  31559. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  31560. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  31561. "winSync", pFile->zPath);
  31562. }
  31563. #endif
  31564. }
  31565. /*
  31566. ** Determine the current size of a file in bytes
  31567. */
  31568. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  31569. winFile *pFile = (winFile*)id;
  31570. int rc = SQLITE_OK;
  31571. assert( id!=0 );
  31572. assert( pSize!=0 );
  31573. SimulateIOError(return SQLITE_IOERR_FSTAT);
  31574. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  31575. #if SQLITE_OS_WINRT
  31576. {
  31577. FILE_STANDARD_INFO info;
  31578. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  31579. &info, sizeof(info)) ){
  31580. *pSize = info.EndOfFile.QuadPart;
  31581. }else{
  31582. pFile->lastErrno = osGetLastError();
  31583. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31584. "winFileSize", pFile->zPath);
  31585. }
  31586. }
  31587. #else
  31588. {
  31589. DWORD upperBits;
  31590. DWORD lowerBits;
  31591. DWORD lastErrno;
  31592. lowerBits = osGetFileSize(pFile->h, &upperBits);
  31593. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  31594. if( (lowerBits == INVALID_FILE_SIZE)
  31595. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  31596. pFile->lastErrno = lastErrno;
  31597. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31598. "winFileSize", pFile->zPath);
  31599. }
  31600. }
  31601. #endif
  31602. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  31603. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  31604. return rc;
  31605. }
  31606. /*
  31607. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  31608. */
  31609. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  31610. # define LOCKFILE_FAIL_IMMEDIATELY 1
  31611. #endif
  31612. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  31613. # define LOCKFILE_EXCLUSIVE_LOCK 2
  31614. #endif
  31615. /*
  31616. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  31617. ** When the LockFile function was used, it was always expected to fail
  31618. ** immediately if the lock could not be obtained. Also, it always expected to
  31619. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  31620. ** and reflect those expectations; therefore, they should not be changed.
  31621. */
  31622. #ifndef SQLITE_LOCKFILE_FLAGS
  31623. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  31624. LOCKFILE_EXCLUSIVE_LOCK)
  31625. #endif
  31626. /*
  31627. ** Currently, SQLite never calls the LockFileEx function without wanting the
  31628. ** call to fail immediately if the lock cannot be obtained.
  31629. */
  31630. #ifndef SQLITE_LOCKFILEEX_FLAGS
  31631. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  31632. #endif
  31633. /*
  31634. ** Acquire a reader lock.
  31635. ** Different API routines are called depending on whether or not this
  31636. ** is Win9x or WinNT.
  31637. */
  31638. static int winGetReadLock(winFile *pFile){
  31639. int res;
  31640. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31641. if( osIsNT() ){
  31642. #if SQLITE_OS_WINCE
  31643. /*
  31644. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31645. ** API LockFileEx.
  31646. */
  31647. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  31648. #else
  31649. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  31650. SHARED_SIZE, 0);
  31651. #endif
  31652. }
  31653. #ifdef SQLITE_WIN32_HAS_ANSI
  31654. else{
  31655. int lk;
  31656. sqlite3_randomness(sizeof(lk), &lk);
  31657. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  31658. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31659. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31660. }
  31661. #endif
  31662. if( res == 0 ){
  31663. pFile->lastErrno = osGetLastError();
  31664. /* No need to log a failure to lock */
  31665. }
  31666. OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31667. return res;
  31668. }
  31669. /*
  31670. ** Undo a readlock
  31671. */
  31672. static int winUnlockReadLock(winFile *pFile){
  31673. int res;
  31674. DWORD lastErrno;
  31675. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31676. if( osIsNT() ){
  31677. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31678. }
  31679. #ifdef SQLITE_WIN32_HAS_ANSI
  31680. else{
  31681. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31682. }
  31683. #endif
  31684. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  31685. pFile->lastErrno = lastErrno;
  31686. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  31687. "winUnlockReadLock", pFile->zPath);
  31688. }
  31689. OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31690. return res;
  31691. }
  31692. /*
  31693. ** Lock the file with the lock specified by parameter locktype - one
  31694. ** of the following:
  31695. **
  31696. ** (1) SHARED_LOCK
  31697. ** (2) RESERVED_LOCK
  31698. ** (3) PENDING_LOCK
  31699. ** (4) EXCLUSIVE_LOCK
  31700. **
  31701. ** Sometimes when requesting one lock state, additional lock states
  31702. ** are inserted in between. The locking might fail on one of the later
  31703. ** transitions leaving the lock state different from what it started but
  31704. ** still short of its goal. The following chart shows the allowed
  31705. ** transitions and the inserted intermediate states:
  31706. **
  31707. ** UNLOCKED -> SHARED
  31708. ** SHARED -> RESERVED
  31709. ** SHARED -> (PENDING) -> EXCLUSIVE
  31710. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31711. ** PENDING -> EXCLUSIVE
  31712. **
  31713. ** This routine will only increase a lock. The winUnlock() routine
  31714. ** erases all locks at once and returns us immediately to locking level 0.
  31715. ** It is not possible to lower the locking level one step at a time. You
  31716. ** must go straight to locking level 0.
  31717. */
  31718. static int winLock(sqlite3_file *id, int locktype){
  31719. int rc = SQLITE_OK; /* Return code from subroutines */
  31720. int res = 1; /* Result of a Windows lock call */
  31721. int newLocktype; /* Set pFile->locktype to this value before exiting */
  31722. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  31723. winFile *pFile = (winFile*)id;
  31724. DWORD lastErrno = NO_ERROR;
  31725. assert( id!=0 );
  31726. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31727. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31728. /* If there is already a lock of this type or more restrictive on the
  31729. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  31730. ** sqlite3OsEnterMutex() hasn't been called yet.
  31731. */
  31732. if( pFile->locktype>=locktype ){
  31733. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  31734. return SQLITE_OK;
  31735. }
  31736. /* Make sure the locking sequence is correct
  31737. */
  31738. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  31739. assert( locktype!=PENDING_LOCK );
  31740. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  31741. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  31742. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  31743. ** the PENDING_LOCK byte is temporary.
  31744. */
  31745. newLocktype = pFile->locktype;
  31746. if( (pFile->locktype==NO_LOCK)
  31747. || ( (locktype==EXCLUSIVE_LOCK)
  31748. && (pFile->locktype==RESERVED_LOCK))
  31749. ){
  31750. int cnt = 3;
  31751. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31752. PENDING_BYTE, 0, 1, 0))==0 ){
  31753. /* Try 3 times to get the pending lock. This is needed to work
  31754. ** around problems caused by indexing and/or anti-virus software on
  31755. ** Windows systems.
  31756. ** If you are using this code as a model for alternative VFSes, do not
  31757. ** copy this retry logic. It is a hack intended for Windows only.
  31758. */
  31759. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
  31760. pFile->h, cnt, sqlite3ErrName(res)));
  31761. if( cnt ) sqlite3_win32_sleep(1);
  31762. }
  31763. gotPendingLock = res;
  31764. if( !res ){
  31765. lastErrno = osGetLastError();
  31766. }
  31767. }
  31768. /* Acquire a shared lock
  31769. */
  31770. if( locktype==SHARED_LOCK && res ){
  31771. assert( pFile->locktype==NO_LOCK );
  31772. res = winGetReadLock(pFile);
  31773. if( res ){
  31774. newLocktype = SHARED_LOCK;
  31775. }else{
  31776. lastErrno = osGetLastError();
  31777. }
  31778. }
  31779. /* Acquire a RESERVED lock
  31780. */
  31781. if( locktype==RESERVED_LOCK && res ){
  31782. assert( pFile->locktype==SHARED_LOCK );
  31783. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  31784. if( res ){
  31785. newLocktype = RESERVED_LOCK;
  31786. }else{
  31787. lastErrno = osGetLastError();
  31788. }
  31789. }
  31790. /* Acquire a PENDING lock
  31791. */
  31792. if( locktype==EXCLUSIVE_LOCK && res ){
  31793. newLocktype = PENDING_LOCK;
  31794. gotPendingLock = 0;
  31795. }
  31796. /* Acquire an EXCLUSIVE lock
  31797. */
  31798. if( locktype==EXCLUSIVE_LOCK && res ){
  31799. assert( pFile->locktype>=SHARED_LOCK );
  31800. res = winUnlockReadLock(pFile);
  31801. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  31802. SHARED_SIZE, 0);
  31803. if( res ){
  31804. newLocktype = EXCLUSIVE_LOCK;
  31805. }else{
  31806. lastErrno = osGetLastError();
  31807. winGetReadLock(pFile);
  31808. }
  31809. }
  31810. /* If we are holding a PENDING lock that ought to be released, then
  31811. ** release it now.
  31812. */
  31813. if( gotPendingLock && locktype==SHARED_LOCK ){
  31814. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31815. }
  31816. /* Update the state of the lock has held in the file descriptor then
  31817. ** return the appropriate result code.
  31818. */
  31819. if( res ){
  31820. rc = SQLITE_OK;
  31821. }else{
  31822. pFile->lastErrno = lastErrno;
  31823. rc = SQLITE_BUSY;
  31824. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  31825. pFile->h, locktype, newLocktype));
  31826. }
  31827. pFile->locktype = (u8)newLocktype;
  31828. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  31829. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31830. return rc;
  31831. }
  31832. /*
  31833. ** This routine checks if there is a RESERVED lock held on the specified
  31834. ** file by this or any other process. If such a lock is held, return
  31835. ** non-zero, otherwise zero.
  31836. */
  31837. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  31838. int rc;
  31839. winFile *pFile = (winFile*)id;
  31840. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31841. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  31842. assert( id!=0 );
  31843. if( pFile->locktype>=RESERVED_LOCK ){
  31844. rc = 1;
  31845. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
  31846. }else{
  31847. rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  31848. if( rc ){
  31849. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31850. }
  31851. rc = !rc;
  31852. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
  31853. }
  31854. *pResOut = rc;
  31855. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  31856. pFile->h, pResOut, *pResOut));
  31857. return SQLITE_OK;
  31858. }
  31859. /*
  31860. ** Lower the locking level on file descriptor id to locktype. locktype
  31861. ** must be either NO_LOCK or SHARED_LOCK.
  31862. **
  31863. ** If the locking level of the file descriptor is already at or below
  31864. ** the requested locking level, this routine is a no-op.
  31865. **
  31866. ** It is not possible for this routine to fail if the second argument
  31867. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  31868. ** might return SQLITE_IOERR;
  31869. */
  31870. static int winUnlock(sqlite3_file *id, int locktype){
  31871. int type;
  31872. winFile *pFile = (winFile*)id;
  31873. int rc = SQLITE_OK;
  31874. assert( pFile!=0 );
  31875. assert( locktype<=SHARED_LOCK );
  31876. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31877. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31878. type = pFile->locktype;
  31879. if( type>=EXCLUSIVE_LOCK ){
  31880. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31881. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  31882. /* This should never happen. We should always be able to
  31883. ** reacquire the read lock */
  31884. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  31885. "winUnlock", pFile->zPath);
  31886. }
  31887. }
  31888. if( type>=RESERVED_LOCK ){
  31889. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31890. }
  31891. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  31892. winUnlockReadLock(pFile);
  31893. }
  31894. if( type>=PENDING_LOCK ){
  31895. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31896. }
  31897. pFile->locktype = (u8)locktype;
  31898. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  31899. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31900. return rc;
  31901. }
  31902. /*
  31903. ** If *pArg is inititially negative then this is a query. Set *pArg to
  31904. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31905. **
  31906. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31907. */
  31908. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  31909. if( *pArg<0 ){
  31910. *pArg = (pFile->ctrlFlags & mask)!=0;
  31911. }else if( (*pArg)==0 ){
  31912. pFile->ctrlFlags &= ~mask;
  31913. }else{
  31914. pFile->ctrlFlags |= mask;
  31915. }
  31916. }
  31917. /* Forward references to VFS helper methods used for temporary files */
  31918. static int winGetTempname(sqlite3_vfs *, char **);
  31919. static int winIsDir(const void *);
  31920. static BOOL winIsDriveLetterAndColon(const char *);
  31921. /*
  31922. ** Control and query of the open file handle.
  31923. */
  31924. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  31925. winFile *pFile = (winFile*)id;
  31926. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  31927. switch( op ){
  31928. case SQLITE_FCNTL_LOCKSTATE: {
  31929. *(int*)pArg = pFile->locktype;
  31930. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31931. return SQLITE_OK;
  31932. }
  31933. case SQLITE_LAST_ERRNO: {
  31934. *(int*)pArg = (int)pFile->lastErrno;
  31935. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31936. return SQLITE_OK;
  31937. }
  31938. case SQLITE_FCNTL_CHUNK_SIZE: {
  31939. pFile->szChunk = *(int *)pArg;
  31940. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31941. return SQLITE_OK;
  31942. }
  31943. case SQLITE_FCNTL_SIZE_HINT: {
  31944. if( pFile->szChunk>0 ){
  31945. sqlite3_int64 oldSz;
  31946. int rc = winFileSize(id, &oldSz);
  31947. if( rc==SQLITE_OK ){
  31948. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  31949. if( newSz>oldSz ){
  31950. SimulateIOErrorBenign(1);
  31951. rc = winTruncate(id, newSz);
  31952. SimulateIOErrorBenign(0);
  31953. }
  31954. }
  31955. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31956. return rc;
  31957. }
  31958. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31959. return SQLITE_OK;
  31960. }
  31961. case SQLITE_FCNTL_PERSIST_WAL: {
  31962. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  31963. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31964. return SQLITE_OK;
  31965. }
  31966. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31967. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  31968. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31969. return SQLITE_OK;
  31970. }
  31971. case SQLITE_FCNTL_VFSNAME: {
  31972. *(char**)pArg = sqlite3_mprintf("win32");
  31973. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31974. return SQLITE_OK;
  31975. }
  31976. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  31977. int *a = (int*)pArg;
  31978. if( a[0]>0 ){
  31979. winIoerrRetry = a[0];
  31980. }else{
  31981. a[0] = winIoerrRetry;
  31982. }
  31983. if( a[1]>0 ){
  31984. winIoerrRetryDelay = a[1];
  31985. }else{
  31986. a[1] = winIoerrRetryDelay;
  31987. }
  31988. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31989. return SQLITE_OK;
  31990. }
  31991. case SQLITE_FCNTL_TEMPFILENAME: {
  31992. char *zTFile = 0;
  31993. int rc = winGetTempname(pFile->pVfs, &zTFile);
  31994. if( rc==SQLITE_OK ){
  31995. *(char**)pArg = zTFile;
  31996. }
  31997. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31998. return rc;
  31999. }
  32000. #if SQLITE_MAX_MMAP_SIZE>0
  32001. case SQLITE_FCNTL_MMAP_SIZE: {
  32002. i64 newLimit = *(i64*)pArg;
  32003. int rc = SQLITE_OK;
  32004. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  32005. newLimit = sqlite3GlobalConfig.mxMmap;
  32006. }
  32007. *(i64*)pArg = pFile->mmapSizeMax;
  32008. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  32009. pFile->mmapSizeMax = newLimit;
  32010. if( pFile->mmapSize>0 ){
  32011. winUnmapfile(pFile);
  32012. rc = winMapfile(pFile, -1);
  32013. }
  32014. }
  32015. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  32016. return rc;
  32017. }
  32018. #endif
  32019. }
  32020. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  32021. return SQLITE_NOTFOUND;
  32022. }
  32023. /*
  32024. ** Return the sector size in bytes of the underlying block device for
  32025. ** the specified file. This is almost always 512 bytes, but may be
  32026. ** larger for some devices.
  32027. **
  32028. ** SQLite code assumes this function cannot fail. It also assumes that
  32029. ** if two files are created in the same file-system directory (i.e.
  32030. ** a database and its journal file) that the sector size will be the
  32031. ** same for both.
  32032. */
  32033. static int winSectorSize(sqlite3_file *id){
  32034. (void)id;
  32035. return SQLITE_DEFAULT_SECTOR_SIZE;
  32036. }
  32037. /*
  32038. ** Return a vector of device characteristics.
  32039. */
  32040. static int winDeviceCharacteristics(sqlite3_file *id){
  32041. winFile *p = (winFile*)id;
  32042. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  32043. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  32044. }
  32045. /*
  32046. ** Windows will only let you create file view mappings
  32047. ** on allocation size granularity boundaries.
  32048. ** During sqlite3_os_init() we do a GetSystemInfo()
  32049. ** to get the granularity size.
  32050. */
  32051. SYSTEM_INFO winSysInfo;
  32052. #ifndef SQLITE_OMIT_WAL
  32053. /*
  32054. ** Helper functions to obtain and relinquish the global mutex. The
  32055. ** global mutex is used to protect the winLockInfo objects used by
  32056. ** this file, all of which may be shared by multiple threads.
  32057. **
  32058. ** Function winShmMutexHeld() is used to assert() that the global mutex
  32059. ** is held when required. This function is only used as part of assert()
  32060. ** statements. e.g.
  32061. **
  32062. ** winShmEnterMutex()
  32063. ** assert( winShmMutexHeld() );
  32064. ** winShmLeaveMutex()
  32065. */
  32066. static void winShmEnterMutex(void){
  32067. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32068. }
  32069. static void winShmLeaveMutex(void){
  32070. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32071. }
  32072. #ifdef SQLITE_DEBUG
  32073. static int winShmMutexHeld(void) {
  32074. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32075. }
  32076. #endif
  32077. /*
  32078. ** Object used to represent a single file opened and mmapped to provide
  32079. ** shared memory. When multiple threads all reference the same
  32080. ** log-summary, each thread has its own winFile object, but they all
  32081. ** point to a single instance of this object. In other words, each
  32082. ** log-summary is opened only once per process.
  32083. **
  32084. ** winShmMutexHeld() must be true when creating or destroying
  32085. ** this object or while reading or writing the following fields:
  32086. **
  32087. ** nRef
  32088. ** pNext
  32089. **
  32090. ** The following fields are read-only after the object is created:
  32091. **
  32092. ** fid
  32093. ** zFilename
  32094. **
  32095. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  32096. ** winShmMutexHeld() is true when reading or writing any other field
  32097. ** in this structure.
  32098. **
  32099. */
  32100. struct winShmNode {
  32101. sqlite3_mutex *mutex; /* Mutex to access this object */
  32102. char *zFilename; /* Name of the file */
  32103. winFile hFile; /* File handle from winOpen */
  32104. int szRegion; /* Size of shared-memory regions */
  32105. int nRegion; /* Size of array apRegion */
  32106. struct ShmRegion {
  32107. HANDLE hMap; /* File handle from CreateFileMapping */
  32108. void *pMap;
  32109. } *aRegion;
  32110. DWORD lastErrno; /* The Windows errno from the last I/O error */
  32111. int nRef; /* Number of winShm objects pointing to this */
  32112. winShm *pFirst; /* All winShm objects pointing to this */
  32113. winShmNode *pNext; /* Next in list of all winShmNode objects */
  32114. #ifdef SQLITE_DEBUG
  32115. u8 nextShmId; /* Next available winShm.id value */
  32116. #endif
  32117. };
  32118. /*
  32119. ** A global array of all winShmNode objects.
  32120. **
  32121. ** The winShmMutexHeld() must be true while reading or writing this list.
  32122. */
  32123. static winShmNode *winShmNodeList = 0;
  32124. /*
  32125. ** Structure used internally by this VFS to record the state of an
  32126. ** open shared memory connection.
  32127. **
  32128. ** The following fields are initialized when this object is created and
  32129. ** are read-only thereafter:
  32130. **
  32131. ** winShm.pShmNode
  32132. ** winShm.id
  32133. **
  32134. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  32135. ** while accessing any read/write fields.
  32136. */
  32137. struct winShm {
  32138. winShmNode *pShmNode; /* The underlying winShmNode object */
  32139. winShm *pNext; /* Next winShm with the same winShmNode */
  32140. u8 hasMutex; /* True if holding the winShmNode mutex */
  32141. u16 sharedMask; /* Mask of shared locks held */
  32142. u16 exclMask; /* Mask of exclusive locks held */
  32143. #ifdef SQLITE_DEBUG
  32144. u8 id; /* Id of this connection with its winShmNode */
  32145. #endif
  32146. };
  32147. /*
  32148. ** Constants used for locking
  32149. */
  32150. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  32151. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  32152. /*
  32153. ** Apply advisory locks for all n bytes beginning at ofst.
  32154. */
  32155. #define _SHM_UNLCK 1
  32156. #define _SHM_RDLCK 2
  32157. #define _SHM_WRLCK 3
  32158. static int winShmSystemLock(
  32159. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  32160. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  32161. int ofst, /* Offset to first byte to be locked/unlocked */
  32162. int nByte /* Number of bytes to lock or unlock */
  32163. ){
  32164. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  32165. /* Access to the winShmNode object is serialized by the caller */
  32166. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  32167. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  32168. pFile->hFile.h, lockType, ofst, nByte));
  32169. /* Release/Acquire the system-level lock */
  32170. if( lockType==_SHM_UNLCK ){
  32171. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  32172. }else{
  32173. /* Initialize the locking parameters */
  32174. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  32175. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  32176. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  32177. }
  32178. if( rc!= 0 ){
  32179. rc = SQLITE_OK;
  32180. }else{
  32181. pFile->lastErrno = osGetLastError();
  32182. rc = SQLITE_BUSY;
  32183. }
  32184. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  32185. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  32186. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  32187. return rc;
  32188. }
  32189. /* Forward references to VFS methods */
  32190. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  32191. static int winDelete(sqlite3_vfs *,const char*,int);
  32192. /*
  32193. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  32194. **
  32195. ** This is not a VFS shared-memory method; it is a utility function called
  32196. ** by VFS shared-memory methods.
  32197. */
  32198. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  32199. winShmNode **pp;
  32200. winShmNode *p;
  32201. assert( winShmMutexHeld() );
  32202. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  32203. osGetCurrentProcessId(), deleteFlag));
  32204. pp = &winShmNodeList;
  32205. while( (p = *pp)!=0 ){
  32206. if( p->nRef==0 ){
  32207. int i;
  32208. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  32209. for(i=0; i<p->nRegion; i++){
  32210. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  32211. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  32212. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  32213. UNUSED_VARIABLE_VALUE(bRc);
  32214. bRc = osCloseHandle(p->aRegion[i].hMap);
  32215. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  32216. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  32217. UNUSED_VARIABLE_VALUE(bRc);
  32218. }
  32219. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  32220. SimulateIOErrorBenign(1);
  32221. winClose((sqlite3_file *)&p->hFile);
  32222. SimulateIOErrorBenign(0);
  32223. }
  32224. if( deleteFlag ){
  32225. SimulateIOErrorBenign(1);
  32226. sqlite3BeginBenignMalloc();
  32227. winDelete(pVfs, p->zFilename, 0);
  32228. sqlite3EndBenignMalloc();
  32229. SimulateIOErrorBenign(0);
  32230. }
  32231. *pp = p->pNext;
  32232. sqlite3_free(p->aRegion);
  32233. sqlite3_free(p);
  32234. }else{
  32235. pp = &p->pNext;
  32236. }
  32237. }
  32238. }
  32239. /*
  32240. ** Open the shared-memory area associated with database file pDbFd.
  32241. **
  32242. ** When opening a new shared-memory file, if no other instances of that
  32243. ** file are currently open, in this process or in other processes, then
  32244. ** the file must be truncated to zero length or have its header cleared.
  32245. */
  32246. static int winOpenSharedMemory(winFile *pDbFd){
  32247. struct winShm *p; /* The connection to be opened */
  32248. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  32249. int rc; /* Result code */
  32250. struct winShmNode *pNew; /* Newly allocated winShmNode */
  32251. int nName; /* Size of zName in bytes */
  32252. assert( pDbFd->pShm==0 ); /* Not previously opened */
  32253. /* Allocate space for the new sqlite3_shm object. Also speculatively
  32254. ** allocate space for a new winShmNode and filename.
  32255. */
  32256. p = sqlite3MallocZero( sizeof(*p) );
  32257. if( p==0 ) return SQLITE_IOERR_NOMEM;
  32258. nName = sqlite3Strlen30(pDbFd->zPath);
  32259. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  32260. if( pNew==0 ){
  32261. sqlite3_free(p);
  32262. return SQLITE_IOERR_NOMEM;
  32263. }
  32264. pNew->zFilename = (char*)&pNew[1];
  32265. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  32266. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  32267. /* Look to see if there is an existing winShmNode that can be used.
  32268. ** If no matching winShmNode currently exists, create a new one.
  32269. */
  32270. winShmEnterMutex();
  32271. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  32272. /* TBD need to come up with better match here. Perhaps
  32273. ** use FILE_ID_BOTH_DIR_INFO Structure.
  32274. */
  32275. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  32276. }
  32277. if( pShmNode ){
  32278. sqlite3_free(pNew);
  32279. }else{
  32280. pShmNode = pNew;
  32281. pNew = 0;
  32282. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  32283. pShmNode->pNext = winShmNodeList;
  32284. winShmNodeList = pShmNode;
  32285. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32286. if( pShmNode->mutex==0 ){
  32287. rc = SQLITE_IOERR_NOMEM;
  32288. goto shm_open_err;
  32289. }
  32290. rc = winOpen(pDbFd->pVfs,
  32291. pShmNode->zFilename, /* Name of the file (UTF-8) */
  32292. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  32293. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  32294. 0);
  32295. if( SQLITE_OK!=rc ){
  32296. goto shm_open_err;
  32297. }
  32298. /* Check to see if another process is holding the dead-man switch.
  32299. ** If not, truncate the file to zero length.
  32300. */
  32301. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  32302. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  32303. if( rc!=SQLITE_OK ){
  32304. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  32305. "winOpenShm", pDbFd->zPath);
  32306. }
  32307. }
  32308. if( rc==SQLITE_OK ){
  32309. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  32310. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  32311. }
  32312. if( rc ) goto shm_open_err;
  32313. }
  32314. /* Make the new connection a child of the winShmNode */
  32315. p->pShmNode = pShmNode;
  32316. #ifdef SQLITE_DEBUG
  32317. p->id = pShmNode->nextShmId++;
  32318. #endif
  32319. pShmNode->nRef++;
  32320. pDbFd->pShm = p;
  32321. winShmLeaveMutex();
  32322. /* The reference count on pShmNode has already been incremented under
  32323. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  32324. ** new (struct winShm) object to the pShmNode has been set. All that is
  32325. ** left to do is to link the new object into the linked list starting
  32326. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  32327. ** mutex.
  32328. */
  32329. sqlite3_mutex_enter(pShmNode->mutex);
  32330. p->pNext = pShmNode->pFirst;
  32331. pShmNode->pFirst = p;
  32332. sqlite3_mutex_leave(pShmNode->mutex);
  32333. return SQLITE_OK;
  32334. /* Jump here on any error */
  32335. shm_open_err:
  32336. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  32337. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  32338. sqlite3_free(p);
  32339. sqlite3_free(pNew);
  32340. winShmLeaveMutex();
  32341. return rc;
  32342. }
  32343. /*
  32344. ** Close a connection to shared-memory. Delete the underlying
  32345. ** storage if deleteFlag is true.
  32346. */
  32347. static int winShmUnmap(
  32348. sqlite3_file *fd, /* Database holding shared memory */
  32349. int deleteFlag /* Delete after closing if true */
  32350. ){
  32351. winFile *pDbFd; /* Database holding shared-memory */
  32352. winShm *p; /* The connection to be closed */
  32353. winShmNode *pShmNode; /* The underlying shared-memory file */
  32354. winShm **pp; /* For looping over sibling connections */
  32355. pDbFd = (winFile*)fd;
  32356. p = pDbFd->pShm;
  32357. if( p==0 ) return SQLITE_OK;
  32358. pShmNode = p->pShmNode;
  32359. /* Remove connection p from the set of connections associated
  32360. ** with pShmNode */
  32361. sqlite3_mutex_enter(pShmNode->mutex);
  32362. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  32363. *pp = p->pNext;
  32364. /* Free the connection p */
  32365. sqlite3_free(p);
  32366. pDbFd->pShm = 0;
  32367. sqlite3_mutex_leave(pShmNode->mutex);
  32368. /* If pShmNode->nRef has reached 0, then close the underlying
  32369. ** shared-memory file, too */
  32370. winShmEnterMutex();
  32371. assert( pShmNode->nRef>0 );
  32372. pShmNode->nRef--;
  32373. if( pShmNode->nRef==0 ){
  32374. winShmPurge(pDbFd->pVfs, deleteFlag);
  32375. }
  32376. winShmLeaveMutex();
  32377. return SQLITE_OK;
  32378. }
  32379. /*
  32380. ** Change the lock state for a shared-memory segment.
  32381. */
  32382. static int winShmLock(
  32383. sqlite3_file *fd, /* Database file holding the shared memory */
  32384. int ofst, /* First lock to acquire or release */
  32385. int n, /* Number of locks to acquire or release */
  32386. int flags /* What to do with the lock */
  32387. ){
  32388. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  32389. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  32390. winShm *pX; /* For looping over all siblings */
  32391. winShmNode *pShmNode = p->pShmNode;
  32392. int rc = SQLITE_OK; /* Result code */
  32393. u16 mask; /* Mask of locks to take or release */
  32394. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  32395. assert( n>=1 );
  32396. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  32397. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  32398. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  32399. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  32400. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  32401. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  32402. assert( n>1 || mask==(1<<ofst) );
  32403. sqlite3_mutex_enter(pShmNode->mutex);
  32404. if( flags & SQLITE_SHM_UNLOCK ){
  32405. u16 allMask = 0; /* Mask of locks held by siblings */
  32406. /* See if any siblings hold this same lock */
  32407. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32408. if( pX==p ) continue;
  32409. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  32410. allMask |= pX->sharedMask;
  32411. }
  32412. /* Unlock the system-level locks */
  32413. if( (mask & allMask)==0 ){
  32414. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  32415. }else{
  32416. rc = SQLITE_OK;
  32417. }
  32418. /* Undo the local locks */
  32419. if( rc==SQLITE_OK ){
  32420. p->exclMask &= ~mask;
  32421. p->sharedMask &= ~mask;
  32422. }
  32423. }else if( flags & SQLITE_SHM_SHARED ){
  32424. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  32425. /* Find out which shared locks are already held by sibling connections.
  32426. ** If any sibling already holds an exclusive lock, go ahead and return
  32427. ** SQLITE_BUSY.
  32428. */
  32429. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32430. if( (pX->exclMask & mask)!=0 ){
  32431. rc = SQLITE_BUSY;
  32432. break;
  32433. }
  32434. allShared |= pX->sharedMask;
  32435. }
  32436. /* Get shared locks at the system level, if necessary */
  32437. if( rc==SQLITE_OK ){
  32438. if( (allShared & mask)==0 ){
  32439. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  32440. }else{
  32441. rc = SQLITE_OK;
  32442. }
  32443. }
  32444. /* Get the local shared locks */
  32445. if( rc==SQLITE_OK ){
  32446. p->sharedMask |= mask;
  32447. }
  32448. }else{
  32449. /* Make sure no sibling connections hold locks that will block this
  32450. ** lock. If any do, return SQLITE_BUSY right away.
  32451. */
  32452. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32453. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  32454. rc = SQLITE_BUSY;
  32455. break;
  32456. }
  32457. }
  32458. /* Get the exclusive locks at the system level. Then if successful
  32459. ** also mark the local connection as being locked.
  32460. */
  32461. if( rc==SQLITE_OK ){
  32462. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  32463. if( rc==SQLITE_OK ){
  32464. assert( (p->sharedMask & mask)==0 );
  32465. p->exclMask |= mask;
  32466. }
  32467. }
  32468. }
  32469. sqlite3_mutex_leave(pShmNode->mutex);
  32470. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  32471. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  32472. sqlite3ErrName(rc)));
  32473. return rc;
  32474. }
  32475. /*
  32476. ** Implement a memory barrier or memory fence on shared memory.
  32477. **
  32478. ** All loads and stores begun before the barrier must complete before
  32479. ** any load or store begun after the barrier.
  32480. */
  32481. static void winShmBarrier(
  32482. sqlite3_file *fd /* Database holding the shared memory */
  32483. ){
  32484. UNUSED_PARAMETER(fd);
  32485. /* MemoryBarrier(); // does not work -- do not know why not */
  32486. winShmEnterMutex();
  32487. winShmLeaveMutex();
  32488. }
  32489. /*
  32490. ** This function is called to obtain a pointer to region iRegion of the
  32491. ** shared-memory associated with the database file fd. Shared-memory regions
  32492. ** are numbered starting from zero. Each shared-memory region is szRegion
  32493. ** bytes in size.
  32494. **
  32495. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32496. **
  32497. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  32498. ** region has not been allocated (by any client, including one running in a
  32499. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32500. ** isWrite is non-zero and the requested shared-memory region has not yet
  32501. ** been allocated, it is allocated by this function.
  32502. **
  32503. ** If the shared-memory region has already been allocated or is allocated by
  32504. ** this call as described above, then it is mapped into this processes
  32505. ** address space (if it is not already), *pp is set to point to the mapped
  32506. ** memory and SQLITE_OK returned.
  32507. */
  32508. static int winShmMap(
  32509. sqlite3_file *fd, /* Handle open on database file */
  32510. int iRegion, /* Region to retrieve */
  32511. int szRegion, /* Size of regions */
  32512. int isWrite, /* True to extend file if necessary */
  32513. void volatile **pp /* OUT: Mapped memory */
  32514. ){
  32515. winFile *pDbFd = (winFile*)fd;
  32516. winShm *p = pDbFd->pShm;
  32517. winShmNode *pShmNode;
  32518. int rc = SQLITE_OK;
  32519. if( !p ){
  32520. rc = winOpenSharedMemory(pDbFd);
  32521. if( rc!=SQLITE_OK ) return rc;
  32522. p = pDbFd->pShm;
  32523. }
  32524. pShmNode = p->pShmNode;
  32525. sqlite3_mutex_enter(pShmNode->mutex);
  32526. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32527. if( pShmNode->nRegion<=iRegion ){
  32528. struct ShmRegion *apNew; /* New aRegion[] array */
  32529. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  32530. sqlite3_int64 sz; /* Current size of wal-index file */
  32531. pShmNode->szRegion = szRegion;
  32532. /* The requested region is not mapped into this processes address space.
  32533. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32534. ** large enough to contain the requested region).
  32535. */
  32536. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  32537. if( rc!=SQLITE_OK ){
  32538. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32539. "winShmMap1", pDbFd->zPath);
  32540. goto shmpage_out;
  32541. }
  32542. if( sz<nByte ){
  32543. /* The requested memory region does not exist. If isWrite is set to
  32544. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32545. **
  32546. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  32547. ** the requested memory region.
  32548. */
  32549. if( !isWrite ) goto shmpage_out;
  32550. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  32551. if( rc!=SQLITE_OK ){
  32552. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32553. "winShmMap2", pDbFd->zPath);
  32554. goto shmpage_out;
  32555. }
  32556. }
  32557. /* Map the requested memory region into this processes address space. */
  32558. apNew = (struct ShmRegion *)sqlite3_realloc(
  32559. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  32560. );
  32561. if( !apNew ){
  32562. rc = SQLITE_IOERR_NOMEM;
  32563. goto shmpage_out;
  32564. }
  32565. pShmNode->aRegion = apNew;
  32566. while( pShmNode->nRegion<=iRegion ){
  32567. HANDLE hMap = NULL; /* file-mapping handle */
  32568. void *pMap = 0; /* Mapped memory region */
  32569. #if SQLITE_OS_WINRT
  32570. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  32571. NULL, PAGE_READWRITE, nByte, NULL
  32572. );
  32573. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32574. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  32575. NULL, PAGE_READWRITE, 0, nByte, NULL
  32576. );
  32577. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32578. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  32579. NULL, PAGE_READWRITE, 0, nByte, NULL
  32580. );
  32581. #endif
  32582. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  32583. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  32584. hMap ? "ok" : "failed"));
  32585. if( hMap ){
  32586. int iOffset = pShmNode->nRegion*szRegion;
  32587. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32588. #if SQLITE_OS_WINRT
  32589. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32590. iOffset - iOffsetShift, szRegion + iOffsetShift
  32591. );
  32592. #else
  32593. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32594. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  32595. );
  32596. #endif
  32597. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  32598. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  32599. szRegion, pMap ? "ok" : "failed"));
  32600. }
  32601. if( !pMap ){
  32602. pShmNode->lastErrno = osGetLastError();
  32603. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  32604. "winShmMap3", pDbFd->zPath);
  32605. if( hMap ) osCloseHandle(hMap);
  32606. goto shmpage_out;
  32607. }
  32608. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  32609. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  32610. pShmNode->nRegion++;
  32611. }
  32612. }
  32613. shmpage_out:
  32614. if( pShmNode->nRegion>iRegion ){
  32615. int iOffset = iRegion*szRegion;
  32616. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32617. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  32618. *pp = (void *)&p[iOffsetShift];
  32619. }else{
  32620. *pp = 0;
  32621. }
  32622. sqlite3_mutex_leave(pShmNode->mutex);
  32623. return rc;
  32624. }
  32625. #else
  32626. # define winShmMap 0
  32627. # define winShmLock 0
  32628. # define winShmBarrier 0
  32629. # define winShmUnmap 0
  32630. #endif /* #ifndef SQLITE_OMIT_WAL */
  32631. /*
  32632. ** Cleans up the mapped region of the specified file, if any.
  32633. */
  32634. #if SQLITE_MAX_MMAP_SIZE>0
  32635. static int winUnmapfile(winFile *pFile){
  32636. assert( pFile!=0 );
  32637. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  32638. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  32639. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  32640. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  32641. if( pFile->pMapRegion ){
  32642. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  32643. pFile->lastErrno = osGetLastError();
  32644. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  32645. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  32646. pFile->pMapRegion));
  32647. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32648. "winUnmapfile1", pFile->zPath);
  32649. }
  32650. pFile->pMapRegion = 0;
  32651. pFile->mmapSize = 0;
  32652. pFile->mmapSizeActual = 0;
  32653. }
  32654. if( pFile->hMap!=NULL ){
  32655. if( !osCloseHandle(pFile->hMap) ){
  32656. pFile->lastErrno = osGetLastError();
  32657. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  32658. osGetCurrentProcessId(), pFile, pFile->hMap));
  32659. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32660. "winUnmapfile2", pFile->zPath);
  32661. }
  32662. pFile->hMap = NULL;
  32663. }
  32664. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32665. osGetCurrentProcessId(), pFile));
  32666. return SQLITE_OK;
  32667. }
  32668. /*
  32669. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32670. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32671. ** there already exists a mapping for this file, and there are still
  32672. ** outstanding xFetch() references to it, this function is a no-op.
  32673. **
  32674. ** If parameter nByte is non-negative, then it is the requested size of
  32675. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32676. ** requested size is the size of the file on disk. The actual size of the
  32677. ** created mapping is either the requested size or the value configured
  32678. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  32679. **
  32680. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32681. ** recreated as a result of outstanding references) or an SQLite error
  32682. ** code otherwise.
  32683. */
  32684. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  32685. sqlite3_int64 nMap = nByte;
  32686. int rc;
  32687. assert( nMap>=0 || pFd->nFetchOut==0 );
  32688. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  32689. osGetCurrentProcessId(), pFd, nByte));
  32690. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32691. if( nMap<0 ){
  32692. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  32693. if( rc ){
  32694. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  32695. osGetCurrentProcessId(), pFd));
  32696. return SQLITE_IOERR_FSTAT;
  32697. }
  32698. }
  32699. if( nMap>pFd->mmapSizeMax ){
  32700. nMap = pFd->mmapSizeMax;
  32701. }
  32702. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  32703. if( nMap==0 && pFd->mmapSize>0 ){
  32704. winUnmapfile(pFd);
  32705. }
  32706. if( nMap!=pFd->mmapSize ){
  32707. void *pNew = 0;
  32708. DWORD protect = PAGE_READONLY;
  32709. DWORD flags = FILE_MAP_READ;
  32710. winUnmapfile(pFd);
  32711. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  32712. protect = PAGE_READWRITE;
  32713. flags |= FILE_MAP_WRITE;
  32714. }
  32715. #if SQLITE_OS_WINRT
  32716. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  32717. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32718. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  32719. (DWORD)((nMap>>32) & 0xffffffff),
  32720. (DWORD)(nMap & 0xffffffff), NULL);
  32721. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32722. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  32723. (DWORD)((nMap>>32) & 0xffffffff),
  32724. (DWORD)(nMap & 0xffffffff), NULL);
  32725. #endif
  32726. if( pFd->hMap==NULL ){
  32727. pFd->lastErrno = osGetLastError();
  32728. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32729. "winMapfile1", pFd->zPath);
  32730. /* Log the error, but continue normal operation using xRead/xWrite */
  32731. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  32732. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32733. return SQLITE_OK;
  32734. }
  32735. assert( (nMap % winSysInfo.dwPageSize)==0 );
  32736. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  32737. #if SQLITE_OS_WINRT
  32738. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  32739. #else
  32740. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  32741. #endif
  32742. if( pNew==NULL ){
  32743. osCloseHandle(pFd->hMap);
  32744. pFd->hMap = NULL;
  32745. pFd->lastErrno = osGetLastError();
  32746. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32747. "winMapfile2", pFd->zPath);
  32748. /* Log the error, but continue normal operation using xRead/xWrite */
  32749. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  32750. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32751. return SQLITE_OK;
  32752. }
  32753. pFd->pMapRegion = pNew;
  32754. pFd->mmapSize = nMap;
  32755. pFd->mmapSizeActual = nMap;
  32756. }
  32757. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32758. osGetCurrentProcessId(), pFd));
  32759. return SQLITE_OK;
  32760. }
  32761. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32762. /*
  32763. ** If possible, return a pointer to a mapping of file fd starting at offset
  32764. ** iOff. The mapping must be valid for at least nAmt bytes.
  32765. **
  32766. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32767. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32768. ** Finally, if an error does occur, return an SQLite error code. The final
  32769. ** value of *pp is undefined in this case.
  32770. **
  32771. ** If this function does return a pointer, the caller must eventually
  32772. ** release the reference by calling winUnfetch().
  32773. */
  32774. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32775. #if SQLITE_MAX_MMAP_SIZE>0
  32776. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32777. #endif
  32778. *pp = 0;
  32779. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  32780. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  32781. #if SQLITE_MAX_MMAP_SIZE>0
  32782. if( pFd->mmapSizeMax>0 ){
  32783. if( pFd->pMapRegion==0 ){
  32784. int rc = winMapfile(pFd, -1);
  32785. if( rc!=SQLITE_OK ){
  32786. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  32787. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32788. return rc;
  32789. }
  32790. }
  32791. if( pFd->mmapSize >= iOff+nAmt ){
  32792. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32793. pFd->nFetchOut++;
  32794. }
  32795. }
  32796. #endif
  32797. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  32798. osGetCurrentProcessId(), fd, pp, *pp));
  32799. return SQLITE_OK;
  32800. }
  32801. /*
  32802. ** If the third argument is non-NULL, then this function releases a
  32803. ** reference obtained by an earlier call to winFetch(). The second
  32804. ** argument passed to this function must be the same as the corresponding
  32805. ** argument that was passed to the winFetch() invocation.
  32806. **
  32807. ** Or, if the third argument is NULL, then this function is being called
  32808. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32809. ** may now be invalid and should be unmapped.
  32810. */
  32811. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32812. #if SQLITE_MAX_MMAP_SIZE>0
  32813. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32814. /* If p==0 (unmap the entire file) then there must be no outstanding
  32815. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32816. ** then there must be at least one outstanding. */
  32817. assert( (p==0)==(pFd->nFetchOut==0) );
  32818. /* If p!=0, it must match the iOff value. */
  32819. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32820. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  32821. osGetCurrentProcessId(), pFd, iOff, p));
  32822. if( p ){
  32823. pFd->nFetchOut--;
  32824. }else{
  32825. /* FIXME: If Windows truly always prevents truncating or deleting a
  32826. ** file while a mapping is held, then the following winUnmapfile() call
  32827. ** is unnecessary can can be omitted - potentially improving
  32828. ** performance. */
  32829. winUnmapfile(pFd);
  32830. }
  32831. assert( pFd->nFetchOut>=0 );
  32832. #endif
  32833. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32834. osGetCurrentProcessId(), fd));
  32835. return SQLITE_OK;
  32836. }
  32837. /*
  32838. ** Here ends the implementation of all sqlite3_file methods.
  32839. **
  32840. ********************** End sqlite3_file Methods *******************************
  32841. ******************************************************************************/
  32842. /*
  32843. ** This vector defines all the methods that can operate on an
  32844. ** sqlite3_file for win32.
  32845. */
  32846. static const sqlite3_io_methods winIoMethod = {
  32847. 3, /* iVersion */
  32848. winClose, /* xClose */
  32849. winRead, /* xRead */
  32850. winWrite, /* xWrite */
  32851. winTruncate, /* xTruncate */
  32852. winSync, /* xSync */
  32853. winFileSize, /* xFileSize */
  32854. winLock, /* xLock */
  32855. winUnlock, /* xUnlock */
  32856. winCheckReservedLock, /* xCheckReservedLock */
  32857. winFileControl, /* xFileControl */
  32858. winSectorSize, /* xSectorSize */
  32859. winDeviceCharacteristics, /* xDeviceCharacteristics */
  32860. winShmMap, /* xShmMap */
  32861. winShmLock, /* xShmLock */
  32862. winShmBarrier, /* xShmBarrier */
  32863. winShmUnmap, /* xShmUnmap */
  32864. winFetch, /* xFetch */
  32865. winUnfetch /* xUnfetch */
  32866. };
  32867. /****************************************************************************
  32868. **************************** sqlite3_vfs methods ****************************
  32869. **
  32870. ** This division contains the implementation of methods on the
  32871. ** sqlite3_vfs object.
  32872. */
  32873. #if 0
  32874. /*
  32875. ** Convert a filename from whatever the underlying operating system
  32876. ** supports for filenames into UTF-8. Space to hold the result is
  32877. ** obtained from malloc and must be freed by the calling function.
  32878. */
  32879. static char *winConvertToUtf8Filename(const void *zFilename){
  32880. char *zConverted = 0;
  32881. if( osIsNT() ){
  32882. zConverted = winUnicodeToUtf8(zFilename);
  32883. }
  32884. #ifdef SQLITE_WIN32_HAS_ANSI
  32885. else{
  32886. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  32887. }
  32888. #endif
  32889. /* caller will handle out of memory */
  32890. return zConverted;
  32891. }
  32892. #endif
  32893. /*
  32894. ** Convert a UTF-8 filename into whatever form the underlying
  32895. ** operating system wants filenames in. Space to hold the result
  32896. ** is obtained from malloc and must be freed by the calling
  32897. ** function.
  32898. */
  32899. static void *winConvertFromUtf8Filename(const char *zFilename){
  32900. void *zConverted = 0;
  32901. if( osIsNT() ){
  32902. zConverted = winUtf8ToUnicode(zFilename);
  32903. }
  32904. #ifdef SQLITE_WIN32_HAS_ANSI
  32905. else{
  32906. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  32907. }
  32908. #endif
  32909. /* caller will handle out of memory */
  32910. return zConverted;
  32911. }
  32912. /*
  32913. ** This function returns non-zero if the specified UTF-8 string buffer
  32914. ** ends with a directory separator character.
  32915. */
  32916. static int winEndsInDirSep(char *zBuf){
  32917. if( zBuf ){
  32918. int nLen = sqlite3Strlen30(zBuf);
  32919. return nLen>0 && winIsDirSep(zBuf[nLen-1]);
  32920. }
  32921. return 0;
  32922. }
  32923. /*
  32924. ** Create a temporary file name and store the resulting pointer into pzBuf.
  32925. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  32926. */
  32927. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  32928. static char zChars[] =
  32929. "abcdefghijklmnopqrstuvwxyz"
  32930. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  32931. "0123456789";
  32932. size_t i, j;
  32933. int nBuf, nLen;
  32934. char *zBuf;
  32935. /* It's odd to simulate an io-error here, but really this is just
  32936. ** using the io-error infrastructure to test that SQLite handles this
  32937. ** function failing.
  32938. */
  32939. SimulateIOError( return SQLITE_IOERR );
  32940. /* Allocate a temporary buffer to store the fully qualified file
  32941. ** name for the temporary file. If this fails, we cannot continue.
  32942. */
  32943. nBuf = pVfs->mxPathname;
  32944. zBuf = sqlite3MallocZero( nBuf+2 );
  32945. if( !zBuf ){
  32946. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32947. return SQLITE_IOERR_NOMEM;
  32948. }
  32949. /* Figure out the effective temporary directory. First, check if one
  32950. ** has been explicitly set by the application; otherwise, use the one
  32951. ** configured by the operating system.
  32952. */
  32953. assert( nBuf>30 );
  32954. if( sqlite3_temp_directory ){
  32955. sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory,
  32956. winEndsInDirSep(sqlite3_temp_directory) ? "" :
  32957. winGetDirDep());
  32958. }
  32959. #if defined(__CYGWIN__)
  32960. else{
  32961. static const char *azDirs[] = {
  32962. 0, /* getenv("SQLITE_TMPDIR") */
  32963. 0, /* getenv("TMPDIR") */
  32964. 0, /* getenv("TMP") */
  32965. 0, /* getenv("TEMP") */
  32966. 0, /* getenv("USERPROFILE") */
  32967. "/var/tmp",
  32968. "/usr/tmp",
  32969. "/tmp",
  32970. ".",
  32971. 0 /* List terminator */
  32972. };
  32973. unsigned int i;
  32974. const char *zDir = 0;
  32975. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  32976. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  32977. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  32978. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  32979. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  32980. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  32981. void *zConverted;
  32982. if( zDir==0 ) continue;
  32983. /* If the path starts with a drive letter followed by the colon
  32984. ** character, assume it is already a native Win32 path; otherwise,
  32985. ** it must be converted to a native Win32 path prior via the Cygwin
  32986. ** API prior to using it.
  32987. */
  32988. if( winIsDriveLetterAndColon(zDir) ){
  32989. zConverted = winConvertFromUtf8Filename(zDir);
  32990. if( !zConverted ){
  32991. sqlite3_free(zBuf);
  32992. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32993. return SQLITE_IOERR_NOMEM;
  32994. }
  32995. if( winIsDir(zConverted) ){
  32996. sqlite3_snprintf(nBuf-30, zBuf, "%s", zDir);
  32997. sqlite3_free(zConverted);
  32998. break;
  32999. }
  33000. sqlite3_free(zConverted);
  33001. }else{
  33002. zConverted = sqlite3MallocZero( nBuf+1 );
  33003. if( !zConverted ){
  33004. sqlite3_free(zBuf);
  33005. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33006. return SQLITE_IOERR_NOMEM;
  33007. }
  33008. if( cygwin_conv_path(
  33009. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  33010. zConverted, nBuf+1)<0 ){
  33011. sqlite3_free(zConverted);
  33012. sqlite3_free(zBuf);
  33013. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  33014. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  33015. "winGetTempname1", zDir);
  33016. }
  33017. if( winIsDir(zConverted) ){
  33018. /* At this point, we know the candidate directory exists and should
  33019. ** be used. However, we may need to convert the string containing
  33020. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  33021. */
  33022. if( osIsNT() ){
  33023. char *zUtf8 = winUnicodeToUtf8(zConverted);
  33024. if( !zUtf8 ){
  33025. sqlite3_free(zConverted);
  33026. sqlite3_free(zBuf);
  33027. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33028. return SQLITE_IOERR_NOMEM;
  33029. }
  33030. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  33031. sqlite3_free(zUtf8);
  33032. sqlite3_free(zConverted);
  33033. break;
  33034. }else{
  33035. sqlite3_snprintf(nBuf-30, zBuf, "%s", zConverted);
  33036. sqlite3_free(zConverted);
  33037. break;
  33038. }
  33039. }
  33040. sqlite3_free(zConverted);
  33041. }
  33042. }
  33043. }
  33044. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  33045. else if( osIsNT() ){
  33046. char *zMulti;
  33047. LPWSTR zWidePath = sqlite3MallocZero( nBuf*sizeof(WCHAR) );
  33048. if( !zWidePath ){
  33049. sqlite3_free(zBuf);
  33050. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33051. return SQLITE_IOERR_NOMEM;
  33052. }
  33053. if( osGetTempPathW(nBuf, zWidePath)==0 ){
  33054. sqlite3_free(zWidePath);
  33055. sqlite3_free(zBuf);
  33056. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  33057. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  33058. "winGetTempname1", 0);
  33059. }
  33060. zMulti = winUnicodeToUtf8(zWidePath);
  33061. if( zMulti ){
  33062. sqlite3_snprintf(nBuf-30, zBuf, "%s", zMulti);
  33063. sqlite3_free(zMulti);
  33064. sqlite3_free(zWidePath);
  33065. }else{
  33066. sqlite3_free(zWidePath);
  33067. sqlite3_free(zBuf);
  33068. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33069. return SQLITE_IOERR_NOMEM;
  33070. }
  33071. }
  33072. #ifdef SQLITE_WIN32_HAS_ANSI
  33073. else{
  33074. char *zUtf8;
  33075. char *zMbcsPath = sqlite3MallocZero( nBuf );
  33076. if( !zMbcsPath ){
  33077. sqlite3_free(zBuf);
  33078. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33079. return SQLITE_IOERR_NOMEM;
  33080. }
  33081. if( osGetTempPathA(nBuf, zMbcsPath)==0 ){
  33082. sqlite3_free(zBuf);
  33083. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  33084. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  33085. "winGetTempname2", 0);
  33086. }
  33087. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  33088. if( zUtf8 ){
  33089. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  33090. sqlite3_free(zUtf8);
  33091. }else{
  33092. sqlite3_free(zBuf);
  33093. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33094. return SQLITE_IOERR_NOMEM;
  33095. }
  33096. }
  33097. #endif /* SQLITE_WIN32_HAS_ANSI */
  33098. #endif /* !SQLITE_OS_WINRT */
  33099. /* Check that the output buffer is large enough for the temporary file
  33100. ** name. If it is not, return SQLITE_ERROR.
  33101. */
  33102. nLen = sqlite3Strlen30(zBuf);
  33103. if( (nLen + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  33104. sqlite3_free(zBuf);
  33105. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  33106. return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0);
  33107. }
  33108. sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  33109. j = sqlite3Strlen30(zBuf);
  33110. sqlite3_randomness(15, &zBuf[j]);
  33111. for(i=0; i<15; i++, j++){
  33112. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  33113. }
  33114. zBuf[j] = 0;
  33115. zBuf[j+1] = 0;
  33116. *pzBuf = zBuf;
  33117. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  33118. return SQLITE_OK;
  33119. }
  33120. /*
  33121. ** Return TRUE if the named file is really a directory. Return false if
  33122. ** it is something other than a directory, or if there is any kind of memory
  33123. ** allocation failure.
  33124. */
  33125. static int winIsDir(const void *zConverted){
  33126. DWORD attr;
  33127. int rc = 0;
  33128. DWORD lastErrno;
  33129. if( osIsNT() ){
  33130. int cnt = 0;
  33131. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33132. memset(&sAttrData, 0, sizeof(sAttrData));
  33133. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  33134. GetFileExInfoStandard,
  33135. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  33136. if( !rc ){
  33137. return 0; /* Invalid name? */
  33138. }
  33139. attr = sAttrData.dwFileAttributes;
  33140. #if SQLITE_OS_WINCE==0
  33141. }else{
  33142. attr = osGetFileAttributesA((char*)zConverted);
  33143. #endif
  33144. }
  33145. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  33146. }
  33147. /*
  33148. ** Open a file.
  33149. */
  33150. static int winOpen(
  33151. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  33152. const char *zName, /* Name of the file (UTF-8) */
  33153. sqlite3_file *id, /* Write the SQLite file handle here */
  33154. int flags, /* Open mode flags */
  33155. int *pOutFlags /* Status return flags */
  33156. ){
  33157. HANDLE h;
  33158. DWORD lastErrno;
  33159. DWORD dwDesiredAccess;
  33160. DWORD dwShareMode;
  33161. DWORD dwCreationDisposition;
  33162. DWORD dwFlagsAndAttributes = 0;
  33163. #if SQLITE_OS_WINCE
  33164. int isTemp = 0;
  33165. #endif
  33166. winFile *pFile = (winFile*)id;
  33167. void *zConverted; /* Filename in OS encoding */
  33168. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  33169. int cnt = 0;
  33170. /* If argument zPath is a NULL pointer, this function is required to open
  33171. ** a temporary file. Use this buffer to store the file name in.
  33172. */
  33173. char *zTmpname = 0; /* For temporary filename, if necessary. */
  33174. int rc = SQLITE_OK; /* Function Return Code */
  33175. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  33176. int eType = flags&0xFFFFFF00; /* Type of file to open */
  33177. #endif
  33178. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  33179. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  33180. int isCreate = (flags & SQLITE_OPEN_CREATE);
  33181. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  33182. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  33183. #ifndef NDEBUG
  33184. int isOpenJournal = (isCreate && (
  33185. eType==SQLITE_OPEN_MASTER_JOURNAL
  33186. || eType==SQLITE_OPEN_MAIN_JOURNAL
  33187. || eType==SQLITE_OPEN_WAL
  33188. ));
  33189. #endif
  33190. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  33191. zUtf8Name, id, flags, pOutFlags));
  33192. /* Check the following statements are true:
  33193. **
  33194. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  33195. ** (b) if CREATE is set, then READWRITE must also be set, and
  33196. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  33197. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  33198. */
  33199. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  33200. assert(isCreate==0 || isReadWrite);
  33201. assert(isExclusive==0 || isCreate);
  33202. assert(isDelete==0 || isCreate);
  33203. /* The main DB, main journal, WAL file and master journal are never
  33204. ** automatically deleted. Nor are they ever temporary files. */
  33205. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  33206. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  33207. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  33208. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  33209. /* Assert that the upper layer has set one of the "file-type" flags. */
  33210. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  33211. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  33212. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  33213. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  33214. );
  33215. assert( pFile!=0 );
  33216. memset(pFile, 0, sizeof(winFile));
  33217. pFile->h = INVALID_HANDLE_VALUE;
  33218. #if SQLITE_OS_WINRT
  33219. if( !zUtf8Name && !sqlite3_temp_directory ){
  33220. sqlite3_log(SQLITE_ERROR,
  33221. "sqlite3_temp_directory variable should be set for WinRT");
  33222. }
  33223. #endif
  33224. /* If the second argument to this function is NULL, generate a
  33225. ** temporary file name to use
  33226. */
  33227. if( !zUtf8Name ){
  33228. assert( isDelete && !isOpenJournal );
  33229. rc = winGetTempname(pVfs, &zTmpname);
  33230. if( rc!=SQLITE_OK ){
  33231. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  33232. return rc;
  33233. }
  33234. zUtf8Name = zTmpname;
  33235. }
  33236. /* Database filenames are double-zero terminated if they are not
  33237. ** URIs with parameters. Hence, they can always be passed into
  33238. ** sqlite3_uri_parameter().
  33239. */
  33240. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  33241. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  33242. /* Convert the filename to the system encoding. */
  33243. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  33244. if( zConverted==0 ){
  33245. sqlite3_free(zTmpname);
  33246. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  33247. return SQLITE_IOERR_NOMEM;
  33248. }
  33249. if( winIsDir(zConverted) ){
  33250. sqlite3_free(zConverted);
  33251. sqlite3_free(zTmpname);
  33252. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  33253. return SQLITE_CANTOPEN_ISDIR;
  33254. }
  33255. if( isReadWrite ){
  33256. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  33257. }else{
  33258. dwDesiredAccess = GENERIC_READ;
  33259. }
  33260. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  33261. ** created. SQLite doesn't use it to indicate "exclusive access"
  33262. ** as it is usually understood.
  33263. */
  33264. if( isExclusive ){
  33265. /* Creates a new file, only if it does not already exist. */
  33266. /* If the file exists, it fails. */
  33267. dwCreationDisposition = CREATE_NEW;
  33268. }else if( isCreate ){
  33269. /* Open existing file, or create if it doesn't exist */
  33270. dwCreationDisposition = OPEN_ALWAYS;
  33271. }else{
  33272. /* Opens a file, only if it exists. */
  33273. dwCreationDisposition = OPEN_EXISTING;
  33274. }
  33275. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  33276. if( isDelete ){
  33277. #if SQLITE_OS_WINCE
  33278. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  33279. isTemp = 1;
  33280. #else
  33281. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  33282. | FILE_ATTRIBUTE_HIDDEN
  33283. | FILE_FLAG_DELETE_ON_CLOSE;
  33284. #endif
  33285. }else{
  33286. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  33287. }
  33288. /* Reports from the internet are that performance is always
  33289. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  33290. #if SQLITE_OS_WINCE
  33291. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  33292. #endif
  33293. if( osIsNT() ){
  33294. #if SQLITE_OS_WINRT
  33295. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  33296. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  33297. extendedParameters.dwFileAttributes =
  33298. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  33299. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  33300. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  33301. extendedParameters.lpSecurityAttributes = NULL;
  33302. extendedParameters.hTemplateFile = NULL;
  33303. while( (h = osCreateFile2((LPCWSTR)zConverted,
  33304. dwDesiredAccess,
  33305. dwShareMode,
  33306. dwCreationDisposition,
  33307. &extendedParameters))==INVALID_HANDLE_VALUE &&
  33308. winRetryIoerr(&cnt, &lastErrno) ){
  33309. /* Noop */
  33310. }
  33311. #else
  33312. while( (h = osCreateFileW((LPCWSTR)zConverted,
  33313. dwDesiredAccess,
  33314. dwShareMode, NULL,
  33315. dwCreationDisposition,
  33316. dwFlagsAndAttributes,
  33317. NULL))==INVALID_HANDLE_VALUE &&
  33318. winRetryIoerr(&cnt, &lastErrno) ){
  33319. /* Noop */
  33320. }
  33321. #endif
  33322. }
  33323. #ifdef SQLITE_WIN32_HAS_ANSI
  33324. else{
  33325. while( (h = osCreateFileA((LPCSTR)zConverted,
  33326. dwDesiredAccess,
  33327. dwShareMode, NULL,
  33328. dwCreationDisposition,
  33329. dwFlagsAndAttributes,
  33330. NULL))==INVALID_HANDLE_VALUE &&
  33331. winRetryIoerr(&cnt, &lastErrno) ){
  33332. /* Noop */
  33333. }
  33334. }
  33335. #endif
  33336. winLogIoerr(cnt);
  33337. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  33338. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  33339. if( h==INVALID_HANDLE_VALUE ){
  33340. pFile->lastErrno = lastErrno;
  33341. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  33342. sqlite3_free(zConverted);
  33343. sqlite3_free(zTmpname);
  33344. if( isReadWrite && !isExclusive ){
  33345. return winOpen(pVfs, zName, id,
  33346. ((flags|SQLITE_OPEN_READONLY) &
  33347. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  33348. pOutFlags);
  33349. }else{
  33350. return SQLITE_CANTOPEN_BKPT;
  33351. }
  33352. }
  33353. if( pOutFlags ){
  33354. if( isReadWrite ){
  33355. *pOutFlags = SQLITE_OPEN_READWRITE;
  33356. }else{
  33357. *pOutFlags = SQLITE_OPEN_READONLY;
  33358. }
  33359. }
  33360. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  33361. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  33362. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  33363. #if SQLITE_OS_WINCE
  33364. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  33365. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  33366. ){
  33367. osCloseHandle(h);
  33368. sqlite3_free(zConverted);
  33369. sqlite3_free(zTmpname);
  33370. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  33371. return rc;
  33372. }
  33373. if( isTemp ){
  33374. pFile->zDeleteOnClose = zConverted;
  33375. }else
  33376. #endif
  33377. {
  33378. sqlite3_free(zConverted);
  33379. }
  33380. sqlite3_free(zTmpname);
  33381. pFile->pMethod = &winIoMethod;
  33382. pFile->pVfs = pVfs;
  33383. pFile->h = h;
  33384. if( isReadonly ){
  33385. pFile->ctrlFlags |= WINFILE_RDONLY;
  33386. }
  33387. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33388. pFile->ctrlFlags |= WINFILE_PSOW;
  33389. }
  33390. pFile->lastErrno = NO_ERROR;
  33391. pFile->zPath = zName;
  33392. #if SQLITE_MAX_MMAP_SIZE>0
  33393. pFile->hMap = NULL;
  33394. pFile->pMapRegion = 0;
  33395. pFile->mmapSize = 0;
  33396. pFile->mmapSizeActual = 0;
  33397. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33398. #endif
  33399. OpenCounter(+1);
  33400. return rc;
  33401. }
  33402. /*
  33403. ** Delete the named file.
  33404. **
  33405. ** Note that Windows does not allow a file to be deleted if some other
  33406. ** process has it open. Sometimes a virus scanner or indexing program
  33407. ** will open a journal file shortly after it is created in order to do
  33408. ** whatever it does. While this other process is holding the
  33409. ** file open, we will be unable to delete it. To work around this
  33410. ** problem, we delay 100 milliseconds and try to delete again. Up
  33411. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  33412. ** up and returning an error.
  33413. */
  33414. static int winDelete(
  33415. sqlite3_vfs *pVfs, /* Not used on win32 */
  33416. const char *zFilename, /* Name of file to delete */
  33417. int syncDir /* Not used on win32 */
  33418. ){
  33419. int cnt = 0;
  33420. int rc;
  33421. DWORD attr;
  33422. DWORD lastErrno;
  33423. void *zConverted;
  33424. UNUSED_PARAMETER(pVfs);
  33425. UNUSED_PARAMETER(syncDir);
  33426. SimulateIOError(return SQLITE_IOERR_DELETE);
  33427. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  33428. zConverted = winConvertFromUtf8Filename(zFilename);
  33429. if( zConverted==0 ){
  33430. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33431. return SQLITE_IOERR_NOMEM;
  33432. }
  33433. if( osIsNT() ){
  33434. do {
  33435. #if SQLITE_OS_WINRT
  33436. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33437. memset(&sAttrData, 0, sizeof(sAttrData));
  33438. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  33439. &sAttrData) ){
  33440. attr = sAttrData.dwFileAttributes;
  33441. }else{
  33442. lastErrno = osGetLastError();
  33443. if( lastErrno==ERROR_FILE_NOT_FOUND
  33444. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33445. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33446. }else{
  33447. rc = SQLITE_ERROR;
  33448. }
  33449. break;
  33450. }
  33451. #else
  33452. attr = osGetFileAttributesW(zConverted);
  33453. #endif
  33454. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33455. lastErrno = osGetLastError();
  33456. if( lastErrno==ERROR_FILE_NOT_FOUND
  33457. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33458. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33459. }else{
  33460. rc = SQLITE_ERROR;
  33461. }
  33462. break;
  33463. }
  33464. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33465. rc = SQLITE_ERROR; /* Files only. */
  33466. break;
  33467. }
  33468. if ( osDeleteFileW(zConverted) ){
  33469. rc = SQLITE_OK; /* Deleted OK. */
  33470. break;
  33471. }
  33472. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33473. rc = SQLITE_ERROR; /* No more retries. */
  33474. break;
  33475. }
  33476. } while(1);
  33477. }
  33478. #ifdef SQLITE_WIN32_HAS_ANSI
  33479. else{
  33480. do {
  33481. attr = osGetFileAttributesA(zConverted);
  33482. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33483. lastErrno = osGetLastError();
  33484. if( lastErrno==ERROR_FILE_NOT_FOUND
  33485. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33486. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33487. }else{
  33488. rc = SQLITE_ERROR;
  33489. }
  33490. break;
  33491. }
  33492. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33493. rc = SQLITE_ERROR; /* Files only. */
  33494. break;
  33495. }
  33496. if ( osDeleteFileA(zConverted) ){
  33497. rc = SQLITE_OK; /* Deleted OK. */
  33498. break;
  33499. }
  33500. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33501. rc = SQLITE_ERROR; /* No more retries. */
  33502. break;
  33503. }
  33504. } while(1);
  33505. }
  33506. #endif
  33507. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  33508. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  33509. }else{
  33510. winLogIoerr(cnt);
  33511. }
  33512. sqlite3_free(zConverted);
  33513. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  33514. return rc;
  33515. }
  33516. /*
  33517. ** Check the existence and status of a file.
  33518. */
  33519. static int winAccess(
  33520. sqlite3_vfs *pVfs, /* Not used on win32 */
  33521. const char *zFilename, /* Name of file to check */
  33522. int flags, /* Type of test to make on this file */
  33523. int *pResOut /* OUT: Result */
  33524. ){
  33525. DWORD attr;
  33526. int rc = 0;
  33527. DWORD lastErrno;
  33528. void *zConverted;
  33529. UNUSED_PARAMETER(pVfs);
  33530. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  33531. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  33532. zFilename, flags, pResOut));
  33533. zConverted = winConvertFromUtf8Filename(zFilename);
  33534. if( zConverted==0 ){
  33535. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33536. return SQLITE_IOERR_NOMEM;
  33537. }
  33538. if( osIsNT() ){
  33539. int cnt = 0;
  33540. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33541. memset(&sAttrData, 0, sizeof(sAttrData));
  33542. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  33543. GetFileExInfoStandard,
  33544. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  33545. if( rc ){
  33546. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  33547. ** as if it does not exist.
  33548. */
  33549. if( flags==SQLITE_ACCESS_EXISTS
  33550. && sAttrData.nFileSizeHigh==0
  33551. && sAttrData.nFileSizeLow==0 ){
  33552. attr = INVALID_FILE_ATTRIBUTES;
  33553. }else{
  33554. attr = sAttrData.dwFileAttributes;
  33555. }
  33556. }else{
  33557. winLogIoerr(cnt);
  33558. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  33559. sqlite3_free(zConverted);
  33560. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  33561. zFilename);
  33562. }else{
  33563. attr = INVALID_FILE_ATTRIBUTES;
  33564. }
  33565. }
  33566. }
  33567. #ifdef SQLITE_WIN32_HAS_ANSI
  33568. else{
  33569. attr = osGetFileAttributesA((char*)zConverted);
  33570. }
  33571. #endif
  33572. sqlite3_free(zConverted);
  33573. switch( flags ){
  33574. case SQLITE_ACCESS_READ:
  33575. case SQLITE_ACCESS_EXISTS:
  33576. rc = attr!=INVALID_FILE_ATTRIBUTES;
  33577. break;
  33578. case SQLITE_ACCESS_READWRITE:
  33579. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  33580. (attr & FILE_ATTRIBUTE_READONLY)==0;
  33581. break;
  33582. default:
  33583. assert(!"Invalid flags argument");
  33584. }
  33585. *pResOut = rc;
  33586. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  33587. zFilename, pResOut, *pResOut));
  33588. return SQLITE_OK;
  33589. }
  33590. /*
  33591. ** Returns non-zero if the specified path name starts with a drive letter
  33592. ** followed by a colon character.
  33593. */
  33594. static BOOL winIsDriveLetterAndColon(
  33595. const char *zPathname
  33596. ){
  33597. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  33598. }
  33599. /*
  33600. ** Returns non-zero if the specified path name should be used verbatim. If
  33601. ** non-zero is returned from this function, the calling function must simply
  33602. ** use the provided path name verbatim -OR- resolve it into a full path name
  33603. ** using the GetFullPathName Win32 API function (if available).
  33604. */
  33605. static BOOL winIsVerbatimPathname(
  33606. const char *zPathname
  33607. ){
  33608. /*
  33609. ** If the path name starts with a forward slash or a backslash, it is either
  33610. ** a legal UNC name, a volume relative path, or an absolute path name in the
  33611. ** "Unix" format on Windows. There is no easy way to differentiate between
  33612. ** the final two cases; therefore, we return the safer return value of TRUE
  33613. ** so that callers of this function will simply use it verbatim.
  33614. */
  33615. if ( winIsDirSep(zPathname[0]) ){
  33616. return TRUE;
  33617. }
  33618. /*
  33619. ** If the path name starts with a letter and a colon it is either a volume
  33620. ** relative path or an absolute path. Callers of this function must not
  33621. ** attempt to treat it as a relative path name (i.e. they should simply use
  33622. ** it verbatim).
  33623. */
  33624. if ( winIsDriveLetterAndColon(zPathname) ){
  33625. return TRUE;
  33626. }
  33627. /*
  33628. ** If we get to this point, the path name should almost certainly be a purely
  33629. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  33630. */
  33631. return FALSE;
  33632. }
  33633. /*
  33634. ** Turn a relative pathname into a full pathname. Write the full
  33635. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  33636. ** bytes in size.
  33637. */
  33638. static int winFullPathname(
  33639. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33640. const char *zRelative, /* Possibly relative input path */
  33641. int nFull, /* Size of output buffer in bytes */
  33642. char *zFull /* Output buffer */
  33643. ){
  33644. #if defined(__CYGWIN__)
  33645. SimulateIOError( return SQLITE_ERROR );
  33646. UNUSED_PARAMETER(nFull);
  33647. assert( nFull>=pVfs->mxPathname );
  33648. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33649. /*
  33650. ** NOTE: We are dealing with a relative path name and the data
  33651. ** directory has been set. Therefore, use it as the basis
  33652. ** for converting the relative path name to an absolute
  33653. ** one by prepending the data directory and a slash.
  33654. */
  33655. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  33656. if( !zOut ){
  33657. return SQLITE_IOERR_NOMEM;
  33658. }
  33659. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  33660. pVfs->mxPathname+1)<0 ){
  33661. sqlite3_free(zOut);
  33662. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33663. "winFullPathname1", zRelative);
  33664. }
  33665. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33666. sqlite3_data_directory, winGetDirDep(), zOut);
  33667. sqlite3_free(zOut);
  33668. }else{
  33669. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
  33670. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33671. "winFullPathname2", zRelative);
  33672. }
  33673. }
  33674. return SQLITE_OK;
  33675. #endif
  33676. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  33677. SimulateIOError( return SQLITE_ERROR );
  33678. /* WinCE has no concept of a relative pathname, or so I am told. */
  33679. /* WinRT has no way to convert a relative path to an absolute one. */
  33680. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33681. /*
  33682. ** NOTE: We are dealing with a relative path name and the data
  33683. ** directory has been set. Therefore, use it as the basis
  33684. ** for converting the relative path name to an absolute
  33685. ** one by prepending the data directory and a backslash.
  33686. */
  33687. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33688. sqlite3_data_directory, winGetDirDep(), zRelative);
  33689. }else{
  33690. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  33691. }
  33692. return SQLITE_OK;
  33693. #endif
  33694. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  33695. DWORD nByte;
  33696. void *zConverted;
  33697. char *zOut;
  33698. /* If this path name begins with "/X:", where "X" is any alphabetic
  33699. ** character, discard the initial "/" from the pathname.
  33700. */
  33701. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  33702. zRelative++;
  33703. }
  33704. /* It's odd to simulate an io-error here, but really this is just
  33705. ** using the io-error infrastructure to test that SQLite handles this
  33706. ** function failing. This function could fail if, for example, the
  33707. ** current working directory has been unlinked.
  33708. */
  33709. SimulateIOError( return SQLITE_ERROR );
  33710. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33711. /*
  33712. ** NOTE: We are dealing with a relative path name and the data
  33713. ** directory has been set. Therefore, use it as the basis
  33714. ** for converting the relative path name to an absolute
  33715. ** one by prepending the data directory and a backslash.
  33716. */
  33717. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33718. sqlite3_data_directory, winGetDirDep(), zRelative);
  33719. return SQLITE_OK;
  33720. }
  33721. zConverted = winConvertFromUtf8Filename(zRelative);
  33722. if( zConverted==0 ){
  33723. return SQLITE_IOERR_NOMEM;
  33724. }
  33725. if( osIsNT() ){
  33726. LPWSTR zTemp;
  33727. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  33728. if( nByte==0 ){
  33729. sqlite3_free(zConverted);
  33730. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33731. "winFullPathname1", zRelative);
  33732. }
  33733. nByte += 3;
  33734. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33735. if( zTemp==0 ){
  33736. sqlite3_free(zConverted);
  33737. return SQLITE_IOERR_NOMEM;
  33738. }
  33739. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  33740. if( nByte==0 ){
  33741. sqlite3_free(zConverted);
  33742. sqlite3_free(zTemp);
  33743. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33744. "winFullPathname2", zRelative);
  33745. }
  33746. sqlite3_free(zConverted);
  33747. zOut = winUnicodeToUtf8(zTemp);
  33748. sqlite3_free(zTemp);
  33749. }
  33750. #ifdef SQLITE_WIN32_HAS_ANSI
  33751. else{
  33752. char *zTemp;
  33753. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  33754. if( nByte==0 ){
  33755. sqlite3_free(zConverted);
  33756. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33757. "winFullPathname3", zRelative);
  33758. }
  33759. nByte += 3;
  33760. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33761. if( zTemp==0 ){
  33762. sqlite3_free(zConverted);
  33763. return SQLITE_IOERR_NOMEM;
  33764. }
  33765. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  33766. if( nByte==0 ){
  33767. sqlite3_free(zConverted);
  33768. sqlite3_free(zTemp);
  33769. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33770. "winFullPathname4", zRelative);
  33771. }
  33772. sqlite3_free(zConverted);
  33773. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33774. sqlite3_free(zTemp);
  33775. }
  33776. #endif
  33777. if( zOut ){
  33778. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  33779. sqlite3_free(zOut);
  33780. return SQLITE_OK;
  33781. }else{
  33782. return SQLITE_IOERR_NOMEM;
  33783. }
  33784. #endif
  33785. }
  33786. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33787. /*
  33788. ** Interfaces for opening a shared library, finding entry points
  33789. ** within the shared library, and closing the shared library.
  33790. */
  33791. /*
  33792. ** Interfaces for opening a shared library, finding entry points
  33793. ** within the shared library, and closing the shared library.
  33794. */
  33795. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  33796. HANDLE h;
  33797. void *zConverted = winConvertFromUtf8Filename(zFilename);
  33798. UNUSED_PARAMETER(pVfs);
  33799. if( zConverted==0 ){
  33800. return 0;
  33801. }
  33802. if( osIsNT() ){
  33803. #if SQLITE_OS_WINRT
  33804. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  33805. #else
  33806. h = osLoadLibraryW((LPCWSTR)zConverted);
  33807. #endif
  33808. }
  33809. #ifdef SQLITE_WIN32_HAS_ANSI
  33810. else{
  33811. h = osLoadLibraryA((char*)zConverted);
  33812. }
  33813. #endif
  33814. sqlite3_free(zConverted);
  33815. return (void*)h;
  33816. }
  33817. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  33818. UNUSED_PARAMETER(pVfs);
  33819. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  33820. }
  33821. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  33822. UNUSED_PARAMETER(pVfs);
  33823. return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
  33824. }
  33825. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  33826. UNUSED_PARAMETER(pVfs);
  33827. osFreeLibrary((HANDLE)pHandle);
  33828. }
  33829. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  33830. #define winDlOpen 0
  33831. #define winDlError 0
  33832. #define winDlSym 0
  33833. #define winDlClose 0
  33834. #endif
  33835. /*
  33836. ** Write up to nBuf bytes of randomness into zBuf.
  33837. */
  33838. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33839. int n = 0;
  33840. UNUSED_PARAMETER(pVfs);
  33841. #if defined(SQLITE_TEST)
  33842. n = nBuf;
  33843. memset(zBuf, 0, nBuf);
  33844. #else
  33845. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  33846. SYSTEMTIME x;
  33847. osGetSystemTime(&x);
  33848. memcpy(&zBuf[n], &x, sizeof(x));
  33849. n += sizeof(x);
  33850. }
  33851. if( sizeof(DWORD)<=nBuf-n ){
  33852. DWORD pid = osGetCurrentProcessId();
  33853. memcpy(&zBuf[n], &pid, sizeof(pid));
  33854. n += sizeof(pid);
  33855. }
  33856. #if SQLITE_OS_WINRT
  33857. if( sizeof(ULONGLONG)<=nBuf-n ){
  33858. ULONGLONG cnt = osGetTickCount64();
  33859. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33860. n += sizeof(cnt);
  33861. }
  33862. #else
  33863. if( sizeof(DWORD)<=nBuf-n ){
  33864. DWORD cnt = osGetTickCount();
  33865. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33866. n += sizeof(cnt);
  33867. }
  33868. #endif
  33869. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  33870. LARGE_INTEGER i;
  33871. osQueryPerformanceCounter(&i);
  33872. memcpy(&zBuf[n], &i, sizeof(i));
  33873. n += sizeof(i);
  33874. }
  33875. #endif
  33876. return n;
  33877. }
  33878. /*
  33879. ** Sleep for a little while. Return the amount of time slept.
  33880. */
  33881. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  33882. sqlite3_win32_sleep((microsec+999)/1000);
  33883. UNUSED_PARAMETER(pVfs);
  33884. return ((microsec+999)/1000)*1000;
  33885. }
  33886. /*
  33887. ** The following variable, if set to a non-zero value, is interpreted as
  33888. ** the number of seconds since 1970 and is used to set the result of
  33889. ** sqlite3OsCurrentTime() during testing.
  33890. */
  33891. #ifdef SQLITE_TEST
  33892. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  33893. #endif
  33894. /*
  33895. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  33896. ** the current time and date as a Julian Day number times 86_400_000. In
  33897. ** other words, write into *piNow the number of milliseconds since the Julian
  33898. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  33899. ** proleptic Gregorian calendar.
  33900. **
  33901. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  33902. ** cannot be found.
  33903. */
  33904. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  33905. /* FILETIME structure is a 64-bit value representing the number of
  33906. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  33907. */
  33908. FILETIME ft;
  33909. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  33910. #ifdef SQLITE_TEST
  33911. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  33912. #endif
  33913. /* 2^32 - to avoid use of LL and warnings in gcc */
  33914. static const sqlite3_int64 max32BitValue =
  33915. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  33916. (sqlite3_int64)294967296;
  33917. #if SQLITE_OS_WINCE
  33918. SYSTEMTIME time;
  33919. osGetSystemTime(&time);
  33920. /* if SystemTimeToFileTime() fails, it returns zero. */
  33921. if (!osSystemTimeToFileTime(&time,&ft)){
  33922. return SQLITE_ERROR;
  33923. }
  33924. #else
  33925. osGetSystemTimeAsFileTime( &ft );
  33926. #endif
  33927. *piNow = winFiletimeEpoch +
  33928. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  33929. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  33930. #ifdef SQLITE_TEST
  33931. if( sqlite3_current_time ){
  33932. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  33933. }
  33934. #endif
  33935. UNUSED_PARAMETER(pVfs);
  33936. return SQLITE_OK;
  33937. }
  33938. /*
  33939. ** Find the current time (in Universal Coordinated Time). Write the
  33940. ** current time and date as a Julian Day number into *prNow and
  33941. ** return 0. Return 1 if the time and date cannot be found.
  33942. */
  33943. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  33944. int rc;
  33945. sqlite3_int64 i;
  33946. rc = winCurrentTimeInt64(pVfs, &i);
  33947. if( !rc ){
  33948. *prNow = i/86400000.0;
  33949. }
  33950. return rc;
  33951. }
  33952. /*
  33953. ** The idea is that this function works like a combination of
  33954. ** GetLastError() and FormatMessage() on Windows (or errno and
  33955. ** strerror_r() on Unix). After an error is returned by an OS
  33956. ** function, SQLite calls this function with zBuf pointing to
  33957. ** a buffer of nBuf bytes. The OS layer should populate the
  33958. ** buffer with a nul-terminated UTF-8 encoded error message
  33959. ** describing the last IO error to have occurred within the calling
  33960. ** thread.
  33961. **
  33962. ** If the error message is too large for the supplied buffer,
  33963. ** it should be truncated. The return value of xGetLastError
  33964. ** is zero if the error message fits in the buffer, or non-zero
  33965. ** otherwise (if the message was truncated). If non-zero is returned,
  33966. ** then it is not necessary to include the nul-terminator character
  33967. ** in the output buffer.
  33968. **
  33969. ** Not supplying an error message will have no adverse effect
  33970. ** on SQLite. It is fine to have an implementation that never
  33971. ** returns an error message:
  33972. **
  33973. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33974. ** assert(zBuf[0]=='\0');
  33975. ** return 0;
  33976. ** }
  33977. **
  33978. ** However if an error message is supplied, it will be incorporated
  33979. ** by sqlite into the error message available to the user using
  33980. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  33981. */
  33982. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33983. UNUSED_PARAMETER(pVfs);
  33984. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  33985. }
  33986. /*
  33987. ** Initialize and deinitialize the operating system interface.
  33988. */
  33989. SQLITE_API int sqlite3_os_init(void){
  33990. static sqlite3_vfs winVfs = {
  33991. 3, /* iVersion */
  33992. sizeof(winFile), /* szOsFile */
  33993. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  33994. 0, /* pNext */
  33995. "win32", /* zName */
  33996. 0, /* pAppData */
  33997. winOpen, /* xOpen */
  33998. winDelete, /* xDelete */
  33999. winAccess, /* xAccess */
  34000. winFullPathname, /* xFullPathname */
  34001. winDlOpen, /* xDlOpen */
  34002. winDlError, /* xDlError */
  34003. winDlSym, /* xDlSym */
  34004. winDlClose, /* xDlClose */
  34005. winRandomness, /* xRandomness */
  34006. winSleep, /* xSleep */
  34007. winCurrentTime, /* xCurrentTime */
  34008. winGetLastError, /* xGetLastError */
  34009. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  34010. winSetSystemCall, /* xSetSystemCall */
  34011. winGetSystemCall, /* xGetSystemCall */
  34012. winNextSystemCall, /* xNextSystemCall */
  34013. };
  34014. #if defined(SQLITE_WIN32_HAS_WIDE)
  34015. static sqlite3_vfs winLongPathVfs = {
  34016. 3, /* iVersion */
  34017. sizeof(winFile), /* szOsFile */
  34018. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  34019. 0, /* pNext */
  34020. "win32-longpath", /* zName */
  34021. 0, /* pAppData */
  34022. winOpen, /* xOpen */
  34023. winDelete, /* xDelete */
  34024. winAccess, /* xAccess */
  34025. winFullPathname, /* xFullPathname */
  34026. winDlOpen, /* xDlOpen */
  34027. winDlError, /* xDlError */
  34028. winDlSym, /* xDlSym */
  34029. winDlClose, /* xDlClose */
  34030. winRandomness, /* xRandomness */
  34031. winSleep, /* xSleep */
  34032. winCurrentTime, /* xCurrentTime */
  34033. winGetLastError, /* xGetLastError */
  34034. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  34035. winSetSystemCall, /* xSetSystemCall */
  34036. winGetSystemCall, /* xGetSystemCall */
  34037. winNextSystemCall, /* xNextSystemCall */
  34038. };
  34039. #endif
  34040. /* Double-check that the aSyscall[] array has been constructed
  34041. ** correctly. See ticket [bb3a86e890c8e96ab] */
  34042. assert( ArraySize(aSyscall)==75 );
  34043. /* get memory map allocation granularity */
  34044. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  34045. #if SQLITE_OS_WINRT
  34046. osGetNativeSystemInfo(&winSysInfo);
  34047. #else
  34048. osGetSystemInfo(&winSysInfo);
  34049. #endif
  34050. assert( winSysInfo.dwAllocationGranularity>0 );
  34051. assert( winSysInfo.dwPageSize>0 );
  34052. sqlite3_vfs_register(&winVfs, 1);
  34053. #if defined(SQLITE_WIN32_HAS_WIDE)
  34054. sqlite3_vfs_register(&winLongPathVfs, 0);
  34055. #endif
  34056. return SQLITE_OK;
  34057. }
  34058. SQLITE_API int sqlite3_os_end(void){
  34059. #if SQLITE_OS_WINRT
  34060. if( sleepObj!=NULL ){
  34061. osCloseHandle(sleepObj);
  34062. sleepObj = NULL;
  34063. }
  34064. #endif
  34065. return SQLITE_OK;
  34066. }
  34067. #endif /* SQLITE_OS_WIN */
  34068. /************** End of os_win.c **********************************************/
  34069. /************** Begin file os_rtt.c ******************************************/
  34070. /*
  34071. ** 2004 May 22
  34072. **
  34073. ** The author disclaims copyright to this source code. In place of
  34074. ** a legal notice, here is a blessing:
  34075. **
  34076. ** May you do good and not evil.
  34077. ** May you find forgiveness for yourself and forgive others.
  34078. ** May you share freely, never taking more than you give.
  34079. **
  34080. ******************************************************************************
  34081. **
  34082. ** This file contains code that is specific to Windows.
  34083. */
  34084. #if SQLITE_OS_RTT /* This file is used for rt-thread only */
  34085. /* #include <rtthread.h> */
  34086. /*
  34087. ** Include code that is common to all os_*.c files
  34088. */
  34089. /************** Include os_common.h in the middle of os_rtt.c ****************/
  34090. /************** Begin file os_common.h ***************************************/
  34091. /*
  34092. ** 2004 May 22
  34093. **
  34094. ** The author disclaims copyright to this source code. In place of
  34095. ** a legal notice, here is a blessing:
  34096. **
  34097. ** May you do good and not evil.
  34098. ** May you find forgiveness for yourself and forgive others.
  34099. ** May you share freely, never taking more than you give.
  34100. **
  34101. ******************************************************************************
  34102. **
  34103. ** This file contains macros and a little bit of code that is common to
  34104. ** all of the platform-specific files (os_*.c) and is #included into those
  34105. ** files.
  34106. **
  34107. ** This file should be #included by the os_*.c files only. It is not a
  34108. ** general purpose header file.
  34109. */
  34110. #ifndef _OS_COMMON_H_
  34111. #define _OS_COMMON_H_
  34112. /*
  34113. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  34114. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  34115. ** switch. The following code should catch this problem at compile-time.
  34116. */
  34117. #ifdef MEMORY_DEBUG
  34118. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  34119. #endif
  34120. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  34121. # ifndef SQLITE_DEBUG_OS_TRACE
  34122. # define SQLITE_DEBUG_OS_TRACE 0
  34123. # endif
  34124. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  34125. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  34126. #else
  34127. # define OSTRACE(X)
  34128. #endif
  34129. /*
  34130. ** Macros for performance tracing. Normally turned off. Only works
  34131. ** on i486 hardware.
  34132. */
  34133. #ifdef SQLITE_PERFORMANCE_TRACE
  34134. /*
  34135. ** hwtime.h contains inline assembler code for implementing
  34136. ** high-performance timing routines.
  34137. */
  34138. /************** Include hwtime.h in the middle of os_common.h ****************/
  34139. /************** Begin file hwtime.h ******************************************/
  34140. /*
  34141. ** 2008 May 27
  34142. **
  34143. ** The author disclaims copyright to this source code. In place of
  34144. ** a legal notice, here is a blessing:
  34145. **
  34146. ** May you do good and not evil.
  34147. ** May you find forgiveness for yourself and forgive others.
  34148. ** May you share freely, never taking more than you give.
  34149. **
  34150. ******************************************************************************
  34151. **
  34152. ** This file contains inline asm code for retrieving "high-performance"
  34153. ** counters for x86 class CPUs.
  34154. */
  34155. #ifndef _HWTIME_H_
  34156. #define _HWTIME_H_
  34157. /*
  34158. ** The following routine only works on pentium-class (or newer) processors.
  34159. ** It uses the RDTSC opcode to read the cycle count value out of the
  34160. ** processor and returns that value. This can be used for high-res
  34161. ** profiling.
  34162. */
  34163. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  34164. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  34165. #if defined(__GNUC__)
  34166. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34167. unsigned int lo, hi;
  34168. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  34169. return (sqlite_uint64)hi << 32 | lo;
  34170. }
  34171. #elif defined(_MSC_VER)
  34172. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  34173. __asm {
  34174. rdtsc
  34175. ret ; return value at EDX:EAX
  34176. }
  34177. }
  34178. #endif
  34179. #elif (defined(__GNUC__) && defined(__x86_64__))
  34180. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34181. unsigned long val;
  34182. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  34183. return val;
  34184. }
  34185. #elif (defined(__GNUC__) && defined(__ppc__))
  34186. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34187. unsigned long long retval;
  34188. unsigned long junk;
  34189. __asm__ __volatile__ ("\n\
  34190. 1: mftbu %1\n\
  34191. mftb %L0\n\
  34192. mftbu %0\n\
  34193. cmpw %0,%1\n\
  34194. bne 1b"
  34195. : "=r" (retval), "=r" (junk));
  34196. return retval;
  34197. }
  34198. #else
  34199. #error Need implementation of sqlite3Hwtime() for your platform.
  34200. /*
  34201. ** To compile without implementing sqlite3Hwtime() for your platform,
  34202. ** you can remove the above #error and use the following
  34203. ** stub function. You will lose timing support for many
  34204. ** of the debugging and testing utilities, but it should at
  34205. ** least compile and run.
  34206. */
  34207. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  34208. #endif
  34209. #endif /* !defined(_HWTIME_H_) */
  34210. /************** End of hwtime.h **********************************************/
  34211. /************** Continuing where we left off in os_common.h ******************/
  34212. static sqlite_uint64 g_start;
  34213. static sqlite_uint64 g_elapsed;
  34214. #define TIMER_START g_start=sqlite3Hwtime()
  34215. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  34216. #define TIMER_ELAPSED g_elapsed
  34217. #else
  34218. #define TIMER_START
  34219. #define TIMER_END
  34220. #define TIMER_ELAPSED ((sqlite_uint64)0)
  34221. #endif
  34222. /*
  34223. ** If we compile with the SQLITE_TEST macro set, then the following block
  34224. ** of code will give us the ability to simulate a disk I/O error. This
  34225. ** is used for testing the I/O recovery logic.
  34226. */
  34227. #ifdef SQLITE_TEST
  34228. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  34229. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  34230. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  34231. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  34232. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  34233. SQLITE_API int sqlite3_diskfull_pending = 0;
  34234. SQLITE_API int sqlite3_diskfull = 0;
  34235. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  34236. #define SimulateIOError(CODE) \
  34237. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  34238. || sqlite3_io_error_pending-- == 1 ) \
  34239. { local_ioerr(); CODE; }
  34240. static void local_ioerr(){
  34241. IOTRACE(("IOERR\n"));
  34242. sqlite3_io_error_hit++;
  34243. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  34244. }
  34245. #define SimulateDiskfullError(CODE) \
  34246. if( sqlite3_diskfull_pending ){ \
  34247. if( sqlite3_diskfull_pending == 1 ){ \
  34248. local_ioerr(); \
  34249. sqlite3_diskfull = 1; \
  34250. sqlite3_io_error_hit = 1; \
  34251. CODE; \
  34252. }else{ \
  34253. sqlite3_diskfull_pending--; \
  34254. } \
  34255. }
  34256. #else
  34257. #define SimulateIOErrorBenign(X)
  34258. #define SimulateIOError(A)
  34259. #define SimulateDiskfullError(A)
  34260. #endif
  34261. /*
  34262. ** When testing, keep a count of the number of open files.
  34263. */
  34264. #ifdef SQLITE_TEST
  34265. SQLITE_API int sqlite3_open_file_count = 0;
  34266. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  34267. #else
  34268. #define OpenCounter(X)
  34269. #endif
  34270. #endif /* !defined(_OS_COMMON_H_) */
  34271. /************** End of os_common.h *******************************************/
  34272. /************** Continuing where we left off in os_rtt.c *********************/
  34273. /*
  34274. ** Compiling and using WAL mode requires several APIs that are not
  34275. ** available in rt-thread.
  34276. */
  34277. #if !defined(SQLITE_OMIT_WAL)
  34278. # error "WAL mode requires not support from the rt-thread, compile\
  34279. with SQLITE_OMIT_WAL."
  34280. #endif
  34281. /*
  34282. ** Are most of the rtt ANSI APIs available (i.e. with certain exceptions
  34283. ** based on the sub-platform)?
  34284. */
  34285. #if !defined(SQLITE_RTT_NO_ANSI)
  34286. # warning "please ensure rtt ANSI APIs is available, otherwise compile with\
  34287. SQLITE_RTT_NO_ANSI"
  34288. # define SQLITE_RTT_HAS_ANSI
  34289. #endif
  34290. /*
  34291. ** Are most of the rtt Unicode APIs available (i.e. with certain exceptions
  34292. ** based on the sub-platform)?
  34293. */
  34294. #if !defined(SQLITE_RTT_NO_WIDE)
  34295. # error "rtt not support Unicode APIs"
  34296. # define SQLITE_RTT_HAS_WIDE
  34297. #endif
  34298. /*
  34299. ** Make sure at least one set of rtt APIs is available.
  34300. */
  34301. #if !defined(SQLITE_RTT_HAS_ANSI) && !defined(SQLITE_RTT_HAS_WIDE)
  34302. # error "At least one of SQLITE_RTT_HAS_ANSI and SQLITE_RTT_HAS_WIDE\
  34303. must be defined."
  34304. #endif
  34305. /*
  34306. ** Maximum pathname length (in chars) for rtt. This should normally be
  34307. ** MAX_PATH.
  34308. */
  34309. #ifndef SQLITE_RTT_MAX_PATH_CHARS
  34310. # warning "default Maximum pathname length be 255, otherwise compile with\
  34311. SQLITE_RTT_MAX_PATH_CHARS=?"
  34312. # define SQLITE_RTT_MAX_PATH_CHARS (255)
  34313. #endif
  34314. /*
  34315. ** Maximum supported path-length.
  34316. */
  34317. #define MAX_PATHNAME 512
  34318. /*
  34319. ** Returns non-zero if the character should be treated as a directory
  34320. ** separator.
  34321. */
  34322. #ifndef rttIsDirSep
  34323. # define rttIsDirSep(a) ((a) == '/')
  34324. #endif
  34325. /*
  34326. ** This macro is used when a local variable is set to a value that is
  34327. ** [sometimes] not used by the code (e.g. via conditional compilation).
  34328. */
  34329. #ifndef UNUSED_VARIABLE_VALUE
  34330. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  34331. #endif
  34332. /*
  34333. ** Returns the string that should be used as the directory separator.
  34334. */
  34335. #ifndef rttGetDirDep
  34336. # define rttGetDirDep() "/"
  34337. #endif
  34338. /*
  34339. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  34340. ** portability layer.
  34341. */
  34342. typedef struct rttFile rttFile;
  34343. struct rttFile {
  34344. sqlite3_io_methods const *pMethod; /* Always the first entry */
  34345. sqlite3_vfs *pVfs; /* The VFS that created this rttFile */
  34346. int h; /* The file descriptor */
  34347. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  34348. unsigned char eFileLock; /* The type of lock held on this fd */
  34349. int lastErrno; /* The unix errno from last I/O error */
  34350. void *lockingContext; /* Locking style specific state */
  34351. const char *zPath; /* Name of the file */
  34352. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  34353. #if SQLITE_ENABLE_LOCKING_STYLE
  34354. int openFlags; /* The flags specified at open() */
  34355. #endif
  34356. #if SQLITE_ENABLE_LOCKING_STYLE
  34357. unsigned fsFlags; /* cached details from statfs() */
  34358. #endif
  34359. #ifdef SQLITE_DEBUG
  34360. /* The next group of variables are used to track whether or not the
  34361. ** transaction counter in bytes 24-27 of database files are updated
  34362. ** whenever any part of the database changes. An assertion fault will
  34363. ** occur if a file is updated without also updating the transaction
  34364. ** counter. This test is made to avoid new problems similar to the
  34365. ** one described by ticket #3584.
  34366. */
  34367. unsigned char transCntrChng; /* True if the transaction counter changed */
  34368. unsigned char dbUpdate; /* True if any part of database file changed */
  34369. unsigned char inNormalWrite; /* True if in a normal write operation */
  34370. #endif
  34371. #ifdef SQLITE_TEST
  34372. /* In test mode, increase the size of this structure a bit so that
  34373. ** it is larger than the struct CrashFile defined in test6.c.
  34374. */
  34375. char aPadding[32];
  34376. #endif
  34377. };
  34378. /*
  34379. ** Allowed values for the rttFile.ctrlFlags bitmask:
  34380. */
  34381. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  34382. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  34383. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  34384. #ifndef SQLITE_DISABLE_DIRSYNC
  34385. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  34386. #else
  34387. # define UNIXFILE_DIRSYNC 0x00
  34388. #endif
  34389. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  34390. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  34391. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  34392. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  34393. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  34394. /*
  34395. ** The following variable is (normally) set once and never changes
  34396. ** thereafter. It records whether the operating system is Win9x
  34397. ** or WinNT.
  34398. **
  34399. ** 0: Operating system unknown.
  34400. ** 1: Operating system is rtt.
  34401. **
  34402. ** In order to facilitate testing on a rtt system, the test fixture
  34403. ** can manually set this value to 1 to emulate Win98 behavior.
  34404. */
  34405. #ifdef SQLITE_TEST
  34406. SQLITE_API int sqlite3_os_type = 0;
  34407. #elif !SQLITE_OS_RTT && \
  34408. defined(SQLITE_RTT_HAS_ANSI) && defined(SQLITE_RTT_HAS_WIDE)
  34409. static int sqlite3_os_type = 0;
  34410. #endif
  34411. #ifndef SYSCALL
  34412. # define SYSCALL sqlite3_syscall_ptr
  34413. #endif
  34414. #include <dfs_posix.h>
  34415. static int _Access(const char *pathname, int mode)
  34416. {
  34417. int fd;
  34418. fd = open(pathname, O_RDONLY, mode);
  34419. if (fd >= 0)
  34420. {
  34421. close(fd);
  34422. return 0;
  34423. }
  34424. return -1;
  34425. }
  34426. /*
  34427. ** Invoke open(). Do so multiple times, until it either succeeds or
  34428. ** fails for some reason other than EINTR.
  34429. **
  34430. ** If the file creation mode "m" is 0 then set it to the default for
  34431. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  34432. ** 0644) as modified by the system umask. If m is not 0, then
  34433. ** make the file creation mode be exactly m ignoring the umask.
  34434. **
  34435. ** The m parameter will be non-zero only when creating -wal, -journal,
  34436. ** and -shm files. We want those files to have *exactly* the same
  34437. ** permissions as their original database, unadulterated by the umask.
  34438. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  34439. ** transaction crashes and leaves behind hot journals, then any
  34440. ** process that is able to write to the database will also be able to
  34441. ** recover the hot journals.
  34442. */
  34443. static int robust_open(const char *z, int f, mode_t m);
  34444. /*
  34445. ** Open a file descriptor to the directory containing file zFilename.
  34446. ** If successful, *pFd is set to the opened file descriptor and
  34447. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34448. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34449. ** value.
  34450. **
  34451. ** The directory file descriptor is used for only one thing - to
  34452. ** fsync() a directory to make sure file creation and deletion events
  34453. ** are flushed to disk. Such fsyncs are not needed on newer
  34454. ** journaling filesystems, but are required on older filesystems.
  34455. **
  34456. ** This routine can be overridden using the xSetSysCall interface.
  34457. ** The ability to override this routine was added in support of the
  34458. ** chromium sandbox. Opening a directory is a security risk (we are
  34459. ** told) so making it overrideable allows the chromium sandbox to
  34460. ** replace this routine with a harmless no-op. To make this routine
  34461. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34462. ** *pFd set to a negative number.
  34463. **
  34464. ** If SQLITE_OK is returned, the caller is responsible for closing
  34465. ** the file descriptor *pFd using close().
  34466. */
  34467. static int openDirectory(const char *zFilename, int *pFd);
  34468. /*
  34469. ** Many system calls are accessed through pointer-to-functions so that
  34470. ** they may be overridden at runtime to facilitate fault injection during
  34471. ** testing and sandboxing. The following array holds the names and pointers
  34472. ** to all overrideable system calls.
  34473. */
  34474. static struct rtt_syscall {
  34475. const char *zName; /* Name of the system call */
  34476. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  34477. sqlite3_syscall_ptr pDefault; /* Default value */
  34478. } aSyscall[] = {
  34479. {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0},
  34480. #define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent)
  34481. { "open", (sqlite3_syscall_ptr)open, 0 },
  34482. #define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent)
  34483. { "close", (sqlite3_syscall_ptr)close, 0 },
  34484. #define osClose ((int(*)(int))aSyscall[2].pCurrent)
  34485. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  34486. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  34487. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  34488. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  34489. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  34490. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  34491. { "read", (sqlite3_syscall_ptr)read, 0 },
  34492. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[6].pCurrent)
  34493. { "write", (sqlite3_syscall_ptr)write, 0 },
  34494. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[7].pCurrent)
  34495. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  34496. #define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent)
  34497. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  34498. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent)
  34499. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  34500. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent)
  34501. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  34502. #define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent)
  34503. {"access", (sqlite3_syscall_ptr)_Access, 0 },
  34504. #define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent)
  34505. }; /* End of the overrideable system calls */
  34506. /*
  34507. **
  34508. ** This function - unixLogError_x(), is only ever called via the macro
  34509. ** unixLogError().
  34510. **
  34511. ** It is invoked after an error occurs in an OS function and errno has been
  34512. ** set. It logs a message using sqlite3_log() containing the current value of
  34513. ** errno and, if possible, the human-readable equivalent from strerror() or
  34514. ** strerror_r().
  34515. **
  34516. ** The first argument passed to the macro should be the error code that
  34517. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  34518. ** The two subsequent arguments should be the name of the OS function that
  34519. ** failed (e.g. "unlink", "open") and the associated file-system path,
  34520. ** if any.
  34521. */
  34522. #define rttLogError(a,b,c) rttLogErrorAtLine(a,b,c,__LINE__)
  34523. static int rttLogErrorAtLine(
  34524. int errcode, /* SQLite error code */
  34525. const char *zFunc, /* Name of OS function that failed */
  34526. const char *zPath, /* File path associated with error */
  34527. int iLine /* Source line number where error occurred */
  34528. ){
  34529. char *zErr; /* Message from strerror() or equivalent */
  34530. int iErrno = errno; /* Saved syscall error number */
  34531. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  34532. ** the strerror() function to obtain the human-readable error message
  34533. ** equivalent to errno. Otherwise, use strerror_r().
  34534. */
  34535. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  34536. char aErr[80];
  34537. memset(aErr, 0, sizeof(aErr));
  34538. zErr = aErr;
  34539. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  34540. ** assume that the system provides the GNU version of strerror_r() that
  34541. ** returns a pointer to a buffer containing the error message. That pointer
  34542. ** may point to aErr[], or it may point to some static storage somewhere.
  34543. ** Otherwise, assume that the system provides the POSIX version of
  34544. ** strerror_r(), which always writes an error message into aErr[].
  34545. **
  34546. ** If the code incorrectly assumes that it is the POSIX version that is
  34547. ** available, the error message will often be an empty string. Not a
  34548. ** huge problem. Incorrectly concluding that the GNU version is available
  34549. ** could lead to a segfault though.
  34550. */
  34551. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  34552. zErr =
  34553. # endif
  34554. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  34555. #elif SQLITE_THREADSAFE
  34556. /* This is a threadsafe build, but strerror_r() is not available. */
  34557. zErr = "";
  34558. #else
  34559. /* Non-threadsafe build, use strerror(). */
  34560. zErr = strerror(iErrno);
  34561. #endif
  34562. if( zPath==0 ) zPath = "";
  34563. sqlite3_log(errcode,
  34564. "os_rtt.c:%d: (%d) %s(%s) - %s",
  34565. iLine, iErrno, zFunc, zPath, zErr
  34566. );
  34567. return errcode;
  34568. }
  34569. /*
  34570. ** Do not accept any file descriptor less than this value, in order to avoid
  34571. ** opening database file using file descriptors that are commonly used for
  34572. ** standard input, output, and error.
  34573. */
  34574. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  34575. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  34576. #endif
  34577. /*
  34578. ** Invoke open(). Do so multiple times, until it either succeeds or
  34579. ** fails for some reason other than EINTR.
  34580. **
  34581. ** If the file creation mode "m" is 0 then set it to the default for
  34582. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  34583. ** 0644) as modified by the system umask. If m is not 0, then
  34584. ** make the file creation mode be exactly m ignoring the umask.
  34585. **
  34586. ** The m parameter will be non-zero only when creating -wal, -journal,
  34587. ** and -shm files. We want those files to have *exactly* the same
  34588. ** permissions as their original database, unadulterated by the umask.
  34589. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  34590. ** transaction crashes and leaves behind hot journals, then any
  34591. ** process that is able to write to the database will also be able to
  34592. ** recover the hot journals.
  34593. */
  34594. static int robust_open(const char *z, int f, mode_t m){
  34595. int fd;
  34596. mode_t m2 = m ;
  34597. while(1){
  34598. #if defined(O_CLOEXEC)
  34599. fd = osOpen(z,f|O_CLOEXEC,m2);
  34600. #else
  34601. fd = osOpen(z,f,m2);
  34602. #endif
  34603. if( fd<0 ){
  34604. if( errno==EINTR ) continue;
  34605. break;
  34606. }
  34607. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  34608. osClose(fd);
  34609. sqlite3_log(SQLITE_WARNING,
  34610. "attempt to open \"%s\" as file descriptor %d", z, fd);
  34611. fd = -1;
  34612. if( osOpen("/000111sql.test111000", f, m)<0 ) break;
  34613. }
  34614. return fd;
  34615. }
  34616. /*
  34617. ** Open a file descriptor to the directory containing file zFilename.
  34618. ** If successful, *pFd is set to the opened file descriptor and
  34619. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34620. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34621. ** value.
  34622. **
  34623. ** The directory file descriptor is used for only one thing - to
  34624. ** fsync() a directory to make sure file creation and deletion events
  34625. ** are flushed to disk. Such fsyncs are not needed on newer
  34626. ** journaling filesystems, but are required on older filesystems.
  34627. **
  34628. ** This routine can be overridden using the xSetSysCall interface.
  34629. ** The ability to override this routine was added in support of the
  34630. ** chromium sandbox. Opening a directory is a security risk (we are
  34631. ** told) so making it overrideable allows the chromium sandbox to
  34632. ** replace this routine with a harmless no-op. To make this routine
  34633. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34634. ** *pFd set to a negative number.
  34635. **
  34636. ** If SQLITE_OK is returned, the caller is responsible for closing
  34637. ** the file descriptor *pFd using close().
  34638. */
  34639. static int openDirectory(const char *zFilename, int *pFd){
  34640. int ii;
  34641. int fd = -1;
  34642. char zDirname[MAX_PATHNAME+1];
  34643. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  34644. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  34645. if( ii>0 ){
  34646. zDirname[ii] = '\0';
  34647. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  34648. if( fd>=0 ){
  34649. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  34650. }
  34651. }
  34652. *pFd = fd;
  34653. return (fd>=0?SQLITE_OK:rttLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  34654. }
  34655. /*
  34656. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  34657. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  34658. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  34659. ** system call named zName.
  34660. */
  34661. static int rttSetSystemCall(
  34662. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  34663. const char *zName, /* Name of system call to override */
  34664. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  34665. ){
  34666. unsigned int i;
  34667. int rc = SQLITE_NOTFOUND;
  34668. UNUSED_PARAMETER(pNotUsed);
  34669. if( zName==0 ){
  34670. /* If no zName is given, restore all system calls to their default
  34671. ** settings and return NULL
  34672. */
  34673. rc = SQLITE_OK;
  34674. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34675. if( aSyscall[i].pDefault ){
  34676. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  34677. }
  34678. }
  34679. }else{
  34680. /* If zName is specified, operate on only the one system call
  34681. ** specified.
  34682. */
  34683. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34684. if( strcmp(zName, aSyscall[i].zName)==0 ){
  34685. if( aSyscall[i].pDefault==0 ){
  34686. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  34687. }
  34688. rc = SQLITE_OK;
  34689. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  34690. aSyscall[i].pCurrent = pNewFunc;
  34691. break;
  34692. }
  34693. }
  34694. }
  34695. return rc;
  34696. }
  34697. /*
  34698. ** Return the value of a system call. Return NULL if zName is not a
  34699. ** recognized system call name. NULL is also returned if the system call
  34700. ** is currently undefined.
  34701. */
  34702. static sqlite3_syscall_ptr rttGetSystemCall(
  34703. sqlite3_vfs *pNotUsed,
  34704. const char *zName
  34705. ){
  34706. unsigned int i;
  34707. UNUSED_PARAMETER(pNotUsed);
  34708. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34709. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  34710. }
  34711. return 0;
  34712. }
  34713. /*
  34714. ** Return the name of the first system call after zName. If zName==NULL
  34715. ** then return the name of the first system call. Return NULL if zName
  34716. ** is the last system call or if zName is not the name of a valid
  34717. ** system call.
  34718. */
  34719. static const char *rttNextSystemCall(sqlite3_vfs *p, const char *zName){
  34720. int i = -1;
  34721. UNUSED_PARAMETER(p);
  34722. if( zName ){
  34723. for(i=0; i<ArraySize(aSyscall)-1; i++){
  34724. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  34725. }
  34726. }
  34727. for(i++; i<ArraySize(aSyscall); i++){
  34728. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  34729. }
  34730. return 0;
  34731. }
  34732. /*
  34733. ** The following routine suspends the current thread for at least ms
  34734. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  34735. */
  34736. SQLITE_API void sqlite3_rtt_sleep(int milliseconds){
  34737. rt_tick_t sleep_tick;
  34738. if (milliseconds <= 0)
  34739. return;
  34740. sleep_tick = rt_tick_from_millisecond(milliseconds);
  34741. osSleep(sleep_tick);
  34742. }
  34743. /*
  34744. ** Helper functions to obtain and relinquish the global mutex. The
  34745. ** global mutex is used to protect the unixInodeInfo and
  34746. ** vxworksFileId objects used by this file, all of which may be
  34747. ** shared by multiple threads.
  34748. **
  34749. ** Function unixMutexHeld() is used to assert() that the global mutex
  34750. ** is held when required. This function is only used as part of assert()
  34751. ** statements. e.g.
  34752. **
  34753. ** unixEnterMutex()
  34754. ** assert( unixMutexHeld() );
  34755. ** unixEnterLeave()
  34756. */
  34757. static void rttEnterMutex(void){
  34758. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34759. }
  34760. static void rttLeaveMutex(void){
  34761. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34762. }
  34763. #ifdef SQLITE_DEBUG
  34764. static int rttMutexHeld(void) {
  34765. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34766. }
  34767. #endif
  34768. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  34769. /*
  34770. ** Helper function for printing out trace information from debugging
  34771. ** binaries. This returns the string represetation of the supplied
  34772. ** integer lock-type.
  34773. */
  34774. static const char *azFileLock(int eFileLock){
  34775. switch( eFileLock ){
  34776. case NO_LOCK: return "NONE";
  34777. case SHARED_LOCK: return "SHARED";
  34778. case RESERVED_LOCK: return "RESERVED";
  34779. case PENDING_LOCK: return "PENDING";
  34780. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  34781. }
  34782. return "ERROR";
  34783. }
  34784. #endif
  34785. /*
  34786. ** This routine translates a standard POSIX errno code into something
  34787. ** useful to the clients of the sqlite3 functions. Specifically, it is
  34788. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  34789. ** and a variety of "please close the file descriptor NOW" errors into
  34790. ** SQLITE_IOERR
  34791. **
  34792. ** Errors during initialization of locks, or file system support for locks,
  34793. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  34794. */
  34795. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  34796. switch (posixError) {
  34797. #if 0
  34798. /* At one point this code was not commented out. In theory, this branch
  34799. ** should never be hit, as this function should only be called after
  34800. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  34801. ** the value of errno as the first argument. Since a system call has failed,
  34802. ** errno should be non-zero.
  34803. **
  34804. ** Despite this, if errno really is zero, we still don't want to return
  34805. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  34806. ** propagated back to the caller. Commenting this branch out means errno==0
  34807. ** will be handled by the "default:" case below.
  34808. */
  34809. case 0:
  34810. return SQLITE_OK;
  34811. #endif
  34812. case EAGAIN:
  34813. case ETIMEDOUT:
  34814. case EBUSY:
  34815. case EINTR:
  34816. case ENOLCK:
  34817. /* random NFS retry error, unless during file system support
  34818. * introspection, in which it actually means what it says */
  34819. return SQLITE_BUSY;
  34820. case EACCES:
  34821. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  34822. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  34823. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  34824. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  34825. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  34826. return SQLITE_BUSY;
  34827. }
  34828. /* else fall through */
  34829. case EPERM:
  34830. return SQLITE_PERM;
  34831. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  34832. ** this module never makes such a call. And the code in SQLite itself
  34833. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  34834. ** this case is also commented out. If the system does set errno to EDEADLK,
  34835. ** the default SQLITE_IOERR_XXX code will be returned. */
  34836. #if 0
  34837. case EDEADLK:
  34838. return SQLITE_IOERR_BLOCKED;
  34839. #endif
  34840. #if EOPNOTSUPP!=ENOTSUP
  34841. case EOPNOTSUPP:
  34842. /* something went terribly awry, unless during file system support
  34843. * introspection, in which it actually means what it says */
  34844. #endif
  34845. #ifdef ENOTSUP
  34846. case ENOTSUP:
  34847. /* invalid fd, unless during file system support introspection, in which
  34848. * it actually means what it says */
  34849. #endif
  34850. case EIO:
  34851. case EBADF:
  34852. case EINVAL:
  34853. case ENOTCONN:
  34854. case ENODEV:
  34855. case ENXIO:
  34856. case ENOENT:
  34857. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  34858. case ESTALE:
  34859. #endif
  34860. case ENOSYS:
  34861. /* these should force the client to close the file and reconnect */
  34862. default:
  34863. return sqliteIOErr;
  34864. }
  34865. }
  34866. static int robust_ftruncate(int h, sqlite3_int64 sz){
  34867. int rc;
  34868. rc = -1;
  34869. return rc;
  34870. }
  34871. /*
  34872. ** Close a file descriptor.
  34873. **
  34874. ** We assume that close() almost always works, since it is only in a
  34875. ** very sick application or on a very sick platform that it might fail.
  34876. ** If it does fail, simply leak the file descriptor, but do log the
  34877. ** error.
  34878. **
  34879. ** Note that it is not safe to retry close() after EINTR since the
  34880. ** file descriptor might have already been reused by another thread.
  34881. ** So we don't even try to recover from an EINTR. Just log the error
  34882. ** and move on.
  34883. */
  34884. static void robust_close(rttFile *pFile, int h, int lineno){
  34885. if( osClose(h) ){
  34886. rttLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  34887. pFile ? pFile->zPath : 0, lineno);
  34888. }
  34889. }
  34890. /*
  34891. ** Check a rttFile that is a database. Verify the following:
  34892. **
  34893. ** (1) There is exactly one hard link on the file
  34894. ** (2) The file is not a symbolic link
  34895. ** (3) The file has not been renamed or unlinked
  34896. **
  34897. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  34898. */
  34899. static void verifyDbFile(rttFile *pFile){
  34900. struct stat buf;
  34901. int rc;
  34902. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  34903. /* One or more of the following warnings have already been issued. Do not
  34904. ** repeat them so as not to clutter the error log */
  34905. return;
  34906. }
  34907. rc = osFstat(pFile->h, &buf);
  34908. if( rc!=0 ){
  34909. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  34910. pFile->ctrlFlags |= UNIXFILE_WARNED;
  34911. return;
  34912. }
  34913. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  34914. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  34915. pFile->ctrlFlags |= UNIXFILE_WARNED;
  34916. return;
  34917. }
  34918. }
  34919. /*
  34920. ** This function performs the parts of the "close file" operation
  34921. ** common to all locking schemes. It closes the directory and file
  34922. ** handles, if they are valid, and sets all fields of the rttFile
  34923. ** structure to 0.
  34924. **
  34925. ** It is *not* necessary to hold the mutex when this routine is called,
  34926. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  34927. ** vxworksReleaseFileId() routine.
  34928. */
  34929. static int closeRttFile(sqlite3_file *id){
  34930. rttFile *pFile = (rttFile*)id;
  34931. if( pFile->h>=0 ){
  34932. robust_close(pFile, pFile->h, __LINE__);
  34933. pFile->h = -1;
  34934. }
  34935. OSTRACE(("CLOSE %-3d\n", pFile->h));
  34936. OpenCounter(-1);
  34937. memset(pFile, 0, sizeof(rttFile));
  34938. return SQLITE_OK;
  34939. }
  34940. /************** End of the posix advisory lock implementation *****************
  34941. ******************************************************************************/
  34942. /******************************************************************************
  34943. ****************************** No-op Locking **********************************
  34944. **
  34945. ** Of the various locking implementations available, this is by far the
  34946. ** simplest: locking is ignored. No attempt is made to lock the database
  34947. ** file for reading or writing.
  34948. **
  34949. ** This locking mode is appropriate for use on read-only databases
  34950. ** (ex: databases that are burned into CD-ROM, for example.) It can
  34951. ** also be used if the application employs some external mechanism to
  34952. ** prevent simultaneous access of the same database by two or more
  34953. ** database connections. But there is a serious risk of database
  34954. ** corruption if this locking mode is used in situations where multiple
  34955. ** database connections are accessing the same database file at the same
  34956. ** time and one or more of those connections are writing.
  34957. */
  34958. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  34959. UNUSED_PARAMETER(NotUsed);
  34960. *pResOut = 0;
  34961. return SQLITE_OK;
  34962. }
  34963. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  34964. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  34965. return SQLITE_OK;
  34966. }
  34967. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  34968. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  34969. return SQLITE_OK;
  34970. }
  34971. /*
  34972. ** Close the file.
  34973. */
  34974. static int nolockClose(sqlite3_file *id) {
  34975. return closeRttFile(id);
  34976. }
  34977. /******************* End of the no-op lock implementation *********************
  34978. ******************************************************************************/
  34979. /******************************************************************************
  34980. ************************* Begin dot-file Locking ******************************
  34981. **
  34982. ** The dotfile locking implementation uses the existence of separate lock
  34983. ** files (really a directory) to control access to the database. This works
  34984. ** on just about every filesystem imaginable. But there are serious downsides:
  34985. **
  34986. ** (1) There is zero concurrency. A single reader blocks all other
  34987. ** connections from reading or writing the database.
  34988. **
  34989. ** (2) An application crash or power loss can leave stale lock files
  34990. ** sitting around that need to be cleared manually.
  34991. **
  34992. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  34993. ** other locking strategy is available.
  34994. **
  34995. ** Dotfile locking works by creating a subdirectory in the same directory as
  34996. ** the database and with the same name but with a ".lock" extension added.
  34997. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  34998. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  34999. */
  35000. /*
  35001. ** The file suffix added to the data base filename in order to create the
  35002. ** lock directory.
  35003. */
  35004. #define DOTLOCK_SUFFIX ".lock"
  35005. /*
  35006. ** Only set the lastErrno if the error code is a real error and not
  35007. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  35008. */
  35009. #define IS_LOCK_ERROR(x) (((x) != SQLITE_OK) && ((x) != SQLITE_BUSY))
  35010. /*
  35011. ** This routine checks if there is a RESERVED lock held on the specified
  35012. ** file by this or any other process. If such a lock is held, set *pResOut
  35013. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35014. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35015. **
  35016. ** In dotfile locking, either a lock exists or it does not. So in this
  35017. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  35018. ** is held on the file and false if the file is unlocked.
  35019. */
  35020. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  35021. int rc = SQLITE_OK;
  35022. int reserved = 0;
  35023. rttFile *pFile = (rttFile*)id;
  35024. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35025. assert( pFile );
  35026. /* Check if a thread in this process holds such a lock */
  35027. if( pFile->eFileLock>SHARED_LOCK ){
  35028. /* Either this connection or some other connection in the same process
  35029. ** holds a lock on the file. No need to check further. */
  35030. reserved = 1;
  35031. }else{
  35032. /* The lock is held if and only if the lockfile exists */
  35033. const char *zLockFile = (const char*)pFile->lockingContext;
  35034. reserved = 0;
  35035. }
  35036. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  35037. *pResOut = reserved;
  35038. return rc;
  35039. }
  35040. /*
  35041. ** Lock the file with the lock specified by parameter eFileLock - one
  35042. ** of the following:
  35043. **
  35044. ** (1) SHARED_LOCK
  35045. ** (2) RESERVED_LOCK
  35046. ** (3) PENDING_LOCK
  35047. ** (4) EXCLUSIVE_LOCK
  35048. **
  35049. ** Sometimes when requesting one lock state, additional lock states
  35050. ** are inserted in between. The locking might fail on one of the later
  35051. ** transitions leaving the lock state different from what it started but
  35052. ** still short of its goal. The following chart shows the allowed
  35053. ** transitions and the inserted intermediate states:
  35054. **
  35055. ** UNLOCKED -> SHARED
  35056. ** SHARED -> RESERVED
  35057. ** SHARED -> (PENDING) -> EXCLUSIVE
  35058. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35059. ** PENDING -> EXCLUSIVE
  35060. **
  35061. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35062. ** routine to lower a locking level.
  35063. **
  35064. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  35065. ** But we track the other locking levels internally.
  35066. */
  35067. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  35068. rttFile *pFile = (rttFile*)id;
  35069. char *zLockFile = (char *)pFile->lockingContext;
  35070. int rc = SQLITE_OK;
  35071. /* If we have any lock, then the lock file already exists. All we have
  35072. ** to do is adjust our internal record of the lock level.
  35073. */
  35074. if( pFile->eFileLock > NO_LOCK ){
  35075. pFile->eFileLock = eFileLock;
  35076. return SQLITE_OK;
  35077. }
  35078. /* grab an exclusive lock */
  35079. rc = osMkdir(zLockFile, 0777);
  35080. if( rc<0 ){
  35081. /* failed to open/create the lock directory */
  35082. int tErrno = errno;
  35083. if( EEXIST == tErrno ){
  35084. rc = SQLITE_BUSY;
  35085. } else {
  35086. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35087. if( IS_LOCK_ERROR(rc) ){
  35088. pFile->lastErrno = tErrno;
  35089. }
  35090. }
  35091. return rc;
  35092. }
  35093. /* got it, set the type and return ok */
  35094. pFile->eFileLock = eFileLock;
  35095. return rc;
  35096. }
  35097. /*
  35098. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35099. ** must be either NO_LOCK or SHARED_LOCK.
  35100. **
  35101. ** If the locking level of the file descriptor is already at or below
  35102. ** the requested locking level, this routine is a no-op.
  35103. **
  35104. ** When the locking level reaches NO_LOCK, delete the lock file.
  35105. */
  35106. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  35107. rttFile *pFile = (rttFile*)id;
  35108. char *zLockFile = (char *)pFile->lockingContext;
  35109. int rc;
  35110. assert( pFile );
  35111. OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock,
  35112. pFile->eFileLock, rt_thread_self()->name ));
  35113. assert( eFileLock<=SHARED_LOCK );
  35114. /* no-op if possible */
  35115. if( pFile->eFileLock==eFileLock ){
  35116. return SQLITE_OK;
  35117. }
  35118. /* To downgrade to shared, simply update our internal notion of the
  35119. ** lock state. No need to mess with the file on disk.
  35120. */
  35121. if( eFileLock==SHARED_LOCK ){
  35122. pFile->eFileLock = SHARED_LOCK;
  35123. return SQLITE_OK;
  35124. }
  35125. /* To fully unlock the database, delete the lock file */
  35126. assert( eFileLock==NO_LOCK );
  35127. rc = osRmdir(zLockFile);
  35128. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  35129. if( rc<0 ){
  35130. int tErrno = errno;
  35131. rc = 0;
  35132. if( ENOENT != tErrno ){
  35133. rc = SQLITE_IOERR_UNLOCK;
  35134. }
  35135. if( IS_LOCK_ERROR(rc) ){
  35136. pFile->lastErrno = tErrno;
  35137. }
  35138. return rc;
  35139. }
  35140. pFile->eFileLock = NO_LOCK;
  35141. return SQLITE_OK;
  35142. }
  35143. /*
  35144. ** Close a file. Make sure the lock has been released before closing.
  35145. */
  35146. static int dotlockClose(sqlite3_file *id) {
  35147. int rc = SQLITE_OK;
  35148. if( id ){
  35149. rttFile *pFile = (rttFile*)id;
  35150. dotlockUnlock(id, NO_LOCK);
  35151. sqlite3_free(pFile->lockingContext);
  35152. rc = closeRttFile(id);
  35153. }
  35154. return rc;
  35155. }
  35156. /****************** End of the dot-file lock implementation *******************
  35157. ******************************************************************************/
  35158. /******************************************************************************
  35159. ************************** Begin flock Locking ********************************
  35160. **
  35161. ** Use the flock() system call to do file locking.
  35162. **
  35163. ** flock() locking is like dot-file locking in that the various
  35164. ** fine-grain locking levels supported by SQLite are collapsed into
  35165. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  35166. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  35167. ** still works when you do this, but concurrency is reduced since
  35168. ** only a single process can be reading the database at a time.
  35169. **
  35170. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  35171. ** compiling for VXWORKS.
  35172. */
  35173. #if SQLITE_ENABLE_LOCKING_STYLE
  35174. #warning "rtt file lock not available"
  35175. /*
  35176. ** Retry flock() calls that fail with EINTR
  35177. */
  35178. static int robust_flock(int fd, int op){
  35179. int rc = 0;
  35180. return rc;
  35181. }
  35182. /*
  35183. ** This routine checks if there is a RESERVED lock held on the specified
  35184. ** file by this or any other process. If such a lock is held, set *pResOut
  35185. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35186. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35187. */
  35188. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  35189. int rc = SQLITE_OK;
  35190. int reserved = 0;
  35191. rttFile *pFile = (rttFile*)id;
  35192. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35193. assert( pFile );
  35194. /* Check if a thread in this process holds such a lock */
  35195. if( pFile->eFileLock>SHARED_LOCK ){
  35196. reserved = 1;
  35197. }
  35198. /* Otherwise see if some other process holds it. */
  35199. if( !reserved ){
  35200. /* attempt to get the lock */
  35201. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  35202. if( !lrc ){
  35203. /* got the lock, unlock it */
  35204. lrc = robust_flock(pFile->h, LOCK_UN);
  35205. if ( lrc ) {
  35206. int tErrno = errno;
  35207. /* unlock failed with an error */
  35208. lrc = SQLITE_IOERR_UNLOCK;
  35209. if( IS_LOCK_ERROR(lrc) ){
  35210. pFile->lastErrno = tErrno;
  35211. rc = lrc;
  35212. }
  35213. }
  35214. } else {
  35215. int tErrno = errno;
  35216. reserved = 1;
  35217. /* someone else might have it reserved */
  35218. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35219. if( IS_LOCK_ERROR(lrc) ){
  35220. pFile->lastErrno = tErrno;
  35221. rc = lrc;
  35222. }
  35223. }
  35224. }
  35225. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  35226. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35227. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  35228. rc = SQLITE_OK;
  35229. reserved=1;
  35230. }
  35231. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35232. *pResOut = reserved;
  35233. return rc;
  35234. }
  35235. /*
  35236. ** Lock the file with the lock specified by parameter eFileLock - one
  35237. ** of the following:
  35238. **
  35239. ** (1) SHARED_LOCK
  35240. ** (2) RESERVED_LOCK
  35241. ** (3) PENDING_LOCK
  35242. ** (4) EXCLUSIVE_LOCK
  35243. **
  35244. ** Sometimes when requesting one lock state, additional lock states
  35245. ** are inserted in between. The locking might fail on one of the later
  35246. ** transitions leaving the lock state different from what it started but
  35247. ** still short of its goal. The following chart shows the allowed
  35248. ** transitions and the inserted intermediate states:
  35249. **
  35250. ** UNLOCKED -> SHARED
  35251. ** SHARED -> RESERVED
  35252. ** SHARED -> (PENDING) -> EXCLUSIVE
  35253. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35254. ** PENDING -> EXCLUSIVE
  35255. **
  35256. ** flock() only really support EXCLUSIVE locks. We track intermediate
  35257. ** lock states in the sqlite3_file structure, but all locks SHARED or
  35258. ** above are really EXCLUSIVE locks and exclude all other processes from
  35259. ** access the file.
  35260. **
  35261. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35262. ** routine to lower a locking level.
  35263. */
  35264. static int flockLock(sqlite3_file *id, int eFileLock) {
  35265. int rc = SQLITE_OK;
  35266. rttFile *pFile = (rttFile*)id;
  35267. assert( pFile );
  35268. /* if we already have a lock, it is exclusive.
  35269. ** Just adjust level and punt on outta here. */
  35270. if (pFile->eFileLock > NO_LOCK) {
  35271. pFile->eFileLock = eFileLock;
  35272. return SQLITE_OK;
  35273. }
  35274. /* grab an exclusive lock */
  35275. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  35276. int tErrno = errno;
  35277. /* didn't get, must be busy */
  35278. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35279. if( IS_LOCK_ERROR(rc) ){
  35280. pFile->lastErrno = tErrno;
  35281. }
  35282. } else {
  35283. /* got it, set the type and return ok */
  35284. pFile->eFileLock = eFileLock;
  35285. }
  35286. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  35287. rc==SQLITE_OK ? "ok" : "failed"));
  35288. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35289. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  35290. rc = SQLITE_BUSY;
  35291. }
  35292. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35293. return rc;
  35294. }
  35295. /*
  35296. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35297. ** must be either NO_LOCK or SHARED_LOCK.
  35298. **
  35299. ** If the locking level of the file descriptor is already at or below
  35300. ** the requested locking level, this routine is a no-op.
  35301. */
  35302. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  35303. rttFile *pFile = (rttFile*)id;
  35304. assert( pFile );
  35305. OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock,
  35306. pFile->eFileLock, rt_thread_self()->name));
  35307. assert( eFileLock<=SHARED_LOCK );
  35308. /* no-op if possible */
  35309. if( pFile->eFileLock==eFileLock ){
  35310. return SQLITE_OK;
  35311. }
  35312. /* shared can just be set because we always have an exclusive */
  35313. if (eFileLock==SHARED_LOCK) {
  35314. pFile->eFileLock = eFileLock;
  35315. return SQLITE_OK;
  35316. }
  35317. /* no, really, unlock. */
  35318. if( robust_flock(pFile->h, LOCK_UN) ){
  35319. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35320. return SQLITE_OK;
  35321. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35322. return SQLITE_IOERR_UNLOCK;
  35323. }else{
  35324. pFile->eFileLock = NO_LOCK;
  35325. return SQLITE_OK;
  35326. }
  35327. }
  35328. /*
  35329. ** Close a file.
  35330. */
  35331. static int flockClose(sqlite3_file *id) {
  35332. int rc = SQLITE_OK;
  35333. if( id ){
  35334. flockUnlock(id, NO_LOCK);
  35335. rc = closeRttFile(id);
  35336. }
  35337. return rc;
  35338. }
  35339. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  35340. /******************* End of the flock lock implementation *********************
  35341. ******************************************************************************/
  35342. /******************************************************************************
  35343. **************** Non-locking sqlite3_file methods *****************************
  35344. **
  35345. ** The next division contains implementations for all methods of the
  35346. ** sqlite3_file object other than the locking methods. The locking
  35347. ** methods were defined in divisions above (one locking method per
  35348. ** division). Those methods that are common to all locking modes
  35349. ** are gather together into this division.
  35350. */
  35351. /*
  35352. ** Seek to the offset passed as the second argument, then read cnt
  35353. ** bytes into pBuf. Return the number of bytes actually read.
  35354. **
  35355. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  35356. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  35357. ** one system to another. Since SQLite does not define USE_PREAD
  35358. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  35359. ** See tickets #2741 and #2681.
  35360. **
  35361. ** To avoid stomping the errno value on a failed read the lastErrno value
  35362. ** is set before returning.
  35363. */
  35364. static int seekAndRead(rttFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  35365. int got;
  35366. int prior = 0;
  35367. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  35368. i64 newOffset;
  35369. #endif
  35370. TIMER_START;
  35371. assert( cnt==(cnt&0x1ffff) );
  35372. assert( id->h>2 );
  35373. cnt &= 0x1ffff;
  35374. do{
  35375. #if defined(USE_PREAD)
  35376. #error "rtt pread not support"
  35377. got = osPread(id->h, pBuf, cnt, offset);
  35378. SimulateIOError( got = -1 );
  35379. #elif defined(USE_PREAD64)
  35380. #error "rtt pread64 not support"
  35381. got = osPread64(id->h, pBuf, cnt, offset);
  35382. SimulateIOError( got = -1 );
  35383. #else
  35384. newOffset = lseek(id->h, offset, SEEK_SET);
  35385. SimulateIOError( newOffset-- );
  35386. if( newOffset!=offset ){
  35387. if( newOffset == -1 ){
  35388. ((rttFile*)id)->lastErrno = errno;
  35389. }else{
  35390. ((rttFile*)id)->lastErrno = 0;
  35391. }
  35392. return -1;
  35393. }
  35394. got = osRead(id->h, pBuf, cnt);
  35395. #endif
  35396. if( got==cnt ) break;
  35397. if( got<0 ){
  35398. if( errno==EINTR ){ got = 1; continue; }
  35399. prior = 0;
  35400. ((rttFile*)id)->lastErrno = errno;
  35401. break;
  35402. }else if( got>0 ){
  35403. cnt -= got;
  35404. offset += got;
  35405. prior += got;
  35406. pBuf = (void*)(got + (char*)pBuf);
  35407. }
  35408. }while( got>0 );
  35409. TIMER_END;
  35410. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  35411. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  35412. return got+prior;
  35413. }
  35414. /*
  35415. ** Read data from a file into a buffer. Return SQLITE_OK if all
  35416. ** bytes were read successfully and SQLITE_IOERR if anything goes
  35417. ** wrong.
  35418. */
  35419. static int rttRead(
  35420. sqlite3_file *id,
  35421. void *pBuf,
  35422. int amt,
  35423. sqlite3_int64 offset
  35424. ){
  35425. rttFile *pFile = (rttFile *)id;
  35426. int got;
  35427. assert( id );
  35428. assert( offset>=0 );
  35429. assert( amt>0 );
  35430. got = seekAndRead(pFile, offset, pBuf, amt);
  35431. if( got==amt ){
  35432. return SQLITE_OK;
  35433. }else if( got<0 ){
  35434. /* lastErrno set by seekAndRead */
  35435. return SQLITE_IOERR_READ;
  35436. }else{
  35437. pFile->lastErrno = 0; /* not a system error */
  35438. /* Unread parts of the buffer must be zero-filled */
  35439. memset(&((char*)pBuf)[got], 0, amt-got);
  35440. return SQLITE_IOERR_SHORT_READ;
  35441. }
  35442. }
  35443. /*
  35444. ** Attempt to seek the file-descriptor passed as the first argument to
  35445. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  35446. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  35447. ** return the actual number of bytes written (which may be less than
  35448. ** nBuf).
  35449. */
  35450. static int seekAndWriteFd(
  35451. int fd, /* File descriptor to write to */
  35452. i64 iOff, /* File offset to begin writing at */
  35453. const void *pBuf, /* Copy data from this buffer to the file */
  35454. int nBuf, /* Size of buffer pBuf in bytes */
  35455. int *piErrno /* OUT: Error number if error occurs */
  35456. ){
  35457. int rc = 0; /* Value returned by system call */
  35458. assert( nBuf==(nBuf&0x1ffff) );
  35459. assert( fd>2 );
  35460. nBuf &= 0x1ffff;
  35461. TIMER_START;
  35462. #if defined(USE_PREAD)
  35463. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  35464. #elif defined(USE_PREAD64)
  35465. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  35466. #else
  35467. do{
  35468. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  35469. SimulateIOError( iSeek-- );
  35470. if( iSeek!=iOff ){
  35471. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  35472. return -1;
  35473. }
  35474. rc = osWrite(fd, pBuf, nBuf);
  35475. }while( rc<0 && errno==EINTR );
  35476. #endif
  35477. TIMER_END;
  35478. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  35479. if( rc<0 && piErrno ) *piErrno = errno;
  35480. return rc;
  35481. }
  35482. /*
  35483. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  35484. ** Return the number of bytes actually read. Update the offset.
  35485. **
  35486. ** To avoid stomping the errno value on a failed write the lastErrno value
  35487. ** is set before returning.
  35488. */
  35489. static int seekAndWrite(rttFile *id, i64 offset, const void *pBuf, int cnt){
  35490. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  35491. }
  35492. /*
  35493. ** Write data from a buffer into a file. Return SQLITE_OK on success
  35494. ** or some other error code on failure.
  35495. */
  35496. static int rttWrite(
  35497. sqlite3_file *id,
  35498. const void *pBuf,
  35499. int amt,
  35500. sqlite3_int64 offset
  35501. ){
  35502. rttFile *pFile = (rttFile*)id;
  35503. int wrote = 0;
  35504. assert( id );
  35505. assert( amt>0 );
  35506. #ifdef SQLITE_DEBUG
  35507. /* If we are doing a normal write to a database file (as opposed to
  35508. ** doing a hot-journal rollback or a write to some file other than a
  35509. ** normal database file) then record the fact that the database
  35510. ** has changed. If the transaction counter is modified, record that
  35511. ** fact too.
  35512. */
  35513. if( pFile->inNormalWrite ){
  35514. pFile->dbUpdate = 1; /* The database has been modified */
  35515. if( offset<=24 && offset+amt>=27 ){
  35516. int rc;
  35517. char oldCntr[4];
  35518. SimulateIOErrorBenign(1);
  35519. rc = seekAndRead(pFile, 24, oldCntr, 4);
  35520. SimulateIOErrorBenign(0);
  35521. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  35522. pFile->transCntrChng = 1; /* The transaction counter has changed */
  35523. }
  35524. }
  35525. }
  35526. #endif
  35527. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  35528. amt -= wrote;
  35529. offset += wrote;
  35530. pBuf = &((char*)pBuf)[wrote];
  35531. }
  35532. SimulateIOError(( wrote=(-1), amt=1 ));
  35533. SimulateDiskfullError(( wrote=0, amt=1 ));
  35534. if( amt>0 ){
  35535. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  35536. /* lastErrno set by seekAndWrite */
  35537. return SQLITE_IOERR_WRITE;
  35538. }else{
  35539. pFile->lastErrno = 0; /* not a system error */
  35540. return SQLITE_FULL;
  35541. }
  35542. }
  35543. return SQLITE_OK;
  35544. }
  35545. #ifdef SQLITE_TEST
  35546. /*
  35547. ** Count the number of fullsyncs and normal syncs. This is used to test
  35548. ** that syncs and fullsyncs are occurring at the right times.
  35549. */
  35550. SQLITE_API int sqlite3_sync_count = 0;
  35551. SQLITE_API int sqlite3_fullsync_count = 0;
  35552. #endif
  35553. /*
  35554. ** We do not trust systems to provide a working fdatasync(). Some do.
  35555. ** Others do no. To be safe, we will stick with the (slightly slower)
  35556. ** fsync(). If you know that your system does support fdatasync() correctly,
  35557. ** then simply compile with -Dfdatasync=fdatasync
  35558. */
  35559. #if !defined(fdatasync)
  35560. #include "dfs.h"
  35561. #include "dfs_file.h"
  35562. int fdatasync(fd)
  35563. {
  35564. struct dfs_fd *dfs_fd;
  35565. dfs_fd = fd_get(fd);
  35566. return dfs_file_flush(dfs_fd);
  35567. }
  35568. #endif
  35569. /*
  35570. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  35571. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  35572. ** only available on Mac OS X. But that could change.
  35573. */
  35574. #ifdef F_FULLFSYNC
  35575. # define HAVE_FULLFSYNC 0
  35576. #endif
  35577. /*
  35578. ** The fsync() system call does not work as advertised on many
  35579. ** unix systems. The following procedure is an attempt to make
  35580. ** it work better.
  35581. **
  35582. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  35583. ** for testing when we want to run through the test suite quickly.
  35584. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  35585. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  35586. ** or power failure will likely corrupt the database file.
  35587. **
  35588. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  35589. ** The idea behind dataOnly is that it should only write the file content
  35590. ** to disk, not the inode. We only set dataOnly if the file size is
  35591. ** unchanged since the file size is part of the inode. However,
  35592. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  35593. ** file size has changed. The only real difference between fdatasync()
  35594. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  35595. ** inode if the mtime or owner or other inode attributes have changed.
  35596. ** We only care about the file size, not the other file attributes, so
  35597. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  35598. ** So, we always use fdatasync() if it is available, regardless of
  35599. ** the value of the dataOnly flag.
  35600. */
  35601. static int full_fsync(int fd, int fullSync, int dataOnly){
  35602. int rc;
  35603. /* The following "ifdef/elif/else/" block has the same structure as
  35604. ** the one below. It is replicated here solely to avoid cluttering
  35605. ** up the real code with the UNUSED_PARAMETER() macros.
  35606. */
  35607. #ifdef SQLITE_NO_SYNC
  35608. UNUSED_PARAMETER(fd);
  35609. UNUSED_PARAMETER(fullSync);
  35610. UNUSED_PARAMETER(dataOnly);
  35611. #elif HAVE_FULLFSYNC
  35612. UNUSED_PARAMETER(dataOnly);
  35613. #else
  35614. UNUSED_PARAMETER(fullSync);
  35615. UNUSED_PARAMETER(dataOnly);
  35616. #endif
  35617. /* Record the number of times that we do a normal fsync() and
  35618. ** FULLSYNC. This is used during testing to verify that this procedure
  35619. ** gets called with the correct arguments.
  35620. */
  35621. #ifdef SQLITE_TEST
  35622. if( fullSync ) sqlite3_fullsync_count++;
  35623. sqlite3_sync_count++;
  35624. #endif
  35625. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  35626. ** no-op
  35627. */
  35628. #ifdef SQLITE_NO_SYNC
  35629. rc = SQLITE_OK;
  35630. #elif HAVE_FULLFSYNC
  35631. #error "rtt not support FULLFSYNC"
  35632. #else
  35633. rc = fdatasync(fd);
  35634. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  35635. return rc;
  35636. }
  35637. /*
  35638. ** Make sure all writes to a particular file are committed to disk.
  35639. **
  35640. ** If dataOnly==0 then both the file itself and its metadata (file
  35641. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  35642. ** file data is synced.
  35643. **
  35644. ** Under Rtt, also make sure that the directory entry for the file
  35645. ** has been created by fsync-ing the directory that contains the file.
  35646. ** If we do not do this and we encounter a power failure, the directory
  35647. ** entry for the journal might not exist after we reboot. The next
  35648. ** SQLite to access the file will not know that the journal exists (because
  35649. ** the directory entry for the journal was never created) and the transaction
  35650. ** will not roll back - possibly leading to database corruption.
  35651. */
  35652. static int rttSync(sqlite3_file *id, int flags){
  35653. int rc;
  35654. rttFile *pFile = (rttFile*)id;
  35655. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  35656. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  35657. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  35658. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  35659. || (flags&0x0F)==SQLITE_SYNC_FULL
  35660. );
  35661. /* Rtt cannot, but some systems may return SQLITE_FULL from here. This
  35662. ** line is to test that doing so does not cause any problems.
  35663. */
  35664. SimulateDiskfullError( return SQLITE_FULL );
  35665. assert( pFile );
  35666. OSTRACE(("SYNC %-3d\n", pFile->h));
  35667. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  35668. SimulateIOError( rc=1 );
  35669. if( rc ){
  35670. pFile->lastErrno = errno;
  35671. return rttLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  35672. }
  35673. /* Also fsync the directory containing the file if the DIRSYNC flag
  35674. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  35675. ** are unable to fsync a directory, so ignore errors on the fsync.
  35676. */
  35677. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  35678. int dirfd;
  35679. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  35680. HAVE_FULLFSYNC, isFullsync));
  35681. rc = osOpenDirectory(pFile->zPath, &dirfd);
  35682. if( rc==SQLITE_OK && dirfd>=0 ){
  35683. full_fsync(dirfd, 0, 0);
  35684. robust_close(pFile, dirfd, __LINE__);
  35685. }else if( rc==SQLITE_CANTOPEN ){
  35686. rc = SQLITE_OK;
  35687. }
  35688. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  35689. }
  35690. return rc;
  35691. }
  35692. /*
  35693. ** Truncate an open file to a specified size
  35694. */
  35695. static int rttTruncate(sqlite3_file *id, i64 nByte){
  35696. rttFile *pFile = (rttFile *)id;
  35697. int rc;
  35698. assert( pFile );
  35699. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  35700. /* If the user has configured a chunk-size for this file, truncate the
  35701. ** file so that it consists of an integer number of chunks (i.e. the
  35702. ** actual file size after the operation may be larger than the requested
  35703. ** size).
  35704. */
  35705. if( pFile->szChunk>0 ){
  35706. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  35707. }
  35708. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  35709. if( rc ){
  35710. pFile->lastErrno = errno;
  35711. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35712. }else{
  35713. #ifdef SQLITE_DEBUG
  35714. /* If we are doing a normal write to a database file (as opposed to
  35715. ** doing a hot-journal rollback or a write to some file other than a
  35716. ** normal database file) and we truncate the file to zero length,
  35717. ** that effectively updates the change counter. This might happen
  35718. ** when restoring a database using the backup API from a zero-length
  35719. ** source.
  35720. */
  35721. if( pFile->inNormalWrite && nByte==0 ){
  35722. pFile->transCntrChng = 1;
  35723. }
  35724. #endif
  35725. return SQLITE_OK;
  35726. }
  35727. }
  35728. /*
  35729. ** Determine the current size of a file in bytes
  35730. */
  35731. static int rttFileSize(sqlite3_file *id, i64 *pSize){
  35732. int rc;
  35733. struct stat buf;
  35734. assert( id );
  35735. rc = osFstat(((rttFile*)id)->h, &buf);
  35736. SimulateIOError( rc=1 );
  35737. if( rc!=0 ){
  35738. ((rttFile*)id)->lastErrno = errno;
  35739. return SQLITE_IOERR_FSTAT;
  35740. }
  35741. *pSize = buf.st_size;
  35742. /* When opening a zero-size database, the findInodeInfo() procedure
  35743. ** writes a single byte into that file in order to work around a bug
  35744. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  35745. ** layers, we need to report this file size as zero even though it is
  35746. ** really 1. Ticket #3260.
  35747. */
  35748. if( *pSize==1 ) *pSize = 0;
  35749. return SQLITE_OK;
  35750. }
  35751. /*
  35752. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  35753. ** file-control operation. Enlarge the database to nBytes in size
  35754. ** (rounded up to the next chunk-size). If the database is already
  35755. ** nBytes or larger, this routine is a no-op.
  35756. */
  35757. static int fcntlSizeHint(rttFile *pFile, i64 nByte){
  35758. if( pFile->szChunk>0 ){
  35759. i64 nSize; /* Required file size */
  35760. struct stat buf; /* Used to hold return values of fstat() */
  35761. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  35762. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  35763. if( nSize>(i64)buf.st_size ){
  35764. /* If the OS does not have posix_fallocate(), fake it. First use
  35765. ** ftruncate() to set the file size, then write a single byte to
  35766. ** the last byte in each block within the extended region. This
  35767. ** is the same technique used by glibc to implement posix_fallocate()
  35768. ** on systems that do not have a real fallocate() system call.
  35769. */
  35770. int nBlk = buf.st_blksize; /* File-system block size */
  35771. i64 iWrite; /* Next offset to write to */
  35772. if( robust_ftruncate(pFile->h, nSize) ){
  35773. pFile->lastErrno = errno;
  35774. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35775. }
  35776. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  35777. while( iWrite<nSize ){
  35778. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  35779. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  35780. iWrite += nBlk;
  35781. }
  35782. }
  35783. }
  35784. return SQLITE_OK;
  35785. }
  35786. /*
  35787. ** If *pArg is inititially negative then this is a query. Set *pArg to
  35788. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  35789. **
  35790. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  35791. */
  35792. static void rttModeBit(rttFile *pFile, unsigned char mask, int *pArg){
  35793. if( *pArg<0 ){
  35794. *pArg = (pFile->ctrlFlags & mask)!=0;
  35795. }else if( (*pArg)==0 ){
  35796. pFile->ctrlFlags &= ~mask;
  35797. }else{
  35798. pFile->ctrlFlags |= mask;
  35799. }
  35800. }
  35801. /* Forward declaration */
  35802. static int rttGetTempname(int nBuf, char *zBuf);
  35803. /*
  35804. ** Information and control of an open file handle.
  35805. */
  35806. static int rttFileControl(sqlite3_file *id, int op, void *pArg){
  35807. rttFile *pFile = (rttFile*)id;
  35808. switch( op ){
  35809. case SQLITE_FCNTL_LOCKSTATE: {
  35810. *(int*)pArg = pFile->eFileLock;
  35811. return SQLITE_OK;
  35812. }
  35813. case SQLITE_LAST_ERRNO: {
  35814. *(int*)pArg = pFile->lastErrno;
  35815. return SQLITE_OK;
  35816. }
  35817. case SQLITE_FCNTL_CHUNK_SIZE: {
  35818. pFile->szChunk = *(int *)pArg;
  35819. return SQLITE_OK;
  35820. }
  35821. case SQLITE_FCNTL_SIZE_HINT: {
  35822. int rc;
  35823. SimulateIOErrorBenign(1);
  35824. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  35825. SimulateIOErrorBenign(0);
  35826. return rc;
  35827. }
  35828. case SQLITE_FCNTL_PERSIST_WAL: {
  35829. rttModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  35830. return SQLITE_OK;
  35831. }
  35832. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  35833. rttModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  35834. return SQLITE_OK;
  35835. }
  35836. case SQLITE_FCNTL_VFSNAME: {
  35837. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  35838. return SQLITE_OK;
  35839. }
  35840. case SQLITE_FCNTL_TEMPFILENAME: {
  35841. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  35842. if( zTFile ){
  35843. rttGetTempname(pFile->pVfs->mxPathname, zTFile);
  35844. *(char**)pArg = zTFile;
  35845. }
  35846. return SQLITE_OK;
  35847. }
  35848. #ifdef SQLITE_DEBUG
  35849. /* The pager calls this method to signal that it has done
  35850. ** a rollback and that the database is therefore unchanged and
  35851. ** it hence it is OK for the transaction change counter to be
  35852. ** unchanged.
  35853. */
  35854. case SQLITE_FCNTL_DB_UNCHANGED: {
  35855. ((rttFile*)id)->dbUpdate = 0;
  35856. return SQLITE_OK;
  35857. }
  35858. #endif
  35859. }
  35860. return SQLITE_NOTFOUND;
  35861. }
  35862. /*
  35863. ** Return the sector size in bytes of the underlying block device for
  35864. ** the specified file. This is almost always 512 bytes, but may be
  35865. ** larger for some devices.
  35866. **
  35867. ** SQLite code assumes this function cannot fail. It also assumes that
  35868. ** if two files are created in the same file-system directory (i.e.
  35869. ** a database and its journal file) that the sector size will be the
  35870. ** same for both.
  35871. */
  35872. static int rttSectorSize(sqlite3_file *NotUsed){
  35873. UNUSED_PARAMETER(NotUsed);
  35874. return SQLITE_DEFAULT_SECTOR_SIZE;
  35875. }
  35876. /*
  35877. ** Return the device characteristics for the file.
  35878. **
  35879. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  35880. ** However, that choice is contraversial since technically the underlying
  35881. ** file system does not always provide powersafe overwrites. (In other
  35882. ** words, after a power-loss event, parts of the file that were never
  35883. ** written might end up being altered.) However, non-PSOW behavior is very,
  35884. ** very rare. And asserting PSOW makes a large reduction in the amount
  35885. ** of required I/O for journaling, since a lot of padding is eliminated.
  35886. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  35887. ** available to turn it off and URI query parameter available to turn it off.
  35888. */
  35889. static int rttDeviceCharacteristics(sqlite3_file *id){
  35890. rttFile *p = (rttFile*)id;
  35891. int rc = 0;
  35892. if( p->ctrlFlags & UNIXFILE_PSOW ){
  35893. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  35894. }
  35895. return rc;
  35896. }
  35897. #ifndef SQLITE_OMIT_WAL
  35898. # error "WAL mode requires not support from the rt-thread, compile\
  35899. with SQLITE_OMIT_WAL."
  35900. #else
  35901. # define rttShmMap 0
  35902. # define rttShmLock 0
  35903. # define rttShmBarrier 0
  35904. # define rttShmUnmap 0
  35905. #endif /* #ifndef SQLITE_OMIT_WAL */
  35906. #if SQLITE_MAX_MMAP_SIZE>0
  35907. #error "rtt not spportt mmap"
  35908. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35909. /*
  35910. ** If possible, return a pointer to a mapping of file fd starting at offset
  35911. ** iOff. The mapping must be valid for at least nAmt bytes.
  35912. **
  35913. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35914. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35915. ** Finally, if an error does occur, return an SQLite error code. The final
  35916. ** value of *pp is undefined in this case.
  35917. **
  35918. ** If this function does return a pointer, the caller must eventually
  35919. ** release the reference by calling unixUnfetch().
  35920. */
  35921. static int rttFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35922. *pp = 0;
  35923. return SQLITE_OK;
  35924. }
  35925. /*
  35926. ** If the third argument is non-NULL, then this function releases a
  35927. ** reference obtained by an earlier call to unixFetch(). The second
  35928. ** argument passed to this function must be the same as the corresponding
  35929. ** argument that was passed to the unixFetch() invocation.
  35930. **
  35931. ** Or, if the third argument is NULL, then this function is being called
  35932. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35933. ** may now be invalid and should be unmapped.
  35934. */
  35935. static int rttUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35936. rttFile *pFd = (rttFile *)fd; /* The underlying database file */
  35937. UNUSED_PARAMETER(iOff);
  35938. return SQLITE_OK;
  35939. }
  35940. /*
  35941. ** Here ends the implementation of all sqlite3_file methods.
  35942. **
  35943. ********************** End sqlite3_file Methods *******************************
  35944. ******************************************************************************/
  35945. /*
  35946. ** This division contains definitions of sqlite3_io_methods objects that
  35947. ** implement various file locking strategies. It also contains definitions
  35948. ** of "finder" functions. A finder-function is used to locate the appropriate
  35949. ** sqlite3_io_methods object for a particular database file. The pAppData
  35950. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  35951. ** the correct finder-function for that VFS.
  35952. **
  35953. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  35954. ** object. The only interesting finder-function is autolockIoFinder, which
  35955. ** looks at the filesystem type and tries to guess the best locking
  35956. ** strategy from that.
  35957. **
  35958. ** For finder-funtion F, two objects are created:
  35959. **
  35960. ** (1) The real finder-function named "FImpt()".
  35961. **
  35962. ** (2) A constant pointer to this function named just "F".
  35963. **
  35964. **
  35965. ** A pointer to the F pointer is used as the pAppData value for VFS
  35966. ** objects. We have to do this instead of letting pAppData point
  35967. ** directly at the finder-function since C90 rules prevent a void*
  35968. ** from be cast into a function pointer.
  35969. **
  35970. **
  35971. ** Each instance of this macro generates two objects:
  35972. **
  35973. ** * A constant sqlite3_io_methods object call METHOD that has locking
  35974. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  35975. **
  35976. ** * An I/O method finder function called FINDER that returns a pointer
  35977. ** to the METHOD object in the previous bullet.
  35978. */
  35979. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  35980. static const sqlite3_io_methods METHOD = { \
  35981. VERSION, /* iVersion */ \
  35982. CLOSE, /* xClose */ \
  35983. rttRead, /* xRead */ \
  35984. rttWrite, /* xWrite */ \
  35985. rttTruncate, /* xTruncate */ \
  35986. rttSync, /* xSync */ \
  35987. rttFileSize, /* xFileSize */ \
  35988. LOCK, /* xLock */ \
  35989. UNLOCK, /* xUnlock */ \
  35990. CKLOCK, /* xCheckReservedLock */ \
  35991. rttFileControl, /* xFileControl */ \
  35992. rttSectorSize, /* xSectorSize */ \
  35993. rttDeviceCharacteristics, /* xDeviceCapabilities */ \
  35994. rttShmMap, /* xShmMap */ \
  35995. rttShmLock, /* xShmLock */ \
  35996. rttShmBarrier, /* xShmBarrier */ \
  35997. rttShmUnmap, /* xShmUnmap */ \
  35998. rttFetch, /* xFetch */ \
  35999. rttUnfetch, /* xUnfetch */ \
  36000. }; \
  36001. static const sqlite3_io_methods *FINDER##Impl(const char *z, rttFile *p){ \
  36002. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  36003. return &METHOD; \
  36004. } \
  36005. static const sqlite3_io_methods *(*const FINDER)(const char*,rttFile *p) \
  36006. = FINDER##Impl;
  36007. /*
  36008. ** Here are all of the sqlite3_io_methods objects for each of the
  36009. ** locking strategies. Functions that return pointers to these methods
  36010. ** are also created.
  36011. */
  36012. IOMETHODS(
  36013. nolockIoFinder, /* Finder function name */
  36014. nolockIoMethods, /* sqlite3_io_methods object name */
  36015. 1, /* shared memory is disabled */
  36016. nolockClose, /* xClose method */
  36017. nolockLock, /* xLock method */
  36018. nolockUnlock, /* xUnlock method */
  36019. nolockCheckReservedLock /* xCheckReservedLock method */
  36020. )
  36021. IOMETHODS(
  36022. dotlockIoFinder, /* Finder function name */
  36023. dotlockIoMethods, /* sqlite3_io_methods object name */
  36024. 1, /* shared memory is disabled */
  36025. dotlockClose, /* xClose method */
  36026. dotlockLock, /* xLock method */
  36027. dotlockUnlock, /* xUnlock method */
  36028. dotlockCheckReservedLock /* xCheckReservedLock method */
  36029. )
  36030. #if SQLITE_ENABLE_LOCKING_STYLE
  36031. IOMETHODS(
  36032. flockIoFinder, /* Finder function name */
  36033. flockIoMethods, /* sqlite3_io_methods object name */
  36034. 1, /* shared memory is disabled */
  36035. flockClose, /* xClose method */
  36036. flockLock, /* xLock method */
  36037. flockUnlock, /* xUnlock method */
  36038. flockCheckReservedLock /* xCheckReservedLock method */
  36039. )
  36040. #endif
  36041. /*
  36042. ** An abstract type for a pointer to a IO method finder function:
  36043. */
  36044. typedef const sqlite3_io_methods *(*finder_type)(const char*,rttFile*);
  36045. /****************************************************************************
  36046. **************************** sqlite3_vfs methods ****************************
  36047. **
  36048. ** This division contains the implementation of methods on the
  36049. ** sqlite3_vfs object.
  36050. */
  36051. /*
  36052. ** Initialize the contents of the rttFile structure pointed to by pId.
  36053. */
  36054. static int fillInRttFile(
  36055. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36056. int h, /* Open file descriptor of file being opened */
  36057. sqlite3_file *pId, /* Write to the rttFile structure here */
  36058. const char *zFilename, /* Name of the file being opened */
  36059. int ctrlFlags /* Zero or more UNIXFILE_* values */
  36060. ){
  36061. const sqlite3_io_methods *pLockingStyle;
  36062. rttFile *pNew = (rttFile *)pId;
  36063. int rc = SQLITE_OK;
  36064. assert( pNew->pInode==NULL );
  36065. /* Usually the path zFilename should not be a relative pathname. The
  36066. ** exception is when opening the proxy "conch" file in builds that
  36067. ** include the special Apple locking styles.
  36068. */
  36069. assert( zFilename==0 || zFilename[0]=='/' );
  36070. /* No locking occurs in temporary files */
  36071. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  36072. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  36073. pNew->h = h;
  36074. pNew->pVfs = pVfs;
  36075. pNew->zPath = zFilename;
  36076. pNew->ctrlFlags = (u8)ctrlFlags;
  36077. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  36078. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36079. pNew->ctrlFlags |= UNIXFILE_PSOW;
  36080. }
  36081. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  36082. pNew->ctrlFlags |= UNIXFILE_EXCL;
  36083. }
  36084. if( ctrlFlags & UNIXFILE_NOLOCK ){
  36085. pLockingStyle = &nolockIoMethods;
  36086. }else{
  36087. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  36088. #if SQLITE_ENABLE_LOCKING_STYLE
  36089. /* Cache zFilename in the locking context (AFP and dotlock override) for
  36090. ** proxyLock activation is possible (remote proxy is based on db name)
  36091. ** zFilename remains valid until file is closed, to support */
  36092. pNew->lockingContext = (void*)zFilename;
  36093. #endif
  36094. }
  36095. if( pLockingStyle == &dotlockIoMethods ){
  36096. /* Dotfile locking uses the file path so it needs to be included in
  36097. ** the dotlockLockingContext
  36098. */
  36099. char *zLockFile;
  36100. int nFilename;
  36101. assert( zFilename!=0 );
  36102. nFilename = (int)strlen(zFilename) + 6;
  36103. zLockFile = (char *)sqlite3_malloc(nFilename);
  36104. if( zLockFile==0 ){
  36105. rc = SQLITE_NOMEM;
  36106. }else{
  36107. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  36108. }
  36109. pNew->lockingContext = zLockFile;
  36110. }
  36111. pNew->lastErrno = 0;
  36112. if( rc!=SQLITE_OK ){
  36113. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36114. }else{
  36115. pNew->pMethod = pLockingStyle;
  36116. OpenCounter(+1);
  36117. verifyDbFile(pNew);
  36118. }
  36119. return rc;
  36120. }
  36121. /*
  36122. ** Return the name of a directory in which to put temporary files.
  36123. ** If no suitable temporary file directory can be found, return NULL.
  36124. */
  36125. static const char *rttTempFileDir(void){
  36126. static const char *azDirs[] = {
  36127. 0,
  36128. "/sql",
  36129. "/sql/tmp"
  36130. "/tmp",
  36131. 0 /* List terminator */
  36132. };
  36133. unsigned int i;
  36134. struct stat buf;
  36135. const char *zDir = 0;
  36136. azDirs[0] = sqlite3_temp_directory;
  36137. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  36138. if( zDir==0 ) continue;
  36139. if( osStat(zDir, &buf) ) continue;
  36140. if( !S_ISDIR(buf.st_mode) ) continue;
  36141. break;
  36142. }
  36143. return zDir;
  36144. }
  36145. /*
  36146. ** Create a temporary file name in zBuf. zBuf must be allocated
  36147. ** by the calling process and must be big enough to hold at least
  36148. ** pVfs->mxPathname bytes.
  36149. */
  36150. static int rttGetTempname(int nBuf, char *zBuf){
  36151. static const unsigned char zChars[] =
  36152. "abcdefghijklmnopqrstuvwxyz"
  36153. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36154. "0123456789";
  36155. unsigned int i, j;
  36156. const char *zDir;
  36157. /* It's odd to simulate an io-error here, but really this is just
  36158. ** using the io-error infrastructure to test that SQLite handles this
  36159. ** function failing.
  36160. */
  36161. SimulateIOError( return SQLITE_IOERR );
  36162. zDir = rttTempFileDir();
  36163. if( zDir==0 ) zDir = ".";
  36164. /* Check that the output buffer is large enough for the temporary file
  36165. ** name. If it is not, return SQLITE_ERROR.
  36166. */
  36167. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  36168. return SQLITE_ERROR;
  36169. }
  36170. do{
  36171. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  36172. j = (int)strlen(zBuf);
  36173. sqlite3_randomness(15, &zBuf[j]);
  36174. for(i=0; i<15; i++, j++){
  36175. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  36176. }
  36177. zBuf[j] = 0;
  36178. zBuf[j+1] = 0;
  36179. }while( osAccess(zBuf,0)==0 );
  36180. return SQLITE_OK;
  36181. }
  36182. /*
  36183. ** Open the file zPath.
  36184. **
  36185. ** Previously, the SQLite OS layer used three functions in place of this
  36186. ** one:
  36187. **
  36188. ** sqlite3OsOpenReadWrite();
  36189. ** sqlite3OsOpenReadOnly();
  36190. ** sqlite3OsOpenExclusive();
  36191. **
  36192. ** These calls correspond to the following combinations of flags:
  36193. **
  36194. ** ReadWrite() -> (READWRITE | CREATE)
  36195. ** ReadOnly() -> (READONLY)
  36196. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  36197. **
  36198. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  36199. ** true, the file was configured to be automatically deleted when the
  36200. ** file handle closed. To achieve the same effect using this new
  36201. ** interface, add the DELETEONCLOSE flag to those specified above for
  36202. ** OpenExclusive().
  36203. */
  36204. static int rttOpen(
  36205. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  36206. const char *zPath, /* Pathname of file to be opened */
  36207. sqlite3_file *pFile, /* The file descriptor to be filled in */
  36208. int flags, /* Input flags to control the opening */
  36209. int *pOutFlags /* Output flags returned to SQLite core */
  36210. ){
  36211. rttFile *p = (rttFile *)pFile;
  36212. int fd = -1; /* File descriptor returned by open() */
  36213. int openFlags = 0; /* Flags to pass to open() */
  36214. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36215. int noLock; /* True to omit locking primitives */
  36216. int rc = SQLITE_OK; /* Function Return Code */
  36217. int ctrlFlags = 0; /* UNIXFILE_* flags */
  36218. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36219. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36220. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36221. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36222. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36223. #if SQLITE_ENABLE_LOCKING_STYLE
  36224. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  36225. #endif
  36226. /* If creating a master or main-file journal, this function will open
  36227. ** a file-descriptor on the directory too. The first time unixSync()
  36228. ** is called the directory file descriptor will be fsync()ed and close()d.
  36229. */
  36230. int syncDir = (isCreate && (
  36231. eType==SQLITE_OPEN_MASTER_JOURNAL
  36232. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36233. || eType==SQLITE_OPEN_WAL
  36234. ));
  36235. /* If argument zPath is a NULL pointer, this function is required to open
  36236. ** a temporary file. Use this buffer to store the file name in.
  36237. */
  36238. char zTmpname[MAX_PATHNAME+2];
  36239. const char *zName = zPath;
  36240. /* Check the following statements are true:
  36241. **
  36242. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36243. ** (b) if CREATE is set, then READWRITE must also be set, and
  36244. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36245. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36246. */
  36247. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36248. assert(isCreate==0 || isReadWrite);
  36249. assert(isExclusive==0 || isCreate);
  36250. assert(isDelete==0 || isCreate);
  36251. /* The main DB, main journal, WAL file and master journal are never
  36252. ** automatically deleted. Nor are they ever temporary files. */
  36253. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36254. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36255. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36256. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36257. /* Assert that the upper layer has set one of the "file-type" flags. */
  36258. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36259. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36260. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36261. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36262. );
  36263. memset(p, 0, sizeof(rttFile));
  36264. if( !zName ){
  36265. /* If zName is NULL, the upper layer is requesting a temp file. */
  36266. assert(isDelete && !syncDir);
  36267. rc = rttGetTempname(MAX_PATHNAME+2, zTmpname);
  36268. if( rc!=SQLITE_OK ){
  36269. return rc;
  36270. }
  36271. zName = zTmpname;
  36272. /* Generated temporary filenames are always double-zero terminated
  36273. ** for use by sqlite3_uri_parameter(). */
  36274. assert( zName[strlen(zName)+1]==0 );
  36275. }
  36276. /* Determine the value of the flags parameter passed to POSIX function
  36277. ** open(). These must be calculated even if open() is not called, as
  36278. ** they may be stored as part of the file handle and used by the
  36279. ** 'conch file' locking functions later on. */
  36280. if( isReadonly ) openFlags |= O_RDONLY;
  36281. if( isReadWrite ) openFlags |= O_RDWR;
  36282. if( isCreate ) openFlags |= O_CREAT;
  36283. if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/);
  36284. openFlags |= (0/*O_LARGEFILE*/|O_BINARY);
  36285. if( fd<0 ){
  36286. mode_t openMode = 0; /* Permissions to create file with */
  36287. fd = robust_open(zName, openFlags, openMode);
  36288. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  36289. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  36290. /* Failed to open the file for read/write access. Try read-only. */
  36291. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  36292. openFlags &= ~(O_RDWR|O_CREAT);
  36293. flags |= SQLITE_OPEN_READONLY;
  36294. openFlags |= O_RDONLY;
  36295. isReadonly = 1;
  36296. fd = robust_open(zName, openFlags, openMode);
  36297. }
  36298. if( fd<0 ){
  36299. rc = rttLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  36300. goto open_finished;
  36301. }
  36302. }
  36303. assert( fd>=0 );
  36304. if( pOutFlags ){
  36305. *pOutFlags = flags;
  36306. }
  36307. if( isDelete ){
  36308. osUnlink(zName);
  36309. }
  36310. #if SQLITE_ENABLE_LOCKING_STYLE
  36311. else{
  36312. p->openFlags = openFlags;
  36313. }
  36314. #endif
  36315. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  36316. /* Set up appropriate ctrlFlags */
  36317. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  36318. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  36319. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  36320. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  36321. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  36322. rc = fillInRttFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36323. open_finished:
  36324. return rc;
  36325. }
  36326. /*
  36327. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  36328. ** the directory after deleting the file.
  36329. */
  36330. static int rttDelete(
  36331. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  36332. const char *zPath, /* Name of file to be deleted */
  36333. int dirSync /* If true, fsync() directory after deleting file */
  36334. ){
  36335. int rc = SQLITE_OK;
  36336. UNUSED_PARAMETER(NotUsed);
  36337. SimulateIOError(return SQLITE_IOERR_DELETE);
  36338. if( osUnlink(zPath)==(-1) ){
  36339. if( errno==ENOENT ){
  36340. rc = SQLITE_IOERR_DELETE_NOENT;
  36341. }else{
  36342. rc = rttLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  36343. }
  36344. return rc;
  36345. }
  36346. #ifndef SQLITE_DISABLE_DIRSYNC
  36347. if( (dirSync & 1)!=0 ){
  36348. int fd;
  36349. rc = osOpenDirectory(zPath, &fd);
  36350. if( rc==SQLITE_OK ){
  36351. robust_close(0, fd, __LINE__);
  36352. }else if( rc==SQLITE_CANTOPEN ){
  36353. rc = SQLITE_OK;
  36354. }
  36355. }
  36356. #endif
  36357. return rc;
  36358. }
  36359. /*
  36360. ** Test the existence of or access permissions of file zPath. The
  36361. ** test performed depends on the value of flags:
  36362. **
  36363. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  36364. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  36365. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  36366. **
  36367. ** Otherwise return 0.
  36368. */
  36369. static int rttAccess(
  36370. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  36371. const char *zPath, /* Path of the file to examine */
  36372. int flags, /* What do we want to learn about the zPath file? */
  36373. int *pResOut /* Write result boolean here */
  36374. ){
  36375. int amode = 0;
  36376. UNUSED_PARAMETER(NotUsed);
  36377. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36378. switch( flags ){
  36379. case SQLITE_ACCESS_EXISTS:
  36380. amode = F_OK;
  36381. break;
  36382. case SQLITE_ACCESS_READWRITE:
  36383. amode = W_OK|R_OK;
  36384. break;
  36385. case SQLITE_ACCESS_READ:
  36386. amode = R_OK;
  36387. break;
  36388. default:
  36389. assert(!"Invalid flags argument");
  36390. }
  36391. *pResOut = (osAccess(zPath, amode)==0);
  36392. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  36393. struct stat buf;
  36394. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  36395. *pResOut = 0;
  36396. }
  36397. }
  36398. return SQLITE_OK;
  36399. }
  36400. /*
  36401. ** Turn a relative pathname into a full pathname. The relative path
  36402. ** is stored as a nul-terminated string in the buffer pointed to by
  36403. ** zPath.
  36404. **
  36405. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  36406. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  36407. ** this buffer before returning.
  36408. */
  36409. static int rttFullPathname(
  36410. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36411. const char *zPath, /* Possibly relative input path */
  36412. int nOut, /* Size of output buffer in bytes */
  36413. char *zOut /* Output buffer */
  36414. ){
  36415. /* It's odd to simulate an io-error here, but really this is just
  36416. ** using the io-error infrastructure to test that SQLite handles this
  36417. ** function failing. This function could fail if, for example, the
  36418. ** current working directory has been unlinked.
  36419. */
  36420. SimulateIOError( return SQLITE_ERROR );
  36421. assert( pVfs->mxPathname==MAX_PATHNAME );
  36422. UNUSED_PARAMETER(pVfs);
  36423. zOut[nOut-1] = '\0';
  36424. if( zPath[0]=='/' ){
  36425. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  36426. }else{
  36427. int nCwd;
  36428. if( osGetcwd(zOut, nOut-1)==0 ){
  36429. return rttLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  36430. }
  36431. nCwd = (int)strlen(zOut);
  36432. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  36433. }
  36434. return SQLITE_OK;
  36435. }
  36436. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36437. # error "rtt not support load extension, compile with SQLITE_OMIT_WAL."
  36438. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36439. #define rttDlOpen 0
  36440. #define rttDlError 0
  36441. #define rttDlSym 0
  36442. #define rttDlClose 0
  36443. #endif
  36444. /*
  36445. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  36446. */
  36447. static int rttRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  36448. UNUSED_PARAMETER(NotUsed);
  36449. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  36450. /* We have to initialize zBuf to prevent valgrind from reporting
  36451. ** errors. The reports issued by valgrind are incorrect - we would
  36452. ** prefer that the randomness be increased by making use of the
  36453. ** uninitialized space in zBuf - but valgrind errors tend to worry
  36454. ** some users. Rather than argue, it seems easier just to initialize
  36455. ** the whole array and silence valgrind, even if that means less randomness
  36456. ** in the random seed.
  36457. **
  36458. ** When testing, initializing zBuf[] to zero is all we do. That means
  36459. ** that we always use the same random number sequence. This makes the
  36460. ** tests repeatable.
  36461. */
  36462. memset(zBuf, 0, nBuf);
  36463. {
  36464. int i;
  36465. char tick8, tick16;
  36466. tick8 = (char)rt_tick_get();
  36467. tick16 = (char)(rt_tick_get() >> 8);
  36468. for (i=0; i<nBuf; i++)
  36469. {
  36470. zBuf[i] = (char)(i ^ tick8 ^ tick16);
  36471. tick8 = zBuf[i];
  36472. tick16 = ~(tick8 ^ tick16);
  36473. }
  36474. }
  36475. return nBuf;
  36476. }
  36477. /*
  36478. ** Sleep for a little while. Return the amount of time slept.
  36479. ** The argument is the number of microseconds we want to sleep.
  36480. ** The return value is the number of microseconds of sleep actually
  36481. ** requested from the underlying operating system, a number which
  36482. ** might be greater than or equal to the argument, but not less
  36483. ** than the argument.
  36484. */
  36485. static int rttSleep(sqlite3_vfs *NotUsed, int microseconds){
  36486. int seconds = (microseconds+999999)/1000000;
  36487. osSleep(seconds * 1000);
  36488. UNUSED_PARAMETER(NotUsed);
  36489. return seconds*1000000;
  36490. }
  36491. /*
  36492. ** The following variable, if set to a non-zero value, is interpreted as
  36493. ** the number of seconds since 1970 and is used to set the result of
  36494. ** sqlite3OsCurrentTime() during testing.
  36495. */
  36496. #ifdef SQLITE_TEST
  36497. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36498. #endif
  36499. #ifndef NO_GETTOD
  36500. #define NO_GETTOD 1
  36501. #endif
  36502. /*
  36503. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36504. ** the current time and date as a Julian Day number times 86_400_000. In
  36505. ** other words, write into *piNow the number of milliseconds since the Julian
  36506. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36507. ** proleptic Gregorian calendar.
  36508. **
  36509. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36510. ** cannot be found.
  36511. */
  36512. static int rttCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36513. static const sqlite3_int64 rttEpoch = 24405875*(sqlite3_int64)8640000;
  36514. int rc = SQLITE_OK;
  36515. #if defined(NO_GETTOD)
  36516. time_t t;
  36517. time(&t);
  36518. *piNow = ((sqlite3_int64)t)*1000 + rttEpoch;
  36519. #else
  36520. struct timeval sNow;
  36521. if( gettimeofday(&sNow, 0)==0 ){
  36522. *piNow = rttEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36523. }else{
  36524. rc = SQLITE_ERROR;
  36525. }
  36526. #endif
  36527. #ifdef SQLITE_TEST
  36528. if( sqlite3_current_time ){
  36529. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + rttEpoch;
  36530. }
  36531. #endif
  36532. UNUSED_PARAMETER(NotUsed);
  36533. return rc;
  36534. }
  36535. /*
  36536. ** Find the current time (in Universal Coordinated Time). Write the
  36537. ** current time and date as a Julian Day number into *prNow and
  36538. ** return 0. Return 1 if the time and date cannot be found.
  36539. */
  36540. static int rttCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  36541. sqlite3_int64 i = 0;
  36542. int rc;
  36543. UNUSED_PARAMETER(NotUsed);
  36544. rc = rttCurrentTimeInt64(0, &i);
  36545. *prNow = i/86400000.0;
  36546. return rc;
  36547. }
  36548. /*
  36549. ** We added the xGetLastError() method with the intention of providing
  36550. ** better low-level error messages when operating-system problems come up
  36551. ** during SQLite operation. But so far, none of that has been implemented
  36552. ** in the core. So this routine is never called. For now, it is merely
  36553. ** a place-holder.
  36554. */
  36555. static int rttGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  36556. UNUSED_PARAMETER(NotUsed);
  36557. UNUSED_PARAMETER(NotUsed2);
  36558. UNUSED_PARAMETER(NotUsed3);
  36559. return 0;
  36560. }
  36561. /*
  36562. ************************ End of sqlite3_vfs methods ***************************
  36563. ******************************************************************************/
  36564. /*
  36565. ** Initialize the operating system interface.
  36566. **
  36567. ** This routine registers all VFS implementations for unix-like operating
  36568. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  36569. ** should be the only routines in this file that are visible from other
  36570. ** files.
  36571. **
  36572. ** This routine is called once during SQLite initialization and by a
  36573. ** single thread. The memory allocation and mutex subsystems have not
  36574. ** necessarily been initialized when this routine is called, and so they
  36575. ** should not be used.
  36576. */
  36577. /*
  36578. ** The following macro defines an initializer for an sqlite3_vfs object.
  36579. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  36580. ** to the "finder" function. (pAppData is a pointer to a pointer because
  36581. ** silly C90 rules prohibit a void* from being cast to a function pointer
  36582. ** and so we have to go through the intermediate pointer to avoid problems
  36583. ** when compiling with -pedantic-errors on GCC.)
  36584. **
  36585. ** The FINDER parameter to this macro is the name of the pointer to the
  36586. ** finder-function. The finder-function returns a pointer to the
  36587. ** sqlite_io_methods object that implements the desired locking
  36588. ** behaviors. See the division above that contains the IOMETHODS
  36589. ** macro for addition information on finder-functions.
  36590. **
  36591. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  36592. ** object. But the "autolockIoFinder" available on MacOSX does a little
  36593. ** more than that; it looks at the filesystem type that hosts the
  36594. ** database file and tries to choose an locking method appropriate for
  36595. ** that filesystem time.
  36596. */
  36597. #define UNIXVFS(VFSNAME, FINDER) { \
  36598. 3, /* iVersion */ \
  36599. sizeof(rttFile), /* szOsFile */ \
  36600. MAX_PATHNAME, /* mxPathname */ \
  36601. 0, /* pNext */ \
  36602. VFSNAME, /* zName */ \
  36603. (void*)&FINDER, /* pAppData */ \
  36604. rttOpen, /* xOpen */ \
  36605. rttDelete, /* xDelete */ \
  36606. rttAccess, /* xAccess */ \
  36607. rttFullPathname, /* xFullPathname */ \
  36608. rttDlOpen, /* xDlOpen */ \
  36609. rttDlError, /* xDlError */ \
  36610. rttDlSym, /* xDlSym */ \
  36611. rttDlClose, /* xDlClose */ \
  36612. rttRandomness, /* xRandomness */ \
  36613. rttSleep, /* xSleep */ \
  36614. rttCurrentTime, /* xCurrentTime */ \
  36615. rttGetLastError, /* xGetLastError */ \
  36616. rttCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  36617. rttSetSystemCall, /* xSetSystemCall */ \
  36618. rttGetSystemCall, /* xGetSystemCall */ \
  36619. rttNextSystemCall, /* xNextSystemCall */ \
  36620. }
  36621. SQLITE_API int sqlite3_os_init(void){
  36622. /*
  36623. ** All default VFSes for unix are contained in the following array.
  36624. **
  36625. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  36626. ** by the SQLite core when the VFS is registered. So the following
  36627. ** array cannot be const.
  36628. */
  36629. static sqlite3_vfs aVfs[] = {
  36630. UNIXVFS("unix-none", nolockIoFinder ),
  36631. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  36632. #if SQLITE_ENABLE_LOCKING_STYLE
  36633. UNIXVFS("unix-flock", flockIoFinder ),
  36634. #endif
  36635. };
  36636. unsigned int i; /* Loop counter */
  36637. /* Double-check that the aSyscall[] array has been constructed
  36638. ** correctly. See ticket [bb3a86e890c8e96ab] */
  36639. assert( ArraySize(aSyscall)==24 );
  36640. /* Register all VFSes defined in the aVfs[] array */
  36641. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  36642. sqlite3_vfs_register(&aVfs[i], i==0);
  36643. }
  36644. return SQLITE_OK;
  36645. }
  36646. /*
  36647. ** Shutdown the operating system interface.
  36648. **
  36649. ** Some operating systems might need to do some cleanup in this routine,
  36650. ** to release dynamically allocated objects. But not on unix.
  36651. ** This routine is a no-op for unix.
  36652. */
  36653. SQLITE_API int sqlite3_os_end(void){
  36654. return SQLITE_OK;
  36655. }
  36656. #endif /* SQLITE_OS_RTT */
  36657. /************** End of os_rtt.c **********************************************/
  36658. /************** Begin file bitvec.c ******************************************/
  36659. /*
  36660. ** 2008 February 16
  36661. **
  36662. ** The author disclaims copyright to this source code. In place of
  36663. ** a legal notice, here is a blessing:
  36664. **
  36665. ** May you do good and not evil.
  36666. ** May you find forgiveness for yourself and forgive others.
  36667. ** May you share freely, never taking more than you give.
  36668. **
  36669. *************************************************************************
  36670. ** This file implements an object that represents a fixed-length
  36671. ** bitmap. Bits are numbered starting with 1.
  36672. **
  36673. ** A bitmap is used to record which pages of a database file have been
  36674. ** journalled during a transaction, or which pages have the "dont-write"
  36675. ** property. Usually only a few pages are meet either condition.
  36676. ** So the bitmap is usually sparse and has low cardinality.
  36677. ** But sometimes (for example when during a DROP of a large table) most
  36678. ** or all of the pages in a database can get journalled. In those cases,
  36679. ** the bitmap becomes dense with high cardinality. The algorithm needs
  36680. ** to handle both cases well.
  36681. **
  36682. ** The size of the bitmap is fixed when the object is created.
  36683. **
  36684. ** All bits are clear when the bitmap is created. Individual bits
  36685. ** may be set or cleared one at a time.
  36686. **
  36687. ** Test operations are about 100 times more common that set operations.
  36688. ** Clear operations are exceedingly rare. There are usually between
  36689. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  36690. ** sometimes grow into tens of thousands or larger. The size of the
  36691. ** Bitvec object is the number of pages in the database file at the
  36692. ** start of a transaction, and is thus usually less than a few thousand,
  36693. ** but can be as large as 2 billion for a really big database.
  36694. */
  36695. /* Size of the Bitvec structure in bytes. */
  36696. #define BITVEC_SZ 512
  36697. /* Round the union size down to the nearest pointer boundary, since that's how
  36698. ** it will be aligned within the Bitvec struct. */
  36699. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  36700. /* Type of the array "element" for the bitmap representation.
  36701. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  36702. ** Setting this to the "natural word" size of your CPU may improve
  36703. ** performance. */
  36704. #define BITVEC_TELEM u8
  36705. /* Size, in bits, of the bitmap element. */
  36706. #define BITVEC_SZELEM 8
  36707. /* Number of elements in a bitmap array. */
  36708. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  36709. /* Number of bits in the bitmap array. */
  36710. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  36711. /* Number of u32 values in hash table. */
  36712. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  36713. /* Maximum number of entries in hash table before
  36714. ** sub-dividing and re-hashing. */
  36715. #define BITVEC_MXHASH (BITVEC_NINT/2)
  36716. /* Hashing function for the aHash representation.
  36717. ** Empirical testing showed that the *37 multiplier
  36718. ** (an arbitrary prime)in the hash function provided
  36719. ** no fewer collisions than the no-op *1. */
  36720. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  36721. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  36722. /*
  36723. ** A bitmap is an instance of the following structure.
  36724. **
  36725. ** This bitmap records the existence of zero or more bits
  36726. ** with values between 1 and iSize, inclusive.
  36727. **
  36728. ** There are three possible representations of the bitmap.
  36729. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  36730. ** bitmap. The least significant bit is bit 1.
  36731. **
  36732. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  36733. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  36734. **
  36735. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  36736. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  36737. ** handles up to iDivisor separate values of i. apSub[0] holds
  36738. ** values between 1 and iDivisor. apSub[1] holds values between
  36739. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  36740. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  36741. ** to hold deal with values between 1 and iDivisor.
  36742. */
  36743. struct Bitvec {
  36744. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  36745. u32 nSet; /* Number of bits that are set - only valid for aHash
  36746. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  36747. ** this would be 125. */
  36748. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  36749. /* Should >=0 for apSub element. */
  36750. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  36751. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  36752. union {
  36753. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  36754. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  36755. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  36756. } u;
  36757. };
  36758. /*
  36759. ** Create a new bitmap object able to handle bits between 0 and iSize,
  36760. ** inclusive. Return a pointer to the new object. Return NULL if
  36761. ** malloc fails.
  36762. */
  36763. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  36764. Bitvec *p;
  36765. assert( sizeof(*p)==BITVEC_SZ );
  36766. p = sqlite3MallocZero( sizeof(*p) );
  36767. if( p ){
  36768. p->iSize = iSize;
  36769. }
  36770. return p;
  36771. }
  36772. /*
  36773. ** Check to see if the i-th bit is set. Return true or false.
  36774. ** If p is NULL (if the bitmap has not been created) or if
  36775. ** i is out of range, then return false.
  36776. */
  36777. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  36778. if( p==0 ) return 0;
  36779. if( i>p->iSize || i==0 ) return 0;
  36780. i--;
  36781. while( p->iDivisor ){
  36782. u32 bin = i/p->iDivisor;
  36783. i = i%p->iDivisor;
  36784. p = p->u.apSub[bin];
  36785. if (!p) {
  36786. return 0;
  36787. }
  36788. }
  36789. if( p->iSize<=BITVEC_NBIT ){
  36790. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  36791. } else{
  36792. u32 h = BITVEC_HASH(i++);
  36793. while( p->u.aHash[h] ){
  36794. if( p->u.aHash[h]==i ) return 1;
  36795. h = (h+1) % BITVEC_NINT;
  36796. }
  36797. return 0;
  36798. }
  36799. }
  36800. /*
  36801. ** Set the i-th bit. Return 0 on success and an error code if
  36802. ** anything goes wrong.
  36803. **
  36804. ** This routine might cause sub-bitmaps to be allocated. Failing
  36805. ** to get the memory needed to hold the sub-bitmap is the only
  36806. ** that can go wrong with an insert, assuming p and i are valid.
  36807. **
  36808. ** The calling function must ensure that p is a valid Bitvec object
  36809. ** and that the value for "i" is within range of the Bitvec object.
  36810. ** Otherwise the behavior is undefined.
  36811. */
  36812. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  36813. u32 h;
  36814. if( p==0 ) return SQLITE_OK;
  36815. assert( i>0 );
  36816. assert( i<=p->iSize );
  36817. i--;
  36818. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  36819. u32 bin = i/p->iDivisor;
  36820. i = i%p->iDivisor;
  36821. if( p->u.apSub[bin]==0 ){
  36822. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  36823. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  36824. }
  36825. p = p->u.apSub[bin];
  36826. }
  36827. if( p->iSize<=BITVEC_NBIT ){
  36828. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  36829. return SQLITE_OK;
  36830. }
  36831. h = BITVEC_HASH(i++);
  36832. /* if there wasn't a hash collision, and this doesn't */
  36833. /* completely fill the hash, then just add it without */
  36834. /* worring about sub-dividing and re-hashing. */
  36835. if( !p->u.aHash[h] ){
  36836. if (p->nSet<(BITVEC_NINT-1)) {
  36837. goto bitvec_set_end;
  36838. } else {
  36839. goto bitvec_set_rehash;
  36840. }
  36841. }
  36842. /* there was a collision, check to see if it's already */
  36843. /* in hash, if not, try to find a spot for it */
  36844. do {
  36845. if( p->u.aHash[h]==i ) return SQLITE_OK;
  36846. h++;
  36847. if( h>=BITVEC_NINT ) h = 0;
  36848. } while( p->u.aHash[h] );
  36849. /* we didn't find it in the hash. h points to the first */
  36850. /* available free spot. check to see if this is going to */
  36851. /* make our hash too "full". */
  36852. bitvec_set_rehash:
  36853. if( p->nSet>=BITVEC_MXHASH ){
  36854. unsigned int j;
  36855. int rc;
  36856. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  36857. if( aiValues==0 ){
  36858. return SQLITE_NOMEM;
  36859. }else{
  36860. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36861. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  36862. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  36863. rc = sqlite3BitvecSet(p, i);
  36864. for(j=0; j<BITVEC_NINT; j++){
  36865. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  36866. }
  36867. sqlite3StackFree(0, aiValues);
  36868. return rc;
  36869. }
  36870. }
  36871. bitvec_set_end:
  36872. p->nSet++;
  36873. p->u.aHash[h] = i;
  36874. return SQLITE_OK;
  36875. }
  36876. /*
  36877. ** Clear the i-th bit.
  36878. **
  36879. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  36880. ** that BitvecClear can use to rebuilt its hash table.
  36881. */
  36882. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  36883. if( p==0 ) return;
  36884. assert( i>0 );
  36885. i--;
  36886. while( p->iDivisor ){
  36887. u32 bin = i/p->iDivisor;
  36888. i = i%p->iDivisor;
  36889. p = p->u.apSub[bin];
  36890. if (!p) {
  36891. return;
  36892. }
  36893. }
  36894. if( p->iSize<=BITVEC_NBIT ){
  36895. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  36896. }else{
  36897. unsigned int j;
  36898. u32 *aiValues = pBuf;
  36899. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36900. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  36901. p->nSet = 0;
  36902. for(j=0; j<BITVEC_NINT; j++){
  36903. if( aiValues[j] && aiValues[j]!=(i+1) ){
  36904. u32 h = BITVEC_HASH(aiValues[j]-1);
  36905. p->nSet++;
  36906. while( p->u.aHash[h] ){
  36907. h++;
  36908. if( h>=BITVEC_NINT ) h = 0;
  36909. }
  36910. p->u.aHash[h] = aiValues[j];
  36911. }
  36912. }
  36913. }
  36914. }
  36915. /*
  36916. ** Destroy a bitmap object. Reclaim all memory used.
  36917. */
  36918. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  36919. if( p==0 ) return;
  36920. if( p->iDivisor ){
  36921. unsigned int i;
  36922. for(i=0; i<BITVEC_NPTR; i++){
  36923. sqlite3BitvecDestroy(p->u.apSub[i]);
  36924. }
  36925. }
  36926. sqlite3_free(p);
  36927. }
  36928. /*
  36929. ** Return the value of the iSize parameter specified when Bitvec *p
  36930. ** was created.
  36931. */
  36932. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  36933. return p->iSize;
  36934. }
  36935. #ifndef SQLITE_OMIT_BUILTIN_TEST
  36936. /*
  36937. ** Let V[] be an array of unsigned characters sufficient to hold
  36938. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  36939. ** Then the following macros can be used to set, clear, or test
  36940. ** individual bits within V.
  36941. */
  36942. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  36943. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  36944. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  36945. /*
  36946. ** This routine runs an extensive test of the Bitvec code.
  36947. **
  36948. ** The input is an array of integers that acts as a program
  36949. ** to test the Bitvec. The integers are opcodes followed
  36950. ** by 0, 1, or 3 operands, depending on the opcode. Another
  36951. ** opcode follows immediately after the last operand.
  36952. **
  36953. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  36954. ** "halt" opcode and causes the test to end.
  36955. **
  36956. ** 0 Halt and return the number of errors
  36957. ** 1 N S X Set N bits beginning with S and incrementing by X
  36958. ** 2 N S X Clear N bits beginning with S and incrementing by X
  36959. ** 3 N Set N randomly chosen bits
  36960. ** 4 N Clear N randomly chosen bits
  36961. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  36962. **
  36963. ** The opcodes 1 through 4 perform set and clear operations are performed
  36964. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  36965. ** Opcode 5 works on the linear array only, not on the Bitvec.
  36966. ** Opcode 5 is used to deliberately induce a fault in order to
  36967. ** confirm that error detection works.
  36968. **
  36969. ** At the conclusion of the test the linear array is compared
  36970. ** against the Bitvec object. If there are any differences,
  36971. ** an error is returned. If they are the same, zero is returned.
  36972. **
  36973. ** If a memory allocation error occurs, return -1.
  36974. */
  36975. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  36976. Bitvec *pBitvec = 0;
  36977. unsigned char *pV = 0;
  36978. int rc = -1;
  36979. int i, nx, pc, op;
  36980. void *pTmpSpace;
  36981. /* Allocate the Bitvec to be tested and a linear array of
  36982. ** bits to act as the reference */
  36983. pBitvec = sqlite3BitvecCreate( sz );
  36984. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  36985. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  36986. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  36987. /* NULL pBitvec tests */
  36988. sqlite3BitvecSet(0, 1);
  36989. sqlite3BitvecClear(0, 1, pTmpSpace);
  36990. /* Run the program */
  36991. pc = 0;
  36992. while( (op = aOp[pc])!=0 ){
  36993. switch( op ){
  36994. case 1:
  36995. case 2:
  36996. case 5: {
  36997. nx = 4;
  36998. i = aOp[pc+2] - 1;
  36999. aOp[pc+2] += aOp[pc+3];
  37000. break;
  37001. }
  37002. case 3:
  37003. case 4:
  37004. default: {
  37005. nx = 2;
  37006. sqlite3_randomness(sizeof(i), &i);
  37007. break;
  37008. }
  37009. }
  37010. if( (--aOp[pc+1]) > 0 ) nx = 0;
  37011. pc += nx;
  37012. i = (i & 0x7fffffff)%sz;
  37013. if( (op & 1)!=0 ){
  37014. SETBIT(pV, (i+1));
  37015. if( op!=5 ){
  37016. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  37017. }
  37018. }else{
  37019. CLEARBIT(pV, (i+1));
  37020. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  37021. }
  37022. }
  37023. /* Test to make sure the linear array exactly matches the
  37024. ** Bitvec object. Start with the assumption that they do
  37025. ** match (rc==0). Change rc to non-zero if a discrepancy
  37026. ** is found.
  37027. */
  37028. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  37029. + sqlite3BitvecTest(pBitvec, 0)
  37030. + (sqlite3BitvecSize(pBitvec) - sz);
  37031. for(i=1; i<=sz; i++){
  37032. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  37033. rc = i;
  37034. break;
  37035. }
  37036. }
  37037. /* Free allocated structure */
  37038. bitvec_end:
  37039. sqlite3_free(pTmpSpace);
  37040. sqlite3_free(pV);
  37041. sqlite3BitvecDestroy(pBitvec);
  37042. return rc;
  37043. }
  37044. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  37045. /************** End of bitvec.c **********************************************/
  37046. /************** Begin file pcache.c ******************************************/
  37047. /*
  37048. ** 2008 August 05
  37049. **
  37050. ** The author disclaims copyright to this source code. In place of
  37051. ** a legal notice, here is a blessing:
  37052. **
  37053. ** May you do good and not evil.
  37054. ** May you find forgiveness for yourself and forgive others.
  37055. ** May you share freely, never taking more than you give.
  37056. **
  37057. *************************************************************************
  37058. ** This file implements that page cache.
  37059. */
  37060. /*
  37061. ** A complete page cache is an instance of this structure.
  37062. */
  37063. struct PCache {
  37064. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  37065. PgHdr *pSynced; /* Last synced page in dirty page list */
  37066. int nRef; /* Number of referenced pages */
  37067. int szCache; /* Configured cache size */
  37068. int szPage; /* Size of every page in this cache */
  37069. int szExtra; /* Size of extra space for each page */
  37070. int bPurgeable; /* True if pages are on backing store */
  37071. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  37072. void *pStress; /* Argument to xStress */
  37073. sqlite3_pcache *pCache; /* Pluggable cache module */
  37074. PgHdr *pPage1; /* Reference to page 1 */
  37075. };
  37076. /*
  37077. ** Some of the assert() macros in this code are too expensive to run
  37078. ** even during normal debugging. Use them only rarely on long-running
  37079. ** tests. Enable the expensive asserts using the
  37080. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  37081. */
  37082. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  37083. # define expensive_assert(X) assert(X)
  37084. #else
  37085. # define expensive_assert(X)
  37086. #endif
  37087. /********************************** Linked List Management ********************/
  37088. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  37089. /*
  37090. ** Check that the pCache->pSynced variable is set correctly. If it
  37091. ** is not, either fail an assert or return zero. Otherwise, return
  37092. ** non-zero. This is only used in debugging builds, as follows:
  37093. **
  37094. ** expensive_assert( pcacheCheckSynced(pCache) );
  37095. */
  37096. static int pcacheCheckSynced(PCache *pCache){
  37097. PgHdr *p;
  37098. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  37099. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  37100. }
  37101. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  37102. }
  37103. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  37104. /*
  37105. ** Remove page pPage from the list of dirty pages.
  37106. */
  37107. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  37108. PCache *p = pPage->pCache;
  37109. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  37110. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  37111. /* Update the PCache1.pSynced variable if necessary. */
  37112. if( p->pSynced==pPage ){
  37113. PgHdr *pSynced = pPage->pDirtyPrev;
  37114. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  37115. pSynced = pSynced->pDirtyPrev;
  37116. }
  37117. p->pSynced = pSynced;
  37118. }
  37119. if( pPage->pDirtyNext ){
  37120. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  37121. }else{
  37122. assert( pPage==p->pDirtyTail );
  37123. p->pDirtyTail = pPage->pDirtyPrev;
  37124. }
  37125. if( pPage->pDirtyPrev ){
  37126. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  37127. }else{
  37128. assert( pPage==p->pDirty );
  37129. p->pDirty = pPage->pDirtyNext;
  37130. }
  37131. pPage->pDirtyNext = 0;
  37132. pPage->pDirtyPrev = 0;
  37133. expensive_assert( pcacheCheckSynced(p) );
  37134. }
  37135. /*
  37136. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  37137. ** pPage).
  37138. */
  37139. static void pcacheAddToDirtyList(PgHdr *pPage){
  37140. PCache *p = pPage->pCache;
  37141. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  37142. pPage->pDirtyNext = p->pDirty;
  37143. if( pPage->pDirtyNext ){
  37144. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  37145. pPage->pDirtyNext->pDirtyPrev = pPage;
  37146. }
  37147. p->pDirty = pPage;
  37148. if( !p->pDirtyTail ){
  37149. p->pDirtyTail = pPage;
  37150. }
  37151. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  37152. p->pSynced = pPage;
  37153. }
  37154. expensive_assert( pcacheCheckSynced(p) );
  37155. }
  37156. /*
  37157. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  37158. ** being used for an in-memory database, this function is a no-op.
  37159. */
  37160. static void pcacheUnpin(PgHdr *p){
  37161. PCache *pCache = p->pCache;
  37162. if( pCache->bPurgeable ){
  37163. if( p->pgno==1 ){
  37164. pCache->pPage1 = 0;
  37165. }
  37166. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  37167. }
  37168. }
  37169. /*************************************************** General Interfaces ******
  37170. **
  37171. ** Initialize and shutdown the page cache subsystem. Neither of these
  37172. ** functions are threadsafe.
  37173. */
  37174. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  37175. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  37176. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  37177. ** built-in default page cache is used instead of the application defined
  37178. ** page cache. */
  37179. sqlite3PCacheSetDefault();
  37180. }
  37181. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  37182. }
  37183. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  37184. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  37185. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  37186. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  37187. }
  37188. }
  37189. /*
  37190. ** Return the size in bytes of a PCache object.
  37191. */
  37192. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  37193. /*
  37194. ** Create a new PCache object. Storage space to hold the object
  37195. ** has already been allocated and is passed in as the p pointer.
  37196. ** The caller discovers how much space needs to be allocated by
  37197. ** calling sqlite3PcacheSize().
  37198. */
  37199. SQLITE_PRIVATE void sqlite3PcacheOpen(
  37200. int szPage, /* Size of every page */
  37201. int szExtra, /* Extra space associated with each page */
  37202. int bPurgeable, /* True if pages are on backing store */
  37203. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  37204. void *pStress, /* Argument to xStress */
  37205. PCache *p /* Preallocated space for the PCache */
  37206. ){
  37207. memset(p, 0, sizeof(PCache));
  37208. p->szPage = szPage;
  37209. p->szExtra = szExtra;
  37210. p->bPurgeable = bPurgeable;
  37211. p->xStress = xStress;
  37212. p->pStress = pStress;
  37213. p->szCache = 100;
  37214. }
  37215. /*
  37216. ** Change the page size for PCache object. The caller must ensure that there
  37217. ** are no outstanding page references when this function is called.
  37218. */
  37219. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  37220. assert( pCache->nRef==0 && pCache->pDirty==0 );
  37221. if( pCache->pCache ){
  37222. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37223. pCache->pCache = 0;
  37224. pCache->pPage1 = 0;
  37225. }
  37226. pCache->szPage = szPage;
  37227. }
  37228. /*
  37229. ** Compute the number of pages of cache requested.
  37230. */
  37231. static int numberOfCachePages(PCache *p){
  37232. if( p->szCache>=0 ){
  37233. return p->szCache;
  37234. }else{
  37235. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  37236. }
  37237. }
  37238. /*
  37239. ** Try to obtain a page from the cache.
  37240. */
  37241. SQLITE_PRIVATE int sqlite3PcacheFetch(
  37242. PCache *pCache, /* Obtain the page from this cache */
  37243. Pgno pgno, /* Page number to obtain */
  37244. int createFlag, /* If true, create page if it does not exist already */
  37245. PgHdr **ppPage /* Write the page here */
  37246. ){
  37247. sqlite3_pcache_page *pPage = 0;
  37248. PgHdr *pPgHdr = 0;
  37249. int eCreate;
  37250. assert( pCache!=0 );
  37251. assert( createFlag==1 || createFlag==0 );
  37252. assert( pgno>0 );
  37253. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  37254. ** allocate it now.
  37255. */
  37256. if( !pCache->pCache && createFlag ){
  37257. sqlite3_pcache *p;
  37258. p = sqlite3GlobalConfig.pcache2.xCreate(
  37259. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  37260. );
  37261. if( !p ){
  37262. return SQLITE_NOMEM;
  37263. }
  37264. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  37265. pCache->pCache = p;
  37266. }
  37267. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  37268. if( pCache->pCache ){
  37269. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  37270. }
  37271. if( !pPage && eCreate==1 ){
  37272. PgHdr *pPg;
  37273. /* Find a dirty page to write-out and recycle. First try to find a
  37274. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  37275. ** cleared), but if that is not possible settle for any other
  37276. ** unreferenced dirty page.
  37277. */
  37278. expensive_assert( pcacheCheckSynced(pCache) );
  37279. for(pPg=pCache->pSynced;
  37280. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  37281. pPg=pPg->pDirtyPrev
  37282. );
  37283. pCache->pSynced = pPg;
  37284. if( !pPg ){
  37285. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  37286. }
  37287. if( pPg ){
  37288. int rc;
  37289. #ifdef SQLITE_LOG_CACHE_SPILL
  37290. sqlite3_log(SQLITE_FULL,
  37291. "spill page %d making room for %d - cache used: %d/%d",
  37292. pPg->pgno, pgno,
  37293. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  37294. numberOfCachePages(pCache));
  37295. #endif
  37296. rc = pCache->xStress(pCache->pStress, pPg);
  37297. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  37298. return rc;
  37299. }
  37300. }
  37301. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  37302. }
  37303. if( pPage ){
  37304. pPgHdr = (PgHdr *)pPage->pExtra;
  37305. if( !pPgHdr->pPage ){
  37306. memset(pPgHdr, 0, sizeof(PgHdr));
  37307. pPgHdr->pPage = pPage;
  37308. pPgHdr->pData = pPage->pBuf;
  37309. pPgHdr->pExtra = (void *)&pPgHdr[1];
  37310. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  37311. pPgHdr->pCache = pCache;
  37312. pPgHdr->pgno = pgno;
  37313. }
  37314. assert( pPgHdr->pCache==pCache );
  37315. assert( pPgHdr->pgno==pgno );
  37316. assert( pPgHdr->pData==pPage->pBuf );
  37317. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  37318. if( 0==pPgHdr->nRef ){
  37319. pCache->nRef++;
  37320. }
  37321. pPgHdr->nRef++;
  37322. if( pgno==1 ){
  37323. pCache->pPage1 = pPgHdr;
  37324. }
  37325. }
  37326. *ppPage = pPgHdr;
  37327. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  37328. }
  37329. /*
  37330. ** Decrement the reference count on a page. If the page is clean and the
  37331. ** reference count drops to 0, then it is made elible for recycling.
  37332. */
  37333. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  37334. assert( p->nRef>0 );
  37335. p->nRef--;
  37336. if( p->nRef==0 ){
  37337. PCache *pCache = p->pCache;
  37338. pCache->nRef--;
  37339. if( (p->flags&PGHDR_DIRTY)==0 ){
  37340. pcacheUnpin(p);
  37341. }else{
  37342. /* Move the page to the head of the dirty list. */
  37343. pcacheRemoveFromDirtyList(p);
  37344. pcacheAddToDirtyList(p);
  37345. }
  37346. }
  37347. }
  37348. /*
  37349. ** Increase the reference count of a supplied page by 1.
  37350. */
  37351. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  37352. assert(p->nRef>0);
  37353. p->nRef++;
  37354. }
  37355. /*
  37356. ** Drop a page from the cache. There must be exactly one reference to the
  37357. ** page. This function deletes that reference, so after it returns the
  37358. ** page pointed to by p is invalid.
  37359. */
  37360. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  37361. PCache *pCache;
  37362. assert( p->nRef==1 );
  37363. if( p->flags&PGHDR_DIRTY ){
  37364. pcacheRemoveFromDirtyList(p);
  37365. }
  37366. pCache = p->pCache;
  37367. pCache->nRef--;
  37368. if( p->pgno==1 ){
  37369. pCache->pPage1 = 0;
  37370. }
  37371. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  37372. }
  37373. /*
  37374. ** Make sure the page is marked as dirty. If it isn't dirty already,
  37375. ** make it so.
  37376. */
  37377. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  37378. p->flags &= ~PGHDR_DONT_WRITE;
  37379. assert( p->nRef>0 );
  37380. if( 0==(p->flags & PGHDR_DIRTY) ){
  37381. p->flags |= PGHDR_DIRTY;
  37382. pcacheAddToDirtyList( p);
  37383. }
  37384. }
  37385. /*
  37386. ** Make sure the page is marked as clean. If it isn't clean already,
  37387. ** make it so.
  37388. */
  37389. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  37390. if( (p->flags & PGHDR_DIRTY) ){
  37391. pcacheRemoveFromDirtyList(p);
  37392. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  37393. if( p->nRef==0 ){
  37394. pcacheUnpin(p);
  37395. }
  37396. }
  37397. }
  37398. /*
  37399. ** Make every page in the cache clean.
  37400. */
  37401. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  37402. PgHdr *p;
  37403. while( (p = pCache->pDirty)!=0 ){
  37404. sqlite3PcacheMakeClean(p);
  37405. }
  37406. }
  37407. /*
  37408. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  37409. */
  37410. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  37411. PgHdr *p;
  37412. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37413. p->flags &= ~PGHDR_NEED_SYNC;
  37414. }
  37415. pCache->pSynced = pCache->pDirtyTail;
  37416. }
  37417. /*
  37418. ** Change the page number of page p to newPgno.
  37419. */
  37420. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  37421. PCache *pCache = p->pCache;
  37422. assert( p->nRef>0 );
  37423. assert( newPgno>0 );
  37424. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  37425. p->pgno = newPgno;
  37426. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  37427. pcacheRemoveFromDirtyList(p);
  37428. pcacheAddToDirtyList(p);
  37429. }
  37430. }
  37431. /*
  37432. ** Drop every cache entry whose page number is greater than "pgno". The
  37433. ** caller must ensure that there are no outstanding references to any pages
  37434. ** other than page 1 with a page number greater than pgno.
  37435. **
  37436. ** If there is a reference to page 1 and the pgno parameter passed to this
  37437. ** function is 0, then the data area associated with page 1 is zeroed, but
  37438. ** the page object is not dropped.
  37439. */
  37440. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  37441. if( pCache->pCache ){
  37442. PgHdr *p;
  37443. PgHdr *pNext;
  37444. for(p=pCache->pDirty; p; p=pNext){
  37445. pNext = p->pDirtyNext;
  37446. /* This routine never gets call with a positive pgno except right
  37447. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  37448. ** it must be that pgno==0.
  37449. */
  37450. assert( p->pgno>0 );
  37451. if( ALWAYS(p->pgno>pgno) ){
  37452. assert( p->flags&PGHDR_DIRTY );
  37453. sqlite3PcacheMakeClean(p);
  37454. }
  37455. }
  37456. if( pgno==0 && pCache->pPage1 ){
  37457. memset(pCache->pPage1->pData, 0, pCache->szPage);
  37458. pgno = 1;
  37459. }
  37460. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  37461. }
  37462. }
  37463. /*
  37464. ** Close a cache.
  37465. */
  37466. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  37467. if( pCache->pCache ){
  37468. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37469. }
  37470. }
  37471. /*
  37472. ** Discard the contents of the cache.
  37473. */
  37474. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  37475. sqlite3PcacheTruncate(pCache, 0);
  37476. }
  37477. /*
  37478. ** Merge two lists of pages connected by pDirty and in pgno order.
  37479. ** Do not both fixing the pDirtyPrev pointers.
  37480. */
  37481. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  37482. PgHdr result, *pTail;
  37483. pTail = &result;
  37484. while( pA && pB ){
  37485. if( pA->pgno<pB->pgno ){
  37486. pTail->pDirty = pA;
  37487. pTail = pA;
  37488. pA = pA->pDirty;
  37489. }else{
  37490. pTail->pDirty = pB;
  37491. pTail = pB;
  37492. pB = pB->pDirty;
  37493. }
  37494. }
  37495. if( pA ){
  37496. pTail->pDirty = pA;
  37497. }else if( pB ){
  37498. pTail->pDirty = pB;
  37499. }else{
  37500. pTail->pDirty = 0;
  37501. }
  37502. return result.pDirty;
  37503. }
  37504. /*
  37505. ** Sort the list of pages in accending order by pgno. Pages are
  37506. ** connected by pDirty pointers. The pDirtyPrev pointers are
  37507. ** corrupted by this sort.
  37508. **
  37509. ** Since there cannot be more than 2^31 distinct pages in a database,
  37510. ** there cannot be more than 31 buckets required by the merge sorter.
  37511. ** One extra bucket is added to catch overflow in case something
  37512. ** ever changes to make the previous sentence incorrect.
  37513. */
  37514. #define N_SORT_BUCKET 32
  37515. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  37516. PgHdr *a[N_SORT_BUCKET], *p;
  37517. int i;
  37518. memset(a, 0, sizeof(a));
  37519. while( pIn ){
  37520. p = pIn;
  37521. pIn = p->pDirty;
  37522. p->pDirty = 0;
  37523. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  37524. if( a[i]==0 ){
  37525. a[i] = p;
  37526. break;
  37527. }else{
  37528. p = pcacheMergeDirtyList(a[i], p);
  37529. a[i] = 0;
  37530. }
  37531. }
  37532. if( NEVER(i==N_SORT_BUCKET-1) ){
  37533. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  37534. ** the input list. But that is impossible.
  37535. */
  37536. a[i] = pcacheMergeDirtyList(a[i], p);
  37537. }
  37538. }
  37539. p = a[0];
  37540. for(i=1; i<N_SORT_BUCKET; i++){
  37541. p = pcacheMergeDirtyList(p, a[i]);
  37542. }
  37543. return p;
  37544. }
  37545. /*
  37546. ** Return a list of all dirty pages in the cache, sorted by page number.
  37547. */
  37548. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  37549. PgHdr *p;
  37550. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37551. p->pDirty = p->pDirtyNext;
  37552. }
  37553. return pcacheSortDirtyList(pCache->pDirty);
  37554. }
  37555. /*
  37556. ** Return the total number of referenced pages held by the cache.
  37557. */
  37558. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  37559. return pCache->nRef;
  37560. }
  37561. /*
  37562. ** Return the number of references to the page supplied as an argument.
  37563. */
  37564. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  37565. return p->nRef;
  37566. }
  37567. /*
  37568. ** Return the total number of pages in the cache.
  37569. */
  37570. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  37571. int nPage = 0;
  37572. if( pCache->pCache ){
  37573. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  37574. }
  37575. return nPage;
  37576. }
  37577. #ifdef SQLITE_TEST
  37578. /*
  37579. ** Get the suggested cache-size value.
  37580. */
  37581. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  37582. return numberOfCachePages(pCache);
  37583. }
  37584. #endif
  37585. /*
  37586. ** Set the suggested cache-size value.
  37587. */
  37588. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  37589. pCache->szCache = mxPage;
  37590. if( pCache->pCache ){
  37591. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  37592. numberOfCachePages(pCache));
  37593. }
  37594. }
  37595. /*
  37596. ** Free up as much memory as possible from the page cache.
  37597. */
  37598. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  37599. if( pCache->pCache ){
  37600. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  37601. }
  37602. }
  37603. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  37604. /*
  37605. ** For all dirty pages currently in the cache, invoke the specified
  37606. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  37607. ** defined.
  37608. */
  37609. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  37610. PgHdr *pDirty;
  37611. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  37612. xIter(pDirty);
  37613. }
  37614. }
  37615. #endif
  37616. /************** End of pcache.c **********************************************/
  37617. /************** Begin file pcache1.c *****************************************/
  37618. /*
  37619. ** 2008 November 05
  37620. **
  37621. ** The author disclaims copyright to this source code. In place of
  37622. ** a legal notice, here is a blessing:
  37623. **
  37624. ** May you do good and not evil.
  37625. ** May you find forgiveness for yourself and forgive others.
  37626. ** May you share freely, never taking more than you give.
  37627. **
  37628. *************************************************************************
  37629. **
  37630. ** This file implements the default page cache implementation (the
  37631. ** sqlite3_pcache interface). It also contains part of the implementation
  37632. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  37633. ** If the default page cache implementation is overriden, then neither of
  37634. ** these two features are available.
  37635. */
  37636. typedef struct PCache1 PCache1;
  37637. typedef struct PgHdr1 PgHdr1;
  37638. typedef struct PgFreeslot PgFreeslot;
  37639. typedef struct PGroup PGroup;
  37640. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  37641. ** of one or more PCaches that are able to recycle each others unpinned
  37642. ** pages when they are under memory pressure. A PGroup is an instance of
  37643. ** the following object.
  37644. **
  37645. ** This page cache implementation works in one of two modes:
  37646. **
  37647. ** (1) Every PCache is the sole member of its own PGroup. There is
  37648. ** one PGroup per PCache.
  37649. **
  37650. ** (2) There is a single global PGroup that all PCaches are a member
  37651. ** of.
  37652. **
  37653. ** Mode 1 uses more memory (since PCache instances are not able to rob
  37654. ** unused pages from other PCaches) but it also operates without a mutex,
  37655. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  37656. ** threadsafe, but recycles pages more efficiently.
  37657. **
  37658. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  37659. ** PGroup which is the pcache1.grp global variable and its mutex is
  37660. ** SQLITE_MUTEX_STATIC_LRU.
  37661. */
  37662. struct PGroup {
  37663. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  37664. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  37665. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  37666. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  37667. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  37668. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  37669. };
  37670. /* Each page cache is an instance of the following object. Every
  37671. ** open database file (including each in-memory database and each
  37672. ** temporary or transient database) has a single page cache which
  37673. ** is an instance of this object.
  37674. **
  37675. ** Pointers to structures of this type are cast and returned as
  37676. ** opaque sqlite3_pcache* handles.
  37677. */
  37678. struct PCache1 {
  37679. /* Cache configuration parameters. Page size (szPage) and the purgeable
  37680. ** flag (bPurgeable) are set when the cache is created. nMax may be
  37681. ** modified at any time by a call to the pcache1Cachesize() method.
  37682. ** The PGroup mutex must be held when accessing nMax.
  37683. */
  37684. PGroup *pGroup; /* PGroup this cache belongs to */
  37685. int szPage; /* Size of allocated pages in bytes */
  37686. int szExtra; /* Size of extra space in bytes */
  37687. int bPurgeable; /* True if cache is purgeable */
  37688. unsigned int nMin; /* Minimum number of pages reserved */
  37689. unsigned int nMax; /* Configured "cache_size" value */
  37690. unsigned int n90pct; /* nMax*9/10 */
  37691. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  37692. /* Hash table of all pages. The following variables may only be accessed
  37693. ** when the accessor is holding the PGroup mutex.
  37694. */
  37695. unsigned int nRecyclable; /* Number of pages in the LRU list */
  37696. unsigned int nPage; /* Total number of pages in apHash */
  37697. unsigned int nHash; /* Number of slots in apHash[] */
  37698. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  37699. };
  37700. /*
  37701. ** Each cache entry is represented by an instance of the following
  37702. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  37703. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  37704. ** in memory.
  37705. */
  37706. struct PgHdr1 {
  37707. sqlite3_pcache_page page;
  37708. unsigned int iKey; /* Key value (page number) */
  37709. PgHdr1 *pNext; /* Next in hash table chain */
  37710. PCache1 *pCache; /* Cache that currently owns this page */
  37711. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  37712. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  37713. };
  37714. /*
  37715. ** Free slots in the allocator used to divide up the buffer provided using
  37716. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  37717. */
  37718. struct PgFreeslot {
  37719. PgFreeslot *pNext; /* Next free slot */
  37720. };
  37721. /*
  37722. ** Global data used by this cache.
  37723. */
  37724. static SQLITE_WSD struct PCacheGlobal {
  37725. PGroup grp; /* The global PGroup for mode (2) */
  37726. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  37727. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  37728. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  37729. ** The nFreeSlot and pFree values do require mutex protection.
  37730. */
  37731. int isInit; /* True if initialized */
  37732. int szSlot; /* Size of each free slot */
  37733. int nSlot; /* The number of pcache slots */
  37734. int nReserve; /* Try to keep nFreeSlot above this */
  37735. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  37736. /* Above requires no mutex. Use mutex below for variable that follow. */
  37737. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  37738. PgFreeslot *pFree; /* Free page blocks */
  37739. int nFreeSlot; /* Number of unused pcache slots */
  37740. /* The following value requires a mutex to change. We skip the mutex on
  37741. ** reading because (1) most platforms read a 32-bit integer atomically and
  37742. ** (2) even if an incorrect value is read, no great harm is done since this
  37743. ** is really just an optimization. */
  37744. int bUnderPressure; /* True if low on PAGECACHE memory */
  37745. } pcache1_g;
  37746. /*
  37747. ** All code in this file should access the global structure above via the
  37748. ** alias "pcache1". This ensures that the WSD emulation is used when
  37749. ** compiling for systems that do not support real WSD.
  37750. */
  37751. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  37752. /*
  37753. ** Macros to enter and leave the PCache LRU mutex.
  37754. */
  37755. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  37756. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  37757. /******************************************************************************/
  37758. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  37759. /*
  37760. ** This function is called during initialization if a static buffer is
  37761. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  37762. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  37763. ** enough to contain 'n' buffers of 'sz' bytes each.
  37764. **
  37765. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  37766. ** to be serialized already. There is no need for further mutexing.
  37767. */
  37768. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  37769. if( pcache1.isInit ){
  37770. PgFreeslot *p;
  37771. sz = ROUNDDOWN8(sz);
  37772. pcache1.szSlot = sz;
  37773. pcache1.nSlot = pcache1.nFreeSlot = n;
  37774. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  37775. pcache1.pStart = pBuf;
  37776. pcache1.pFree = 0;
  37777. pcache1.bUnderPressure = 0;
  37778. while( n-- ){
  37779. p = (PgFreeslot*)pBuf;
  37780. p->pNext = pcache1.pFree;
  37781. pcache1.pFree = p;
  37782. pBuf = (void*)&((char*)pBuf)[sz];
  37783. }
  37784. pcache1.pEnd = pBuf;
  37785. }
  37786. }
  37787. /*
  37788. ** Malloc function used within this file to allocate space from the buffer
  37789. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  37790. ** such buffer exists or there is no space left in it, this function falls
  37791. ** back to sqlite3Malloc().
  37792. **
  37793. ** Multiple threads can run this routine at the same time. Global variables
  37794. ** in pcache1 need to be protected via mutex.
  37795. */
  37796. static void *pcache1Alloc(int nByte){
  37797. void *p = 0;
  37798. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  37799. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  37800. if( nByte<=pcache1.szSlot ){
  37801. sqlite3_mutex_enter(pcache1.mutex);
  37802. p = (PgHdr1 *)pcache1.pFree;
  37803. if( p ){
  37804. pcache1.pFree = pcache1.pFree->pNext;
  37805. pcache1.nFreeSlot--;
  37806. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37807. assert( pcache1.nFreeSlot>=0 );
  37808. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  37809. }
  37810. sqlite3_mutex_leave(pcache1.mutex);
  37811. }
  37812. if( p==0 ){
  37813. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  37814. ** it from sqlite3Malloc instead.
  37815. */
  37816. p = sqlite3Malloc(nByte);
  37817. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37818. if( p ){
  37819. int sz = sqlite3MallocSize(p);
  37820. sqlite3_mutex_enter(pcache1.mutex);
  37821. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  37822. sqlite3_mutex_leave(pcache1.mutex);
  37823. }
  37824. #endif
  37825. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37826. }
  37827. return p;
  37828. }
  37829. /*
  37830. ** Free an allocated buffer obtained from pcache1Alloc().
  37831. */
  37832. static int pcache1Free(void *p){
  37833. int nFreed = 0;
  37834. if( p==0 ) return 0;
  37835. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37836. PgFreeslot *pSlot;
  37837. sqlite3_mutex_enter(pcache1.mutex);
  37838. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  37839. pSlot = (PgFreeslot*)p;
  37840. pSlot->pNext = pcache1.pFree;
  37841. pcache1.pFree = pSlot;
  37842. pcache1.nFreeSlot++;
  37843. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37844. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  37845. sqlite3_mutex_leave(pcache1.mutex);
  37846. }else{
  37847. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37848. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37849. nFreed = sqlite3MallocSize(p);
  37850. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37851. sqlite3_mutex_enter(pcache1.mutex);
  37852. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  37853. sqlite3_mutex_leave(pcache1.mutex);
  37854. #endif
  37855. sqlite3_free(p);
  37856. }
  37857. return nFreed;
  37858. }
  37859. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  37860. /*
  37861. ** Return the size of a pcache allocation
  37862. */
  37863. static int pcache1MemSize(void *p){
  37864. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37865. return pcache1.szSlot;
  37866. }else{
  37867. int iSize;
  37868. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37869. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37870. iSize = sqlite3MallocSize(p);
  37871. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37872. return iSize;
  37873. }
  37874. }
  37875. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  37876. /*
  37877. ** Allocate a new page object initially associated with cache pCache.
  37878. */
  37879. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  37880. PgHdr1 *p = 0;
  37881. void *pPg;
  37882. /* The group mutex must be released before pcache1Alloc() is called. This
  37883. ** is because it may call sqlite3_release_memory(), which assumes that
  37884. ** this mutex is not held. */
  37885. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37886. pcache1LeaveMutex(pCache->pGroup);
  37887. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37888. pPg = pcache1Alloc(pCache->szPage);
  37889. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  37890. if( !pPg || !p ){
  37891. pcache1Free(pPg);
  37892. sqlite3_free(p);
  37893. pPg = 0;
  37894. }
  37895. #else
  37896. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  37897. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  37898. #endif
  37899. pcache1EnterMutex(pCache->pGroup);
  37900. if( pPg ){
  37901. p->page.pBuf = pPg;
  37902. p->page.pExtra = &p[1];
  37903. if( pCache->bPurgeable ){
  37904. pCache->pGroup->nCurrentPage++;
  37905. }
  37906. return p;
  37907. }
  37908. return 0;
  37909. }
  37910. /*
  37911. ** Free a page object allocated by pcache1AllocPage().
  37912. **
  37913. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  37914. ** that the current implementation happens to never call this routine
  37915. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  37916. */
  37917. static void pcache1FreePage(PgHdr1 *p){
  37918. if( ALWAYS(p) ){
  37919. PCache1 *pCache = p->pCache;
  37920. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  37921. pcache1Free(p->page.pBuf);
  37922. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37923. sqlite3_free(p);
  37924. #endif
  37925. if( pCache->bPurgeable ){
  37926. pCache->pGroup->nCurrentPage--;
  37927. }
  37928. }
  37929. }
  37930. /*
  37931. ** Malloc function used by SQLite to obtain space from the buffer configured
  37932. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  37933. ** exists, this function falls back to sqlite3Malloc().
  37934. */
  37935. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  37936. return pcache1Alloc(sz);
  37937. }
  37938. /*
  37939. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  37940. */
  37941. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  37942. pcache1Free(p);
  37943. }
  37944. /*
  37945. ** Return true if it desirable to avoid allocating a new page cache
  37946. ** entry.
  37947. **
  37948. ** If memory was allocated specifically to the page cache using
  37949. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  37950. ** it is desirable to avoid allocating a new page cache entry because
  37951. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  37952. ** for all page cache needs and we should not need to spill the
  37953. ** allocation onto the heap.
  37954. **
  37955. ** Or, the heap is used for all page cache memory but the heap is
  37956. ** under memory pressure, then again it is desirable to avoid
  37957. ** allocating a new page cache entry in order to avoid stressing
  37958. ** the heap even further.
  37959. */
  37960. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  37961. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  37962. return pcache1.bUnderPressure;
  37963. }else{
  37964. return sqlite3HeapNearlyFull();
  37965. }
  37966. }
  37967. /******************************************************************************/
  37968. /******** General Implementation Functions ************************************/
  37969. /*
  37970. ** This function is used to resize the hash table used by the cache passed
  37971. ** as the first argument.
  37972. **
  37973. ** The PCache mutex must be held when this function is called.
  37974. */
  37975. static int pcache1ResizeHash(PCache1 *p){
  37976. PgHdr1 **apNew;
  37977. unsigned int nNew;
  37978. unsigned int i;
  37979. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  37980. nNew = p->nHash*2;
  37981. if( nNew<256 ){
  37982. nNew = 256;
  37983. }
  37984. pcache1LeaveMutex(p->pGroup);
  37985. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  37986. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  37987. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  37988. pcache1EnterMutex(p->pGroup);
  37989. if( apNew ){
  37990. for(i=0; i<p->nHash; i++){
  37991. PgHdr1 *pPage;
  37992. PgHdr1 *pNext = p->apHash[i];
  37993. while( (pPage = pNext)!=0 ){
  37994. unsigned int h = pPage->iKey % nNew;
  37995. pNext = pPage->pNext;
  37996. pPage->pNext = apNew[h];
  37997. apNew[h] = pPage;
  37998. }
  37999. }
  38000. sqlite3_free(p->apHash);
  38001. p->apHash = apNew;
  38002. p->nHash = nNew;
  38003. }
  38004. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  38005. }
  38006. /*
  38007. ** This function is used internally to remove the page pPage from the
  38008. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  38009. ** LRU list, then this function is a no-op.
  38010. **
  38011. ** The PGroup mutex must be held when this function is called.
  38012. **
  38013. ** If pPage is NULL then this routine is a no-op.
  38014. */
  38015. static void pcache1PinPage(PgHdr1 *pPage){
  38016. PCache1 *pCache;
  38017. PGroup *pGroup;
  38018. if( pPage==0 ) return;
  38019. pCache = pPage->pCache;
  38020. pGroup = pCache->pGroup;
  38021. assert( sqlite3_mutex_held(pGroup->mutex) );
  38022. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  38023. if( pPage->pLruPrev ){
  38024. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  38025. }
  38026. if( pPage->pLruNext ){
  38027. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  38028. }
  38029. if( pGroup->pLruHead==pPage ){
  38030. pGroup->pLruHead = pPage->pLruNext;
  38031. }
  38032. if( pGroup->pLruTail==pPage ){
  38033. pGroup->pLruTail = pPage->pLruPrev;
  38034. }
  38035. pPage->pLruNext = 0;
  38036. pPage->pLruPrev = 0;
  38037. pPage->pCache->nRecyclable--;
  38038. }
  38039. }
  38040. /*
  38041. ** Remove the page supplied as an argument from the hash table
  38042. ** (PCache1.apHash structure) that it is currently stored in.
  38043. **
  38044. ** The PGroup mutex must be held when this function is called.
  38045. */
  38046. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  38047. unsigned int h;
  38048. PCache1 *pCache = pPage->pCache;
  38049. PgHdr1 **pp;
  38050. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38051. h = pPage->iKey % pCache->nHash;
  38052. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  38053. *pp = (*pp)->pNext;
  38054. pCache->nPage--;
  38055. }
  38056. /*
  38057. ** If there are currently more than nMaxPage pages allocated, try
  38058. ** to recycle pages to reduce the number allocated to nMaxPage.
  38059. */
  38060. static void pcache1EnforceMaxPage(PGroup *pGroup){
  38061. assert( sqlite3_mutex_held(pGroup->mutex) );
  38062. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  38063. PgHdr1 *p = pGroup->pLruTail;
  38064. assert( p->pCache->pGroup==pGroup );
  38065. pcache1PinPage(p);
  38066. pcache1RemoveFromHash(p);
  38067. pcache1FreePage(p);
  38068. }
  38069. }
  38070. /*
  38071. ** Discard all pages from cache pCache with a page number (key value)
  38072. ** greater than or equal to iLimit. Any pinned pages that meet this
  38073. ** criteria are unpinned before they are discarded.
  38074. **
  38075. ** The PCache mutex must be held when this function is called.
  38076. */
  38077. static void pcache1TruncateUnsafe(
  38078. PCache1 *pCache, /* The cache to truncate */
  38079. unsigned int iLimit /* Drop pages with this pgno or larger */
  38080. ){
  38081. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  38082. unsigned int h;
  38083. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38084. for(h=0; h<pCache->nHash; h++){
  38085. PgHdr1 **pp = &pCache->apHash[h];
  38086. PgHdr1 *pPage;
  38087. while( (pPage = *pp)!=0 ){
  38088. if( pPage->iKey>=iLimit ){
  38089. pCache->nPage--;
  38090. *pp = pPage->pNext;
  38091. pcache1PinPage(pPage);
  38092. pcache1FreePage(pPage);
  38093. }else{
  38094. pp = &pPage->pNext;
  38095. TESTONLY( nPage++; )
  38096. }
  38097. }
  38098. }
  38099. assert( pCache->nPage==nPage );
  38100. }
  38101. /******************************************************************************/
  38102. /******** sqlite3_pcache Methods **********************************************/
  38103. /*
  38104. ** Implementation of the sqlite3_pcache.xInit method.
  38105. */
  38106. static int pcache1Init(void *NotUsed){
  38107. UNUSED_PARAMETER(NotUsed);
  38108. assert( pcache1.isInit==0 );
  38109. memset(&pcache1, 0, sizeof(pcache1));
  38110. if( sqlite3GlobalConfig.bCoreMutex ){
  38111. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  38112. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  38113. }
  38114. pcache1.grp.mxPinned = 10;
  38115. pcache1.isInit = 1;
  38116. return SQLITE_OK;
  38117. }
  38118. /*
  38119. ** Implementation of the sqlite3_pcache.xShutdown method.
  38120. ** Note that the static mutex allocated in xInit does
  38121. ** not need to be freed.
  38122. */
  38123. static void pcache1Shutdown(void *NotUsed){
  38124. UNUSED_PARAMETER(NotUsed);
  38125. assert( pcache1.isInit!=0 );
  38126. memset(&pcache1, 0, sizeof(pcache1));
  38127. }
  38128. /*
  38129. ** Implementation of the sqlite3_pcache.xCreate method.
  38130. **
  38131. ** Allocate a new cache.
  38132. */
  38133. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  38134. PCache1 *pCache; /* The newly created page cache */
  38135. PGroup *pGroup; /* The group the new page cache will belong to */
  38136. int sz; /* Bytes of memory required to allocate the new cache */
  38137. /*
  38138. ** The separateCache variable is true if each PCache has its own private
  38139. ** PGroup. In other words, separateCache is true for mode (1) where no
  38140. ** mutexing is required.
  38141. **
  38142. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  38143. **
  38144. ** * Always use a unified cache in single-threaded applications
  38145. **
  38146. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  38147. ** use separate caches (mode-1)
  38148. */
  38149. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  38150. const int separateCache = 0;
  38151. #else
  38152. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  38153. #endif
  38154. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  38155. assert( szExtra < 300 );
  38156. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  38157. pCache = (PCache1 *)sqlite3MallocZero(sz);
  38158. if( pCache ){
  38159. if( separateCache ){
  38160. pGroup = (PGroup*)&pCache[1];
  38161. pGroup->mxPinned = 10;
  38162. }else{
  38163. pGroup = &pcache1.grp;
  38164. }
  38165. pCache->pGroup = pGroup;
  38166. pCache->szPage = szPage;
  38167. pCache->szExtra = szExtra;
  38168. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  38169. if( bPurgeable ){
  38170. pCache->nMin = 10;
  38171. pcache1EnterMutex(pGroup);
  38172. pGroup->nMinPage += pCache->nMin;
  38173. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38174. pcache1LeaveMutex(pGroup);
  38175. }
  38176. }
  38177. return (sqlite3_pcache *)pCache;
  38178. }
  38179. /*
  38180. ** Implementation of the sqlite3_pcache.xCachesize method.
  38181. **
  38182. ** Configure the cache_size limit for a cache.
  38183. */
  38184. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  38185. PCache1 *pCache = (PCache1 *)p;
  38186. if( pCache->bPurgeable ){
  38187. PGroup *pGroup = pCache->pGroup;
  38188. pcache1EnterMutex(pGroup);
  38189. pGroup->nMaxPage += (nMax - pCache->nMax);
  38190. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38191. pCache->nMax = nMax;
  38192. pCache->n90pct = pCache->nMax*9/10;
  38193. pcache1EnforceMaxPage(pGroup);
  38194. pcache1LeaveMutex(pGroup);
  38195. }
  38196. }
  38197. /*
  38198. ** Implementation of the sqlite3_pcache.xShrink method.
  38199. **
  38200. ** Free up as much memory as possible.
  38201. */
  38202. static void pcache1Shrink(sqlite3_pcache *p){
  38203. PCache1 *pCache = (PCache1*)p;
  38204. if( pCache->bPurgeable ){
  38205. PGroup *pGroup = pCache->pGroup;
  38206. int savedMaxPage;
  38207. pcache1EnterMutex(pGroup);
  38208. savedMaxPage = pGroup->nMaxPage;
  38209. pGroup->nMaxPage = 0;
  38210. pcache1EnforceMaxPage(pGroup);
  38211. pGroup->nMaxPage = savedMaxPage;
  38212. pcache1LeaveMutex(pGroup);
  38213. }
  38214. }
  38215. /*
  38216. ** Implementation of the sqlite3_pcache.xPagecount method.
  38217. */
  38218. static int pcache1Pagecount(sqlite3_pcache *p){
  38219. int n;
  38220. PCache1 *pCache = (PCache1*)p;
  38221. pcache1EnterMutex(pCache->pGroup);
  38222. n = pCache->nPage;
  38223. pcache1LeaveMutex(pCache->pGroup);
  38224. return n;
  38225. }
  38226. /*
  38227. ** Implementation of the sqlite3_pcache.xFetch method.
  38228. **
  38229. ** Fetch a page by key value.
  38230. **
  38231. ** Whether or not a new page may be allocated by this function depends on
  38232. ** the value of the createFlag argument. 0 means do not allocate a new
  38233. ** page. 1 means allocate a new page if space is easily available. 2
  38234. ** means to try really hard to allocate a new page.
  38235. **
  38236. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  38237. ** database) there is really no difference between createFlag 1 and 2. So
  38238. ** the calling function (pcache.c) will never have a createFlag of 1 on
  38239. ** a non-purgeable cache.
  38240. **
  38241. ** There are three different approaches to obtaining space for a page,
  38242. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  38243. **
  38244. ** 1. Regardless of the value of createFlag, the cache is searched for a
  38245. ** copy of the requested page. If one is found, it is returned.
  38246. **
  38247. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  38248. ** returned.
  38249. **
  38250. ** 3. If createFlag is 1, and the page is not already in the cache, then
  38251. ** return NULL (do not allocate a new page) if any of the following
  38252. ** conditions are true:
  38253. **
  38254. ** (a) the number of pages pinned by the cache is greater than
  38255. ** PCache1.nMax, or
  38256. **
  38257. ** (b) the number of pages pinned by the cache is greater than
  38258. ** the sum of nMax for all purgeable caches, less the sum of
  38259. ** nMin for all other purgeable caches, or
  38260. **
  38261. ** 4. If none of the first three conditions apply and the cache is marked
  38262. ** as purgeable, and if one of the following is true:
  38263. **
  38264. ** (a) The number of pages allocated for the cache is already
  38265. ** PCache1.nMax, or
  38266. **
  38267. ** (b) The number of pages allocated for all purgeable caches is
  38268. ** already equal to or greater than the sum of nMax for all
  38269. ** purgeable caches,
  38270. **
  38271. ** (c) The system is under memory pressure and wants to avoid
  38272. ** unnecessary pages cache entry allocations
  38273. **
  38274. ** then attempt to recycle a page from the LRU list. If it is the right
  38275. ** size, return the recycled buffer. Otherwise, free the buffer and
  38276. ** proceed to step 5.
  38277. **
  38278. ** 5. Otherwise, allocate and return a new page buffer.
  38279. */
  38280. static sqlite3_pcache_page *pcache1Fetch(
  38281. sqlite3_pcache *p,
  38282. unsigned int iKey,
  38283. int createFlag
  38284. ){
  38285. unsigned int nPinned;
  38286. PCache1 *pCache = (PCache1 *)p;
  38287. PGroup *pGroup;
  38288. PgHdr1 *pPage = 0;
  38289. assert( pCache->bPurgeable || createFlag!=1 );
  38290. assert( pCache->bPurgeable || pCache->nMin==0 );
  38291. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  38292. assert( pCache->nMin==0 || pCache->bPurgeable );
  38293. pcache1EnterMutex(pGroup = pCache->pGroup);
  38294. /* Step 1: Search the hash table for an existing entry. */
  38295. if( pCache->nHash>0 ){
  38296. unsigned int h = iKey % pCache->nHash;
  38297. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  38298. }
  38299. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  38300. if( pPage || createFlag==0 ){
  38301. pcache1PinPage(pPage);
  38302. goto fetch_out;
  38303. }
  38304. /* The pGroup local variable will normally be initialized by the
  38305. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  38306. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  38307. ** local variable here. Delaying the initialization of pGroup is an
  38308. ** optimization: The common case is to exit the module before reaching
  38309. ** this point.
  38310. */
  38311. #ifdef SQLITE_MUTEX_OMIT
  38312. pGroup = pCache->pGroup;
  38313. #endif
  38314. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  38315. assert( pCache->nPage >= pCache->nRecyclable );
  38316. nPinned = pCache->nPage - pCache->nRecyclable;
  38317. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  38318. assert( pCache->n90pct == pCache->nMax*9/10 );
  38319. if( createFlag==1 && (
  38320. nPinned>=pGroup->mxPinned
  38321. || nPinned>=pCache->n90pct
  38322. || pcache1UnderMemoryPressure(pCache)
  38323. )){
  38324. goto fetch_out;
  38325. }
  38326. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  38327. goto fetch_out;
  38328. }
  38329. assert( pCache->nHash>0 && pCache->apHash );
  38330. /* Step 4. Try to recycle a page. */
  38331. if( pCache->bPurgeable && pGroup->pLruTail && (
  38332. (pCache->nPage+1>=pCache->nMax)
  38333. || pGroup->nCurrentPage>=pGroup->nMaxPage
  38334. || pcache1UnderMemoryPressure(pCache)
  38335. )){
  38336. PCache1 *pOther;
  38337. pPage = pGroup->pLruTail;
  38338. pcache1RemoveFromHash(pPage);
  38339. pcache1PinPage(pPage);
  38340. pOther = pPage->pCache;
  38341. /* We want to verify that szPage and szExtra are the same for pOther
  38342. ** and pCache. Assert that we can verify this by comparing sums. */
  38343. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  38344. assert( pCache->szExtra<512 );
  38345. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  38346. assert( pOther->szExtra<512 );
  38347. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  38348. pcache1FreePage(pPage);
  38349. pPage = 0;
  38350. }else{
  38351. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  38352. }
  38353. }
  38354. /* Step 5. If a usable page buffer has still not been found,
  38355. ** attempt to allocate a new one.
  38356. */
  38357. if( !pPage ){
  38358. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  38359. pPage = pcache1AllocPage(pCache);
  38360. if( createFlag==1 ) sqlite3EndBenignMalloc();
  38361. }
  38362. if( pPage ){
  38363. unsigned int h = iKey % pCache->nHash;
  38364. pCache->nPage++;
  38365. pPage->iKey = iKey;
  38366. pPage->pNext = pCache->apHash[h];
  38367. pPage->pCache = pCache;
  38368. pPage->pLruPrev = 0;
  38369. pPage->pLruNext = 0;
  38370. *(void **)pPage->page.pExtra = 0;
  38371. pCache->apHash[h] = pPage;
  38372. }
  38373. fetch_out:
  38374. if( pPage && iKey>pCache->iMaxKey ){
  38375. pCache->iMaxKey = iKey;
  38376. }
  38377. pcache1LeaveMutex(pGroup);
  38378. return &pPage->page;
  38379. }
  38380. /*
  38381. ** Implementation of the sqlite3_pcache.xUnpin method.
  38382. **
  38383. ** Mark a page as unpinned (eligible for asynchronous recycling).
  38384. */
  38385. static void pcache1Unpin(
  38386. sqlite3_pcache *p,
  38387. sqlite3_pcache_page *pPg,
  38388. int reuseUnlikely
  38389. ){
  38390. PCache1 *pCache = (PCache1 *)p;
  38391. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38392. PGroup *pGroup = pCache->pGroup;
  38393. assert( pPage->pCache==pCache );
  38394. pcache1EnterMutex(pGroup);
  38395. /* It is an error to call this function if the page is already
  38396. ** part of the PGroup LRU list.
  38397. */
  38398. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  38399. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  38400. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  38401. pcache1RemoveFromHash(pPage);
  38402. pcache1FreePage(pPage);
  38403. }else{
  38404. /* Add the page to the PGroup LRU list. */
  38405. if( pGroup->pLruHead ){
  38406. pGroup->pLruHead->pLruPrev = pPage;
  38407. pPage->pLruNext = pGroup->pLruHead;
  38408. pGroup->pLruHead = pPage;
  38409. }else{
  38410. pGroup->pLruTail = pPage;
  38411. pGroup->pLruHead = pPage;
  38412. }
  38413. pCache->nRecyclable++;
  38414. }
  38415. pcache1LeaveMutex(pCache->pGroup);
  38416. }
  38417. /*
  38418. ** Implementation of the sqlite3_pcache.xRekey method.
  38419. */
  38420. static void pcache1Rekey(
  38421. sqlite3_pcache *p,
  38422. sqlite3_pcache_page *pPg,
  38423. unsigned int iOld,
  38424. unsigned int iNew
  38425. ){
  38426. PCache1 *pCache = (PCache1 *)p;
  38427. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38428. PgHdr1 **pp;
  38429. unsigned int h;
  38430. assert( pPage->iKey==iOld );
  38431. assert( pPage->pCache==pCache );
  38432. pcache1EnterMutex(pCache->pGroup);
  38433. h = iOld%pCache->nHash;
  38434. pp = &pCache->apHash[h];
  38435. while( (*pp)!=pPage ){
  38436. pp = &(*pp)->pNext;
  38437. }
  38438. *pp = pPage->pNext;
  38439. h = iNew%pCache->nHash;
  38440. pPage->iKey = iNew;
  38441. pPage->pNext = pCache->apHash[h];
  38442. pCache->apHash[h] = pPage;
  38443. if( iNew>pCache->iMaxKey ){
  38444. pCache->iMaxKey = iNew;
  38445. }
  38446. pcache1LeaveMutex(pCache->pGroup);
  38447. }
  38448. /*
  38449. ** Implementation of the sqlite3_pcache.xTruncate method.
  38450. **
  38451. ** Discard all unpinned pages in the cache with a page number equal to
  38452. ** or greater than parameter iLimit. Any pinned pages with a page number
  38453. ** equal to or greater than iLimit are implicitly unpinned.
  38454. */
  38455. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  38456. PCache1 *pCache = (PCache1 *)p;
  38457. pcache1EnterMutex(pCache->pGroup);
  38458. if( iLimit<=pCache->iMaxKey ){
  38459. pcache1TruncateUnsafe(pCache, iLimit);
  38460. pCache->iMaxKey = iLimit-1;
  38461. }
  38462. pcache1LeaveMutex(pCache->pGroup);
  38463. }
  38464. /*
  38465. ** Implementation of the sqlite3_pcache.xDestroy method.
  38466. **
  38467. ** Destroy a cache allocated using pcache1Create().
  38468. */
  38469. static void pcache1Destroy(sqlite3_pcache *p){
  38470. PCache1 *pCache = (PCache1 *)p;
  38471. PGroup *pGroup = pCache->pGroup;
  38472. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  38473. pcache1EnterMutex(pGroup);
  38474. pcache1TruncateUnsafe(pCache, 0);
  38475. assert( pGroup->nMaxPage >= pCache->nMax );
  38476. pGroup->nMaxPage -= pCache->nMax;
  38477. assert( pGroup->nMinPage >= pCache->nMin );
  38478. pGroup->nMinPage -= pCache->nMin;
  38479. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38480. pcache1EnforceMaxPage(pGroup);
  38481. pcache1LeaveMutex(pGroup);
  38482. sqlite3_free(pCache->apHash);
  38483. sqlite3_free(pCache);
  38484. }
  38485. /*
  38486. ** This function is called during initialization (sqlite3_initialize()) to
  38487. ** install the default pluggable cache module, assuming the user has not
  38488. ** already provided an alternative.
  38489. */
  38490. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  38491. static const sqlite3_pcache_methods2 defaultMethods = {
  38492. 1, /* iVersion */
  38493. 0, /* pArg */
  38494. pcache1Init, /* xInit */
  38495. pcache1Shutdown, /* xShutdown */
  38496. pcache1Create, /* xCreate */
  38497. pcache1Cachesize, /* xCachesize */
  38498. pcache1Pagecount, /* xPagecount */
  38499. pcache1Fetch, /* xFetch */
  38500. pcache1Unpin, /* xUnpin */
  38501. pcache1Rekey, /* xRekey */
  38502. pcache1Truncate, /* xTruncate */
  38503. pcache1Destroy, /* xDestroy */
  38504. pcache1Shrink /* xShrink */
  38505. };
  38506. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  38507. }
  38508. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38509. /*
  38510. ** This function is called to free superfluous dynamically allocated memory
  38511. ** held by the pager system. Memory in use by any SQLite pager allocated
  38512. ** by the current thread may be sqlite3_free()ed.
  38513. **
  38514. ** nReq is the number of bytes of memory required. Once this much has
  38515. ** been released, the function returns. The return value is the total number
  38516. ** of bytes of memory released.
  38517. */
  38518. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  38519. int nFree = 0;
  38520. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38521. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  38522. if( pcache1.pStart==0 ){
  38523. PgHdr1 *p;
  38524. pcache1EnterMutex(&pcache1.grp);
  38525. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  38526. nFree += pcache1MemSize(p->page.pBuf);
  38527. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38528. nFree += sqlite3MemSize(p);
  38529. #endif
  38530. pcache1PinPage(p);
  38531. pcache1RemoveFromHash(p);
  38532. pcache1FreePage(p);
  38533. }
  38534. pcache1LeaveMutex(&pcache1.grp);
  38535. }
  38536. return nFree;
  38537. }
  38538. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38539. #ifdef SQLITE_TEST
  38540. /*
  38541. ** This function is used by test procedures to inspect the internal state
  38542. ** of the global cache.
  38543. */
  38544. SQLITE_PRIVATE void sqlite3PcacheStats(
  38545. int *pnCurrent, /* OUT: Total number of pages cached */
  38546. int *pnMax, /* OUT: Global maximum cache size */
  38547. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  38548. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  38549. ){
  38550. PgHdr1 *p;
  38551. int nRecyclable = 0;
  38552. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  38553. nRecyclable++;
  38554. }
  38555. *pnCurrent = pcache1.grp.nCurrentPage;
  38556. *pnMax = (int)pcache1.grp.nMaxPage;
  38557. *pnMin = (int)pcache1.grp.nMinPage;
  38558. *pnRecyclable = nRecyclable;
  38559. }
  38560. #endif
  38561. /************** End of pcache1.c *********************************************/
  38562. /************** Begin file rowset.c ******************************************/
  38563. /*
  38564. ** 2008 December 3
  38565. **
  38566. ** The author disclaims copyright to this source code. In place of
  38567. ** a legal notice, here is a blessing:
  38568. **
  38569. ** May you do good and not evil.
  38570. ** May you find forgiveness for yourself and forgive others.
  38571. ** May you share freely, never taking more than you give.
  38572. **
  38573. *************************************************************************
  38574. **
  38575. ** This module implements an object we call a "RowSet".
  38576. **
  38577. ** The RowSet object is a collection of rowids. Rowids
  38578. ** are inserted into the RowSet in an arbitrary order. Inserts
  38579. ** can be intermixed with tests to see if a given rowid has been
  38580. ** previously inserted into the RowSet.
  38581. **
  38582. ** After all inserts are finished, it is possible to extract the
  38583. ** elements of the RowSet in sorted order. Once this extraction
  38584. ** process has started, no new elements may be inserted.
  38585. **
  38586. ** Hence, the primitive operations for a RowSet are:
  38587. **
  38588. ** CREATE
  38589. ** INSERT
  38590. ** TEST
  38591. ** SMALLEST
  38592. ** DESTROY
  38593. **
  38594. ** The CREATE and DESTROY primitives are the constructor and destructor,
  38595. ** obviously. The INSERT primitive adds a new element to the RowSet.
  38596. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  38597. ** extracts the least value from the RowSet.
  38598. **
  38599. ** The INSERT primitive might allocate additional memory. Memory is
  38600. ** allocated in chunks so most INSERTs do no allocation. There is an
  38601. ** upper bound on the size of allocated memory. No memory is freed
  38602. ** until DESTROY.
  38603. **
  38604. ** The TEST primitive includes a "batch" number. The TEST primitive
  38605. ** will only see elements that were inserted before the last change
  38606. ** in the batch number. In other words, if an INSERT occurs between
  38607. ** two TESTs where the TESTs have the same batch nubmer, then the
  38608. ** value added by the INSERT will not be visible to the second TEST.
  38609. ** The initial batch number is zero, so if the very first TEST contains
  38610. ** a non-zero batch number, it will see all prior INSERTs.
  38611. **
  38612. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  38613. ** that is attempted.
  38614. **
  38615. ** The cost of an INSERT is roughly constant. (Sometime new memory
  38616. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  38617. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  38618. ** The cost of a TEST using the same batch number is O(logN). The cost
  38619. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  38620. ** primitives are constant time. The cost of DESTROY is O(N).
  38621. **
  38622. ** There is an added cost of O(N) when switching between TEST and
  38623. ** SMALLEST primitives.
  38624. */
  38625. /*
  38626. ** Target size for allocation chunks.
  38627. */
  38628. #define ROWSET_ALLOCATION_SIZE 1024
  38629. /*
  38630. ** The number of rowset entries per allocation chunk.
  38631. */
  38632. #define ROWSET_ENTRY_PER_CHUNK \
  38633. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  38634. /*
  38635. ** Each entry in a RowSet is an instance of the following object.
  38636. **
  38637. ** This same object is reused to store a linked list of trees of RowSetEntry
  38638. ** objects. In that alternative use, pRight points to the next entry
  38639. ** in the list, pLeft points to the tree, and v is unused. The
  38640. ** RowSet.pForest value points to the head of this forest list.
  38641. */
  38642. struct RowSetEntry {
  38643. i64 v; /* ROWID value for this entry */
  38644. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  38645. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  38646. };
  38647. /*
  38648. ** RowSetEntry objects are allocated in large chunks (instances of the
  38649. ** following structure) to reduce memory allocation overhead. The
  38650. ** chunks are kept on a linked list so that they can be deallocated
  38651. ** when the RowSet is destroyed.
  38652. */
  38653. struct RowSetChunk {
  38654. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  38655. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  38656. };
  38657. /*
  38658. ** A RowSet in an instance of the following structure.
  38659. **
  38660. ** A typedef of this structure if found in sqliteInt.h.
  38661. */
  38662. struct RowSet {
  38663. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  38664. sqlite3 *db; /* The database connection */
  38665. struct RowSetEntry *pEntry; /* List of entries using pRight */
  38666. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  38667. struct RowSetEntry *pFresh; /* Source of new entry objects */
  38668. struct RowSetEntry *pForest; /* List of binary trees of entries */
  38669. u16 nFresh; /* Number of objects on pFresh */
  38670. u8 rsFlags; /* Various flags */
  38671. u8 iBatch; /* Current insert batch */
  38672. };
  38673. /*
  38674. ** Allowed values for RowSet.rsFlags
  38675. */
  38676. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  38677. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  38678. /*
  38679. ** Turn bulk memory into a RowSet object. N bytes of memory
  38680. ** are available at pSpace. The db pointer is used as a memory context
  38681. ** for any subsequent allocations that need to occur.
  38682. ** Return a pointer to the new RowSet object.
  38683. **
  38684. ** It must be the case that N is sufficient to make a Rowset. If not
  38685. ** an assertion fault occurs.
  38686. **
  38687. ** If N is larger than the minimum, use the surplus as an initial
  38688. ** allocation of entries available to be filled.
  38689. */
  38690. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  38691. RowSet *p;
  38692. assert( N >= ROUND8(sizeof(*p)) );
  38693. p = pSpace;
  38694. p->pChunk = 0;
  38695. p->db = db;
  38696. p->pEntry = 0;
  38697. p->pLast = 0;
  38698. p->pForest = 0;
  38699. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  38700. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  38701. p->rsFlags = ROWSET_SORTED;
  38702. p->iBatch = 0;
  38703. return p;
  38704. }
  38705. /*
  38706. ** Deallocate all chunks from a RowSet. This frees all memory that
  38707. ** the RowSet has allocated over its lifetime. This routine is
  38708. ** the destructor for the RowSet.
  38709. */
  38710. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  38711. struct RowSetChunk *pChunk, *pNextChunk;
  38712. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  38713. pNextChunk = pChunk->pNextChunk;
  38714. sqlite3DbFree(p->db, pChunk);
  38715. }
  38716. p->pChunk = 0;
  38717. p->nFresh = 0;
  38718. p->pEntry = 0;
  38719. p->pLast = 0;
  38720. p->pForest = 0;
  38721. p->rsFlags = ROWSET_SORTED;
  38722. }
  38723. /*
  38724. ** Allocate a new RowSetEntry object that is associated with the
  38725. ** given RowSet. Return a pointer to the new and completely uninitialized
  38726. ** objected.
  38727. **
  38728. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  38729. ** routine returns NULL.
  38730. */
  38731. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  38732. assert( p!=0 );
  38733. if( p->nFresh==0 ){
  38734. struct RowSetChunk *pNew;
  38735. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  38736. if( pNew==0 ){
  38737. return 0;
  38738. }
  38739. pNew->pNextChunk = p->pChunk;
  38740. p->pChunk = pNew;
  38741. p->pFresh = pNew->aEntry;
  38742. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  38743. }
  38744. p->nFresh--;
  38745. return p->pFresh++;
  38746. }
  38747. /*
  38748. ** Insert a new value into a RowSet.
  38749. **
  38750. ** The mallocFailed flag of the database connection is set if a
  38751. ** memory allocation fails.
  38752. */
  38753. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  38754. struct RowSetEntry *pEntry; /* The new entry */
  38755. struct RowSetEntry *pLast; /* The last prior entry */
  38756. /* This routine is never called after sqlite3RowSetNext() */
  38757. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38758. pEntry = rowSetEntryAlloc(p);
  38759. if( pEntry==0 ) return;
  38760. pEntry->v = rowid;
  38761. pEntry->pRight = 0;
  38762. pLast = p->pLast;
  38763. if( pLast ){
  38764. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  38765. p->rsFlags &= ~ROWSET_SORTED;
  38766. }
  38767. pLast->pRight = pEntry;
  38768. }else{
  38769. p->pEntry = pEntry;
  38770. }
  38771. p->pLast = pEntry;
  38772. }
  38773. /*
  38774. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  38775. **
  38776. ** The input lists are connected via pRight pointers and are
  38777. ** assumed to each already be in sorted order.
  38778. */
  38779. static struct RowSetEntry *rowSetEntryMerge(
  38780. struct RowSetEntry *pA, /* First sorted list to be merged */
  38781. struct RowSetEntry *pB /* Second sorted list to be merged */
  38782. ){
  38783. struct RowSetEntry head;
  38784. struct RowSetEntry *pTail;
  38785. pTail = &head;
  38786. while( pA && pB ){
  38787. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38788. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  38789. if( pA->v<pB->v ){
  38790. pTail->pRight = pA;
  38791. pA = pA->pRight;
  38792. pTail = pTail->pRight;
  38793. }else if( pB->v<pA->v ){
  38794. pTail->pRight = pB;
  38795. pB = pB->pRight;
  38796. pTail = pTail->pRight;
  38797. }else{
  38798. pA = pA->pRight;
  38799. }
  38800. }
  38801. if( pA ){
  38802. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38803. pTail->pRight = pA;
  38804. }else{
  38805. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  38806. pTail->pRight = pB;
  38807. }
  38808. return head.pRight;
  38809. }
  38810. /*
  38811. ** Sort all elements on the list of RowSetEntry objects into order of
  38812. ** increasing v.
  38813. */
  38814. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  38815. unsigned int i;
  38816. struct RowSetEntry *pNext, *aBucket[40];
  38817. memset(aBucket, 0, sizeof(aBucket));
  38818. while( pIn ){
  38819. pNext = pIn->pRight;
  38820. pIn->pRight = 0;
  38821. for(i=0; aBucket[i]; i++){
  38822. pIn = rowSetEntryMerge(aBucket[i], pIn);
  38823. aBucket[i] = 0;
  38824. }
  38825. aBucket[i] = pIn;
  38826. pIn = pNext;
  38827. }
  38828. pIn = 0;
  38829. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  38830. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  38831. }
  38832. return pIn;
  38833. }
  38834. /*
  38835. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  38836. ** Convert this tree into a linked list connected by the pRight pointers
  38837. ** and return pointers to the first and last elements of the new list.
  38838. */
  38839. static void rowSetTreeToList(
  38840. struct RowSetEntry *pIn, /* Root of the input tree */
  38841. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  38842. struct RowSetEntry **ppLast /* Write tail of the output list here */
  38843. ){
  38844. assert( pIn!=0 );
  38845. if( pIn->pLeft ){
  38846. struct RowSetEntry *p;
  38847. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  38848. p->pRight = pIn;
  38849. }else{
  38850. *ppFirst = pIn;
  38851. }
  38852. if( pIn->pRight ){
  38853. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  38854. }else{
  38855. *ppLast = pIn;
  38856. }
  38857. assert( (*ppLast)->pRight==0 );
  38858. }
  38859. /*
  38860. ** Convert a sorted list of elements (connected by pRight) into a binary
  38861. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  38862. ** node taken from the head of *ppList. A depth of 2 means a tree with
  38863. ** three nodes. And so forth.
  38864. **
  38865. ** Use as many entries from the input list as required and update the
  38866. ** *ppList to point to the unused elements of the list. If the input
  38867. ** list contains too few elements, then construct an incomplete tree
  38868. ** and leave *ppList set to NULL.
  38869. **
  38870. ** Return a pointer to the root of the constructed binary tree.
  38871. */
  38872. static struct RowSetEntry *rowSetNDeepTree(
  38873. struct RowSetEntry **ppList,
  38874. int iDepth
  38875. ){
  38876. struct RowSetEntry *p; /* Root of the new tree */
  38877. struct RowSetEntry *pLeft; /* Left subtree */
  38878. if( *ppList==0 ){
  38879. return 0;
  38880. }
  38881. if( iDepth==1 ){
  38882. p = *ppList;
  38883. *ppList = p->pRight;
  38884. p->pLeft = p->pRight = 0;
  38885. return p;
  38886. }
  38887. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  38888. p = *ppList;
  38889. if( p==0 ){
  38890. return pLeft;
  38891. }
  38892. p->pLeft = pLeft;
  38893. *ppList = p->pRight;
  38894. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  38895. return p;
  38896. }
  38897. /*
  38898. ** Convert a sorted list of elements into a binary tree. Make the tree
  38899. ** as deep as it needs to be in order to contain the entire list.
  38900. */
  38901. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  38902. int iDepth; /* Depth of the tree so far */
  38903. struct RowSetEntry *p; /* Current tree root */
  38904. struct RowSetEntry *pLeft; /* Left subtree */
  38905. assert( pList!=0 );
  38906. p = pList;
  38907. pList = p->pRight;
  38908. p->pLeft = p->pRight = 0;
  38909. for(iDepth=1; pList; iDepth++){
  38910. pLeft = p;
  38911. p = pList;
  38912. pList = p->pRight;
  38913. p->pLeft = pLeft;
  38914. p->pRight = rowSetNDeepTree(&pList, iDepth);
  38915. }
  38916. return p;
  38917. }
  38918. /*
  38919. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  38920. ** sort them all together into one big ordered list on p->pEntry.
  38921. **
  38922. ** This routine should only be called once in the life of a RowSet.
  38923. */
  38924. static void rowSetToList(RowSet *p){
  38925. /* This routine is called only once */
  38926. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38927. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  38928. p->pEntry = rowSetEntrySort(p->pEntry);
  38929. }
  38930. /* While this module could theoretically support it, sqlite3RowSetNext()
  38931. ** is never called after sqlite3RowSetText() for the same RowSet. So
  38932. ** there is never a forest to deal with. Should this change, simply
  38933. ** remove the assert() and the #if 0. */
  38934. assert( p->pForest==0 );
  38935. #if 0
  38936. while( p->pForest ){
  38937. struct RowSetEntry *pTree = p->pForest->pLeft;
  38938. if( pTree ){
  38939. struct RowSetEntry *pHead, *pTail;
  38940. rowSetTreeToList(pTree, &pHead, &pTail);
  38941. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  38942. }
  38943. p->pForest = p->pForest->pRight;
  38944. }
  38945. #endif
  38946. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  38947. }
  38948. /*
  38949. ** Extract the smallest element from the RowSet.
  38950. ** Write the element into *pRowid. Return 1 on success. Return
  38951. ** 0 if the RowSet is already empty.
  38952. **
  38953. ** After this routine has been called, the sqlite3RowSetInsert()
  38954. ** routine may not be called again.
  38955. */
  38956. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  38957. assert( p!=0 );
  38958. /* Merge the forest into a single sorted list on first call */
  38959. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  38960. /* Return the next entry on the list */
  38961. if( p->pEntry ){
  38962. *pRowid = p->pEntry->v;
  38963. p->pEntry = p->pEntry->pRight;
  38964. if( p->pEntry==0 ){
  38965. sqlite3RowSetClear(p);
  38966. }
  38967. return 1;
  38968. }else{
  38969. return 0;
  38970. }
  38971. }
  38972. /*
  38973. ** Check to see if element iRowid was inserted into the rowset as
  38974. ** part of any insert batch prior to iBatch. Return 1 or 0.
  38975. **
  38976. ** If this is the first test of a new batch and if there exist entires
  38977. ** on pRowSet->pEntry, then sort those entires into the forest at
  38978. ** pRowSet->pForest so that they can be tested.
  38979. */
  38980. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  38981. struct RowSetEntry *p, *pTree;
  38982. /* This routine is never called after sqlite3RowSetNext() */
  38983. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  38984. /* Sort entries into the forest on the first test of a new batch
  38985. */
  38986. if( iBatch!=pRowSet->iBatch ){
  38987. p = pRowSet->pEntry;
  38988. if( p ){
  38989. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  38990. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  38991. p = rowSetEntrySort(p);
  38992. }
  38993. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38994. ppPrevTree = &pTree->pRight;
  38995. if( pTree->pLeft==0 ){
  38996. pTree->pLeft = rowSetListToTree(p);
  38997. break;
  38998. }else{
  38999. struct RowSetEntry *pAux, *pTail;
  39000. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  39001. pTree->pLeft = 0;
  39002. p = rowSetEntryMerge(pAux, p);
  39003. }
  39004. }
  39005. if( pTree==0 ){
  39006. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  39007. if( pTree ){
  39008. pTree->v = 0;
  39009. pTree->pRight = 0;
  39010. pTree->pLeft = rowSetListToTree(p);
  39011. }
  39012. }
  39013. pRowSet->pEntry = 0;
  39014. pRowSet->pLast = 0;
  39015. pRowSet->rsFlags |= ROWSET_SORTED;
  39016. }
  39017. pRowSet->iBatch = iBatch;
  39018. }
  39019. /* Test to see if the iRowid value appears anywhere in the forest.
  39020. ** Return 1 if it does and 0 if not.
  39021. */
  39022. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  39023. p = pTree->pLeft;
  39024. while( p ){
  39025. if( p->v<iRowid ){
  39026. p = p->pRight;
  39027. }else if( p->v>iRowid ){
  39028. p = p->pLeft;
  39029. }else{
  39030. return 1;
  39031. }
  39032. }
  39033. }
  39034. return 0;
  39035. }
  39036. /************** End of rowset.c **********************************************/
  39037. /************** Begin file pager.c *******************************************/
  39038. /*
  39039. ** 2001 September 15
  39040. **
  39041. ** The author disclaims copyright to this source code. In place of
  39042. ** a legal notice, here is a blessing:
  39043. **
  39044. ** May you do good and not evil.
  39045. ** May you find forgiveness for yourself and forgive others.
  39046. ** May you share freely, never taking more than you give.
  39047. **
  39048. *************************************************************************
  39049. ** This is the implementation of the page cache subsystem or "pager".
  39050. **
  39051. ** The pager is used to access a database disk file. It implements
  39052. ** atomic commit and rollback through the use of a journal file that
  39053. ** is separate from the database file. The pager also implements file
  39054. ** locking to prevent two processes from writing the same database
  39055. ** file simultaneously, or one process from reading the database while
  39056. ** another is writing.
  39057. */
  39058. #ifndef SQLITE_OMIT_DISKIO
  39059. /************** Include wal.h in the middle of pager.c ***********************/
  39060. /************** Begin file wal.h *********************************************/
  39061. /*
  39062. ** 2010 February 1
  39063. **
  39064. ** The author disclaims copyright to this source code. In place of
  39065. ** a legal notice, here is a blessing:
  39066. **
  39067. ** May you do good and not evil.
  39068. ** May you find forgiveness for yourself and forgive others.
  39069. ** May you share freely, never taking more than you give.
  39070. **
  39071. *************************************************************************
  39072. ** This header file defines the interface to the write-ahead logging
  39073. ** system. Refer to the comments below and the header comment attached to
  39074. ** the implementation of each function in log.c for further details.
  39075. */
  39076. #ifndef _WAL_H_
  39077. #define _WAL_H_
  39078. /* Additional values that can be added to the sync_flags argument of
  39079. ** sqlite3WalFrames():
  39080. */
  39081. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  39082. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  39083. #ifdef SQLITE_OMIT_WAL
  39084. # define sqlite3WalOpen(x,y,z) 0
  39085. # define sqlite3WalLimit(x,y)
  39086. # define sqlite3WalClose(w,x,y,z) 0
  39087. # define sqlite3WalBeginReadTransaction(y,z) 0
  39088. # define sqlite3WalEndReadTransaction(z)
  39089. # define sqlite3WalDbsize(y) 0
  39090. # define sqlite3WalBeginWriteTransaction(y) 0
  39091. # define sqlite3WalEndWriteTransaction(x) 0
  39092. # define sqlite3WalUndo(x,y,z) 0
  39093. # define sqlite3WalSavepoint(y,z)
  39094. # define sqlite3WalSavepointUndo(y,z) 0
  39095. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  39096. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  39097. # define sqlite3WalCallback(z) 0
  39098. # define sqlite3WalExclusiveMode(y,z) 0
  39099. # define sqlite3WalHeapMemory(z) 0
  39100. # define sqlite3WalFramesize(z) 0
  39101. # define sqlite3WalFindFrame(x,y,z) 0
  39102. #else
  39103. #define WAL_SAVEPOINT_NDATA 4
  39104. /* Connection to a write-ahead log (WAL) file.
  39105. ** There is one object of this type for each pager.
  39106. */
  39107. typedef struct Wal Wal;
  39108. /* Open and close a connection to a write-ahead log. */
  39109. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  39110. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  39111. /* Set the limiting size of a WAL file. */
  39112. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  39113. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  39114. ** snapshot is like a read-transaction. It is the state of the database
  39115. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  39116. ** preserves the current state even if the other threads or processes
  39117. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  39118. ** transaction and releases the lock.
  39119. */
  39120. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  39121. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  39122. /* Read a page from the write-ahead log, if it is present. */
  39123. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  39124. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  39125. /* If the WAL is not empty, return the size of the database. */
  39126. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  39127. /* Obtain or release the WRITER lock. */
  39128. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  39129. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  39130. /* Undo any frames written (but not committed) to the log */
  39131. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  39132. /* Return an integer that records the current (uncommitted) write
  39133. ** position in the WAL */
  39134. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  39135. /* Move the write position of the WAL back to iFrame. Called in
  39136. ** response to a ROLLBACK TO command. */
  39137. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  39138. /* Write a frame or frames to the log. */
  39139. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  39140. /* Copy pages from the log to the database file */
  39141. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  39142. Wal *pWal, /* Write-ahead log connection */
  39143. int eMode, /* One of PASSIVE, FULL and RESTART */
  39144. int (*xBusy)(void*), /* Function to call when busy */
  39145. void *pBusyArg, /* Context argument for xBusyHandler */
  39146. int sync_flags, /* Flags to sync db file with (or 0) */
  39147. int nBuf, /* Size of buffer nBuf */
  39148. u8 *zBuf, /* Temporary buffer to use */
  39149. int *pnLog, /* OUT: Number of frames in WAL */
  39150. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  39151. );
  39152. /* Return the value to pass to a sqlite3_wal_hook callback, the
  39153. ** number of frames in the WAL at the point of the last commit since
  39154. ** sqlite3WalCallback() was called. If no commits have occurred since
  39155. ** the last call, then return 0.
  39156. */
  39157. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  39158. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  39159. ** by the pager layer on the database file.
  39160. */
  39161. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  39162. /* Return true if the argument is non-NULL and the WAL module is using
  39163. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  39164. ** WAL module is using shared-memory, return false.
  39165. */
  39166. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  39167. #ifdef SQLITE_ENABLE_ZIPVFS
  39168. /* If the WAL file is not empty, return the number of bytes of content
  39169. ** stored in each frame (i.e. the db page-size when the WAL was created).
  39170. */
  39171. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  39172. #endif
  39173. #endif /* ifndef SQLITE_OMIT_WAL */
  39174. #endif /* _WAL_H_ */
  39175. /************** End of wal.h *************************************************/
  39176. /************** Continuing where we left off in pager.c **********************/
  39177. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  39178. **
  39179. ** This comment block describes invariants that hold when using a rollback
  39180. ** journal. These invariants do not apply for journal_mode=WAL,
  39181. ** journal_mode=MEMORY, or journal_mode=OFF.
  39182. **
  39183. ** Within this comment block, a page is deemed to have been synced
  39184. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  39185. ** Otherwise, the page is not synced until the xSync method of the VFS
  39186. ** is called successfully on the file containing the page.
  39187. **
  39188. ** Definition: A page of the database file is said to be "overwriteable" if
  39189. ** one or more of the following are true about the page:
  39190. **
  39191. ** (a) The original content of the page as it was at the beginning of
  39192. ** the transaction has been written into the rollback journal and
  39193. ** synced.
  39194. **
  39195. ** (b) The page was a freelist leaf page at the start of the transaction.
  39196. **
  39197. ** (c) The page number is greater than the largest page that existed in
  39198. ** the database file at the start of the transaction.
  39199. **
  39200. ** (1) A page of the database file is never overwritten unless one of the
  39201. ** following are true:
  39202. **
  39203. ** (a) The page and all other pages on the same sector are overwriteable.
  39204. **
  39205. ** (b) The atomic page write optimization is enabled, and the entire
  39206. ** transaction other than the update of the transaction sequence
  39207. ** number consists of a single page change.
  39208. **
  39209. ** (2) The content of a page written into the rollback journal exactly matches
  39210. ** both the content in the database when the rollback journal was written
  39211. ** and the content in the database at the beginning of the current
  39212. ** transaction.
  39213. **
  39214. ** (3) Writes to the database file are an integer multiple of the page size
  39215. ** in length and are aligned on a page boundary.
  39216. **
  39217. ** (4) Reads from the database file are either aligned on a page boundary and
  39218. ** an integer multiple of the page size in length or are taken from the
  39219. ** first 100 bytes of the database file.
  39220. **
  39221. ** (5) All writes to the database file are synced prior to the rollback journal
  39222. ** being deleted, truncated, or zeroed.
  39223. **
  39224. ** (6) If a master journal file is used, then all writes to the database file
  39225. ** are synced prior to the master journal being deleted.
  39226. **
  39227. ** Definition: Two databases (or the same database at two points it time)
  39228. ** are said to be "logically equivalent" if they give the same answer to
  39229. ** all queries. Note in particular the content of freelist leaf
  39230. ** pages can be changed arbitarily without effecting the logical equivalence
  39231. ** of the database.
  39232. **
  39233. ** (7) At any time, if any subset, including the empty set and the total set,
  39234. ** of the unsynced changes to a rollback journal are removed and the
  39235. ** journal is rolled back, the resulting database file will be logical
  39236. ** equivalent to the database file at the beginning of the transaction.
  39237. **
  39238. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  39239. ** is called to restore the database file to the same size it was at
  39240. ** the beginning of the transaction. (In some VFSes, the xTruncate
  39241. ** method is a no-op, but that does not change the fact the SQLite will
  39242. ** invoke it.)
  39243. **
  39244. ** (9) Whenever the database file is modified, at least one bit in the range
  39245. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  39246. ** the EXCLUSIVE lock, thus signaling other connections on the same
  39247. ** database to flush their caches.
  39248. **
  39249. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  39250. ** than one billion transactions.
  39251. **
  39252. ** (11) A database file is well-formed at the beginning and at the conclusion
  39253. ** of every transaction.
  39254. **
  39255. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  39256. ** the database file.
  39257. **
  39258. ** (13) A SHARED lock is held on the database file while reading any
  39259. ** content out of the database file.
  39260. **
  39261. ******************************************************************************/
  39262. /*
  39263. ** Macros for troubleshooting. Normally turned off
  39264. */
  39265. #if 0
  39266. int sqlite3PagerTrace=1; /* True to enable tracing */
  39267. #define sqlite3DebugPrintf printf
  39268. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  39269. #else
  39270. #define PAGERTRACE(X)
  39271. #endif
  39272. /*
  39273. ** The following two macros are used within the PAGERTRACE() macros above
  39274. ** to print out file-descriptors.
  39275. **
  39276. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  39277. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  39278. ** struct as its argument.
  39279. */
  39280. #define PAGERID(p) ((int)(p->fd))
  39281. #define FILEHANDLEID(fd) ((int)fd)
  39282. /*
  39283. ** The Pager.eState variable stores the current 'state' of a pager. A
  39284. ** pager may be in any one of the seven states shown in the following
  39285. ** state diagram.
  39286. **
  39287. ** OPEN <------+------+
  39288. ** | | |
  39289. ** V | |
  39290. ** +---------> READER-------+ |
  39291. ** | | |
  39292. ** | V |
  39293. ** |<-------WRITER_LOCKED------> ERROR
  39294. ** | | ^
  39295. ** | V |
  39296. ** |<------WRITER_CACHEMOD-------->|
  39297. ** | | |
  39298. ** | V |
  39299. ** |<-------WRITER_DBMOD---------->|
  39300. ** | | |
  39301. ** | V |
  39302. ** +<------WRITER_FINISHED-------->+
  39303. **
  39304. **
  39305. ** List of state transitions and the C [function] that performs each:
  39306. **
  39307. ** OPEN -> READER [sqlite3PagerSharedLock]
  39308. ** READER -> OPEN [pager_unlock]
  39309. **
  39310. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  39311. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  39312. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  39313. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  39314. ** WRITER_*** -> READER [pager_end_transaction]
  39315. **
  39316. ** WRITER_*** -> ERROR [pager_error]
  39317. ** ERROR -> OPEN [pager_unlock]
  39318. **
  39319. **
  39320. ** OPEN:
  39321. **
  39322. ** The pager starts up in this state. Nothing is guaranteed in this
  39323. ** state - the file may or may not be locked and the database size is
  39324. ** unknown. The database may not be read or written.
  39325. **
  39326. ** * No read or write transaction is active.
  39327. ** * Any lock, or no lock at all, may be held on the database file.
  39328. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  39329. **
  39330. ** READER:
  39331. **
  39332. ** In this state all the requirements for reading the database in
  39333. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  39334. ** was) in exclusive-locking mode, a user-level read transaction is
  39335. ** open. The database size is known in this state.
  39336. **
  39337. ** A connection running with locking_mode=normal enters this state when
  39338. ** it opens a read-transaction on the database and returns to state
  39339. ** OPEN after the read-transaction is completed. However a connection
  39340. ** running in locking_mode=exclusive (including temp databases) remains in
  39341. ** this state even after the read-transaction is closed. The only way
  39342. ** a locking_mode=exclusive connection can transition from READER to OPEN
  39343. ** is via the ERROR state (see below).
  39344. **
  39345. ** * A read transaction may be active (but a write-transaction cannot).
  39346. ** * A SHARED or greater lock is held on the database file.
  39347. ** * The dbSize variable may be trusted (even if a user-level read
  39348. ** transaction is not active). The dbOrigSize and dbFileSize variables
  39349. ** may not be trusted at this point.
  39350. ** * If the database is a WAL database, then the WAL connection is open.
  39351. ** * Even if a read-transaction is not open, it is guaranteed that
  39352. ** there is no hot-journal in the file-system.
  39353. **
  39354. ** WRITER_LOCKED:
  39355. **
  39356. ** The pager moves to this state from READER when a write-transaction
  39357. ** is first opened on the database. In WRITER_LOCKED state, all locks
  39358. ** required to start a write-transaction are held, but no actual
  39359. ** modifications to the cache or database have taken place.
  39360. **
  39361. ** In rollback mode, a RESERVED or (if the transaction was opened with
  39362. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  39363. ** moving to this state, but the journal file is not written to or opened
  39364. ** to in this state. If the transaction is committed or rolled back while
  39365. ** in WRITER_LOCKED state, all that is required is to unlock the database
  39366. ** file.
  39367. **
  39368. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  39369. ** If the connection is running with locking_mode=exclusive, an attempt
  39370. ** is made to obtain an EXCLUSIVE lock on the database file.
  39371. **
  39372. ** * A write transaction is active.
  39373. ** * If the connection is open in rollback-mode, a RESERVED or greater
  39374. ** lock is held on the database file.
  39375. ** * If the connection is open in WAL-mode, a WAL write transaction
  39376. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  39377. ** called).
  39378. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  39379. ** * The contents of the pager cache have not been modified.
  39380. ** * The journal file may or may not be open.
  39381. ** * Nothing (not even the first header) has been written to the journal.
  39382. **
  39383. ** WRITER_CACHEMOD:
  39384. **
  39385. ** A pager moves from WRITER_LOCKED state to this state when a page is
  39386. ** first modified by the upper layer. In rollback mode the journal file
  39387. ** is opened (if it is not already open) and a header written to the
  39388. ** start of it. The database file on disk has not been modified.
  39389. **
  39390. ** * A write transaction is active.
  39391. ** * A RESERVED or greater lock is held on the database file.
  39392. ** * The journal file is open and the first header has been written
  39393. ** to it, but the header has not been synced to disk.
  39394. ** * The contents of the page cache have been modified.
  39395. **
  39396. ** WRITER_DBMOD:
  39397. **
  39398. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  39399. ** when it modifies the contents of the database file. WAL connections
  39400. ** never enter this state (since they do not modify the database file,
  39401. ** just the log file).
  39402. **
  39403. ** * A write transaction is active.
  39404. ** * An EXCLUSIVE or greater lock is held on the database file.
  39405. ** * The journal file is open and the first header has been written
  39406. ** and synced to disk.
  39407. ** * The contents of the page cache have been modified (and possibly
  39408. ** written to disk).
  39409. **
  39410. ** WRITER_FINISHED:
  39411. **
  39412. ** It is not possible for a WAL connection to enter this state.
  39413. **
  39414. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  39415. ** state after the entire transaction has been successfully written into the
  39416. ** database file. In this state the transaction may be committed simply
  39417. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  39418. ** not possible to modify the database further. At this point, the upper
  39419. ** layer must either commit or rollback the transaction.
  39420. **
  39421. ** * A write transaction is active.
  39422. ** * An EXCLUSIVE or greater lock is held on the database file.
  39423. ** * All writing and syncing of journal and database data has finished.
  39424. ** If no error occurred, all that remains is to finalize the journal to
  39425. ** commit the transaction. If an error did occur, the caller will need
  39426. ** to rollback the transaction.
  39427. **
  39428. ** ERROR:
  39429. **
  39430. ** The ERROR state is entered when an IO or disk-full error (including
  39431. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  39432. ** difficult to be sure that the in-memory pager state (cache contents,
  39433. ** db size etc.) are consistent with the contents of the file-system.
  39434. **
  39435. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  39436. ** cannot.
  39437. **
  39438. ** For example, if an IO error occurs while performing a rollback,
  39439. ** the contents of the page-cache may be left in an inconsistent state.
  39440. ** At this point it would be dangerous to change back to READER state
  39441. ** (as usually happens after a rollback). Any subsequent readers might
  39442. ** report database corruption (due to the inconsistent cache), and if
  39443. ** they upgrade to writers, they may inadvertently corrupt the database
  39444. ** file. To avoid this hazard, the pager switches into the ERROR state
  39445. ** instead of READER following such an error.
  39446. **
  39447. ** Once it has entered the ERROR state, any attempt to use the pager
  39448. ** to read or write data returns an error. Eventually, once all
  39449. ** outstanding transactions have been abandoned, the pager is able to
  39450. ** transition back to OPEN state, discarding the contents of the
  39451. ** page-cache and any other in-memory state at the same time. Everything
  39452. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  39453. ** when a read-transaction is next opened on the pager (transitioning
  39454. ** the pager into READER state). At that point the system has recovered
  39455. ** from the error.
  39456. **
  39457. ** Specifically, the pager jumps into the ERROR state if:
  39458. **
  39459. ** 1. An error occurs while attempting a rollback. This happens in
  39460. ** function sqlite3PagerRollback().
  39461. **
  39462. ** 2. An error occurs while attempting to finalize a journal file
  39463. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  39464. **
  39465. ** 3. An error occurs while attempting to write to the journal or
  39466. ** database file in function pagerStress() in order to free up
  39467. ** memory.
  39468. **
  39469. ** In other cases, the error is returned to the b-tree layer. The b-tree
  39470. ** layer then attempts a rollback operation. If the error condition
  39471. ** persists, the pager enters the ERROR state via condition (1) above.
  39472. **
  39473. ** Condition (3) is necessary because it can be triggered by a read-only
  39474. ** statement executed within a transaction. In this case, if the error
  39475. ** code were simply returned to the user, the b-tree layer would not
  39476. ** automatically attempt a rollback, as it assumes that an error in a
  39477. ** read-only statement cannot leave the pager in an internally inconsistent
  39478. ** state.
  39479. **
  39480. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  39481. ** * There are one or more outstanding references to pages (after the
  39482. ** last reference is dropped the pager should move back to OPEN state).
  39483. ** * The pager is not an in-memory pager.
  39484. **
  39485. **
  39486. ** Notes:
  39487. **
  39488. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  39489. ** connection is open in WAL mode. A WAL connection is always in one
  39490. ** of the first four states.
  39491. **
  39492. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  39493. ** state. There are two exceptions: immediately after exclusive-mode has
  39494. ** been turned on (and before any read or write transactions are
  39495. ** executed), and when the pager is leaving the "error state".
  39496. **
  39497. ** * See also: assert_pager_state().
  39498. */
  39499. #define PAGER_OPEN 0
  39500. #define PAGER_READER 1
  39501. #define PAGER_WRITER_LOCKED 2
  39502. #define PAGER_WRITER_CACHEMOD 3
  39503. #define PAGER_WRITER_DBMOD 4
  39504. #define PAGER_WRITER_FINISHED 5
  39505. #define PAGER_ERROR 6
  39506. /*
  39507. ** The Pager.eLock variable is almost always set to one of the
  39508. ** following locking-states, according to the lock currently held on
  39509. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39510. ** This variable is kept up to date as locks are taken and released by
  39511. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  39512. **
  39513. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  39514. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  39515. ** the operation was successful. In these circumstances pagerLockDb() and
  39516. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  39517. ** when unlocking the file, and only updated when locking the file if the
  39518. ** VFS call is successful. This way, the Pager.eLock variable may be set
  39519. ** to a less exclusive (lower) value than the lock that is actually held
  39520. ** at the system level, but it is never set to a more exclusive value.
  39521. **
  39522. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  39523. ** be a few redundant xLock() calls or a lock may be held for longer than
  39524. ** required, but nothing really goes wrong.
  39525. **
  39526. ** The exception is when the database file is unlocked as the pager moves
  39527. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  39528. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  39529. ** transition, by the same pager or any other). If the call to xUnlock()
  39530. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  39531. ** can confuse the call to xCheckReservedLock() call made later as part
  39532. ** of hot-journal detection.
  39533. **
  39534. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  39535. ** lock held by this process or any others". So xCheckReservedLock may
  39536. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  39537. ** doesn't know it because of a previous error in xUnlock). If this happens
  39538. ** a hot-journal may be mistaken for a journal being created by an active
  39539. ** transaction in another process, causing SQLite to read from the database
  39540. ** without rolling it back.
  39541. **
  39542. ** To work around this, if a call to xUnlock() fails when unlocking the
  39543. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  39544. ** is only changed back to a real locking state after a successful call
  39545. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  39546. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  39547. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  39548. ** lock on the database file before attempting to roll it back. See function
  39549. ** PagerSharedLock() for more detail.
  39550. **
  39551. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  39552. ** PAGER_OPEN state.
  39553. */
  39554. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  39555. /*
  39556. ** A macro used for invoking the codec if there is one
  39557. */
  39558. #ifdef SQLITE_HAS_CODEC
  39559. # define CODEC1(P,D,N,X,E) \
  39560. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  39561. # define CODEC2(P,D,N,X,E,O) \
  39562. if( P->xCodec==0 ){ O=(char*)D; }else \
  39563. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  39564. #else
  39565. # define CODEC1(P,D,N,X,E) /* NO-OP */
  39566. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  39567. #endif
  39568. /*
  39569. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  39570. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  39571. ** This could conceivably cause corruption following a power failure on
  39572. ** such a system. This is currently an undocumented limit.
  39573. */
  39574. #define MAX_SECTOR_SIZE 0x10000
  39575. /*
  39576. ** An instance of the following structure is allocated for each active
  39577. ** savepoint and statement transaction in the system. All such structures
  39578. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  39579. ** resized using sqlite3Realloc().
  39580. **
  39581. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  39582. ** set to 0. If a journal-header is written into the main journal while
  39583. ** the savepoint is active, then iHdrOffset is set to the byte offset
  39584. ** immediately following the last journal record written into the main
  39585. ** journal before the journal-header. This is required during savepoint
  39586. ** rollback (see pagerPlaybackSavepoint()).
  39587. */
  39588. typedef struct PagerSavepoint PagerSavepoint;
  39589. struct PagerSavepoint {
  39590. i64 iOffset; /* Starting offset in main journal */
  39591. i64 iHdrOffset; /* See above */
  39592. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  39593. Pgno nOrig; /* Original number of pages in file */
  39594. Pgno iSubRec; /* Index of first record in sub-journal */
  39595. #ifndef SQLITE_OMIT_WAL
  39596. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  39597. #endif
  39598. };
  39599. /*
  39600. ** Bits of the Pager.doNotSpill flag. See further description below.
  39601. */
  39602. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  39603. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  39604. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  39605. /*
  39606. ** A open page cache is an instance of struct Pager. A description of
  39607. ** some of the more important member variables follows:
  39608. **
  39609. ** eState
  39610. **
  39611. ** The current 'state' of the pager object. See the comment and state
  39612. ** diagram above for a description of the pager state.
  39613. **
  39614. ** eLock
  39615. **
  39616. ** For a real on-disk database, the current lock held on the database file -
  39617. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39618. **
  39619. ** For a temporary or in-memory database (neither of which require any
  39620. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  39621. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  39622. ** logic into thinking that it already has all the locks it will ever
  39623. ** need (and no reason to release them).
  39624. **
  39625. ** In some (obscure) circumstances, this variable may also be set to
  39626. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  39627. ** details.
  39628. **
  39629. ** changeCountDone
  39630. **
  39631. ** This boolean variable is used to make sure that the change-counter
  39632. ** (the 4-byte header field at byte offset 24 of the database file) is
  39633. ** not updated more often than necessary.
  39634. **
  39635. ** It is set to true when the change-counter field is updated, which
  39636. ** can only happen if an exclusive lock is held on the database file.
  39637. ** It is cleared (set to false) whenever an exclusive lock is
  39638. ** relinquished on the database file. Each time a transaction is committed,
  39639. ** The changeCountDone flag is inspected. If it is true, the work of
  39640. ** updating the change-counter is omitted for the current transaction.
  39641. **
  39642. ** This mechanism means that when running in exclusive mode, a connection
  39643. ** need only update the change-counter once, for the first transaction
  39644. ** committed.
  39645. **
  39646. ** setMaster
  39647. **
  39648. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  39649. ** (or may not) specify a master-journal name to be written into the
  39650. ** journal file before it is synced to disk.
  39651. **
  39652. ** Whether or not a journal file contains a master-journal pointer affects
  39653. ** the way in which the journal file is finalized after the transaction is
  39654. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  39655. ** If a journal file does not contain a master-journal pointer, it is
  39656. ** finalized by overwriting the first journal header with zeroes. If
  39657. ** it does contain a master-journal pointer the journal file is finalized
  39658. ** by truncating it to zero bytes, just as if the connection were
  39659. ** running in "journal_mode=truncate" mode.
  39660. **
  39661. ** Journal files that contain master journal pointers cannot be finalized
  39662. ** simply by overwriting the first journal-header with zeroes, as the
  39663. ** master journal pointer could interfere with hot-journal rollback of any
  39664. ** subsequently interrupted transaction that reuses the journal file.
  39665. **
  39666. ** The flag is cleared as soon as the journal file is finalized (either
  39667. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  39668. ** journal file from being successfully finalized, the setMaster flag
  39669. ** is cleared anyway (and the pager will move to ERROR state).
  39670. **
  39671. ** doNotSpill
  39672. **
  39673. ** This variables control the behavior of cache-spills (calls made by
  39674. ** the pcache module to the pagerStress() routine to write cached data
  39675. ** to the file-system in order to free up memory).
  39676. **
  39677. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  39678. ** writing to the database from pagerStress() is disabled altogether.
  39679. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  39680. ** comes up during savepoint rollback that requires the pcache module
  39681. ** to allocate a new page to prevent the journal file from being written
  39682. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  39683. ** case is a user preference.
  39684. **
  39685. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  39686. ** is permitted, but syncing the journal file is not. This flag is set
  39687. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  39688. ** the database page-size in order to prevent a journal sync from happening
  39689. ** in between the journalling of two pages on the same sector.
  39690. **
  39691. ** subjInMemory
  39692. **
  39693. ** This is a boolean variable. If true, then any required sub-journal
  39694. ** is opened as an in-memory journal file. If false, then in-memory
  39695. ** sub-journals are only used for in-memory pager files.
  39696. **
  39697. ** This variable is updated by the upper layer each time a new
  39698. ** write-transaction is opened.
  39699. **
  39700. ** dbSize, dbOrigSize, dbFileSize
  39701. **
  39702. ** Variable dbSize is set to the number of pages in the database file.
  39703. ** It is valid in PAGER_READER and higher states (all states except for
  39704. ** OPEN and ERROR).
  39705. **
  39706. ** dbSize is set based on the size of the database file, which may be
  39707. ** larger than the size of the database (the value stored at offset
  39708. ** 28 of the database header by the btree). If the size of the file
  39709. ** is not an integer multiple of the page-size, the value stored in
  39710. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  39711. ** Except, any file that is greater than 0 bytes in size is considered
  39712. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  39713. ** to dbSize==1).
  39714. **
  39715. ** During a write-transaction, if pages with page-numbers greater than
  39716. ** dbSize are modified in the cache, dbSize is updated accordingly.
  39717. ** Similarly, if the database is truncated using PagerTruncateImage(),
  39718. ** dbSize is updated.
  39719. **
  39720. ** Variables dbOrigSize and dbFileSize are valid in states
  39721. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  39722. ** variable at the start of the transaction. It is used during rollback,
  39723. ** and to determine whether or not pages need to be journalled before
  39724. ** being modified.
  39725. **
  39726. ** Throughout a write-transaction, dbFileSize contains the size of
  39727. ** the file on disk in pages. It is set to a copy of dbSize when the
  39728. ** write-transaction is first opened, and updated when VFS calls are made
  39729. ** to write or truncate the database file on disk.
  39730. **
  39731. ** The only reason the dbFileSize variable is required is to suppress
  39732. ** unnecessary calls to xTruncate() after committing a transaction. If,
  39733. ** when a transaction is committed, the dbFileSize variable indicates
  39734. ** that the database file is larger than the database image (Pager.dbSize),
  39735. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  39736. ** to measure the database file on disk, and then truncates it if required.
  39737. ** dbFileSize is not used when rolling back a transaction. In this case
  39738. ** pager_truncate() is called unconditionally (which means there may be
  39739. ** a call to xFilesize() that is not strictly required). In either case,
  39740. ** pager_truncate() may cause the file to become smaller or larger.
  39741. **
  39742. ** dbHintSize
  39743. **
  39744. ** The dbHintSize variable is used to limit the number of calls made to
  39745. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  39746. **
  39747. ** dbHintSize is set to a copy of the dbSize variable when a
  39748. ** write-transaction is opened (at the same time as dbFileSize and
  39749. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  39750. ** dbHintSize is increased to the number of pages that correspond to the
  39751. ** size-hint passed to the method call. See pager_write_pagelist() for
  39752. ** details.
  39753. **
  39754. ** errCode
  39755. **
  39756. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  39757. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  39758. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  39759. ** sub-codes.
  39760. */
  39761. struct Pager {
  39762. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  39763. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  39764. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  39765. u8 useJournal; /* Use a rollback journal on this file */
  39766. u8 noSync; /* Do not sync the journal if true */
  39767. u8 fullSync; /* Do extra syncs of the journal for robustness */
  39768. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  39769. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  39770. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  39771. u8 tempFile; /* zFilename is a temporary file */
  39772. u8 readOnly; /* True for a read-only database */
  39773. u8 memDb; /* True to inhibit all file I/O */
  39774. /**************************************************************************
  39775. ** The following block contains those class members that change during
  39776. ** routine opertion. Class members not in this block are either fixed
  39777. ** when the pager is first created or else only change when there is a
  39778. ** significant mode change (such as changing the page_size, locking_mode,
  39779. ** or the journal_mode). From another view, these class members describe
  39780. ** the "state" of the pager, while other class members describe the
  39781. ** "configuration" of the pager.
  39782. */
  39783. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  39784. u8 eLock; /* Current lock held on database file */
  39785. u8 changeCountDone; /* Set after incrementing the change-counter */
  39786. u8 setMaster; /* True if a m-j name has been written to jrnl */
  39787. u8 doNotSpill; /* Do not spill the cache when non-zero */
  39788. u8 subjInMemory; /* True to use in-memory sub-journals */
  39789. Pgno dbSize; /* Number of pages in the database */
  39790. Pgno dbOrigSize; /* dbSize before the current transaction */
  39791. Pgno dbFileSize; /* Number of pages in the database file */
  39792. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  39793. int errCode; /* One of several kinds of errors */
  39794. int nRec; /* Pages journalled since last j-header written */
  39795. u32 cksumInit; /* Quasi-random value added to every checksum */
  39796. u32 nSubRec; /* Number of records written to sub-journal */
  39797. Bitvec *pInJournal; /* One bit for each page in the database file */
  39798. sqlite3_file *fd; /* File descriptor for database */
  39799. sqlite3_file *jfd; /* File descriptor for main journal */
  39800. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  39801. i64 journalOff; /* Current write offset in the journal file */
  39802. i64 journalHdr; /* Byte offset to previous journal header */
  39803. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  39804. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  39805. int nSavepoint; /* Number of elements in aSavepoint[] */
  39806. char dbFileVers[16]; /* Changes whenever database file changes */
  39807. u8 bUseFetch; /* True to use xFetch() */
  39808. int nMmapOut; /* Number of mmap pages currently outstanding */
  39809. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  39810. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  39811. /*
  39812. ** End of the routinely-changing class members
  39813. ***************************************************************************/
  39814. u16 nExtra; /* Add this many bytes to each in-memory page */
  39815. i16 nReserve; /* Number of unused bytes at end of each page */
  39816. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  39817. u32 sectorSize; /* Assumed sector size during rollback */
  39818. int pageSize; /* Number of bytes in a page */
  39819. Pgno mxPgno; /* Maximum allowed size of the database */
  39820. i64 journalSizeLimit; /* Size limit for persistent journal files */
  39821. char *zFilename; /* Name of the database file */
  39822. char *zJournal; /* Name of the journal file */
  39823. int (*xBusyHandler)(void*); /* Function to call when busy */
  39824. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  39825. int aStat[3]; /* Total cache hits, misses and writes */
  39826. #ifdef SQLITE_TEST
  39827. int nRead; /* Database pages read */
  39828. #endif
  39829. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  39830. #ifdef SQLITE_HAS_CODEC
  39831. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  39832. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  39833. void (*xCodecFree)(void*); /* Destructor for the codec */
  39834. void *pCodec; /* First argument to xCodec... methods */
  39835. #endif
  39836. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  39837. PCache *pPCache; /* Pointer to page cache object */
  39838. #ifndef SQLITE_OMIT_WAL
  39839. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  39840. char *zWal; /* File name for write-ahead log */
  39841. #endif
  39842. };
  39843. /*
  39844. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  39845. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  39846. ** or CACHE_WRITE to sqlite3_db_status().
  39847. */
  39848. #define PAGER_STAT_HIT 0
  39849. #define PAGER_STAT_MISS 1
  39850. #define PAGER_STAT_WRITE 2
  39851. /*
  39852. ** The following global variables hold counters used for
  39853. ** testing purposes only. These variables do not exist in
  39854. ** a non-testing build. These variables are not thread-safe.
  39855. */
  39856. #ifdef SQLITE_TEST
  39857. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  39858. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  39859. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  39860. # define PAGER_INCR(v) v++
  39861. #else
  39862. # define PAGER_INCR(v)
  39863. #endif
  39864. /*
  39865. ** Journal files begin with the following magic string. The data
  39866. ** was obtained from /dev/random. It is used only as a sanity check.
  39867. **
  39868. ** Since version 2.8.0, the journal format contains additional sanity
  39869. ** checking information. If the power fails while the journal is being
  39870. ** written, semi-random garbage data might appear in the journal
  39871. ** file after power is restored. If an attempt is then made
  39872. ** to roll the journal back, the database could be corrupted. The additional
  39873. ** sanity checking data is an attempt to discover the garbage in the
  39874. ** journal and ignore it.
  39875. **
  39876. ** The sanity checking information for the new journal format consists
  39877. ** of a 32-bit checksum on each page of data. The checksum covers both
  39878. ** the page number and the pPager->pageSize bytes of data for the page.
  39879. ** This cksum is initialized to a 32-bit random value that appears in the
  39880. ** journal file right after the header. The random initializer is important,
  39881. ** because garbage data that appears at the end of a journal is likely
  39882. ** data that was once in other files that have now been deleted. If the
  39883. ** garbage data came from an obsolete journal file, the checksums might
  39884. ** be correct. But by initializing the checksum to random value which
  39885. ** is different for every journal, we minimize that risk.
  39886. */
  39887. static const unsigned char aJournalMagic[] = {
  39888. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  39889. };
  39890. /*
  39891. ** The size of the of each page record in the journal is given by
  39892. ** the following macro.
  39893. */
  39894. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  39895. /*
  39896. ** The journal header size for this pager. This is usually the same
  39897. ** size as a single disk sector. See also setSectorSize().
  39898. */
  39899. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  39900. /*
  39901. ** The macro MEMDB is true if we are dealing with an in-memory database.
  39902. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  39903. ** the value of MEMDB will be a constant and the compiler will optimize
  39904. ** out code that would never execute.
  39905. */
  39906. #ifdef SQLITE_OMIT_MEMORYDB
  39907. # define MEMDB 0
  39908. #else
  39909. # define MEMDB pPager->memDb
  39910. #endif
  39911. /*
  39912. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  39913. ** interfaces to access the database using memory-mapped I/O.
  39914. */
  39915. #if SQLITE_MAX_MMAP_SIZE>0
  39916. # define USEFETCH(x) ((x)->bUseFetch)
  39917. #else
  39918. # define USEFETCH(x) 0
  39919. #endif
  39920. /*
  39921. ** The maximum legal page number is (2^31 - 1).
  39922. */
  39923. #define PAGER_MAX_PGNO 2147483647
  39924. /*
  39925. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  39926. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  39927. **
  39928. ** This is so that expressions can be written as:
  39929. **
  39930. ** if( isOpen(pPager->jfd) ){ ...
  39931. **
  39932. ** instead of
  39933. **
  39934. ** if( pPager->jfd->pMethods ){ ...
  39935. */
  39936. #define isOpen(pFd) ((pFd)->pMethods)
  39937. /*
  39938. ** Return true if this pager uses a write-ahead log instead of the usual
  39939. ** rollback journal. Otherwise false.
  39940. */
  39941. #ifndef SQLITE_OMIT_WAL
  39942. static int pagerUseWal(Pager *pPager){
  39943. return (pPager->pWal!=0);
  39944. }
  39945. #else
  39946. # define pagerUseWal(x) 0
  39947. # define pagerRollbackWal(x) 0
  39948. # define pagerWalFrames(v,w,x,y) 0
  39949. # define pagerOpenWalIfPresent(z) SQLITE_OK
  39950. # define pagerBeginReadTransaction(z) SQLITE_OK
  39951. #endif
  39952. #ifndef NDEBUG
  39953. /*
  39954. ** Usage:
  39955. **
  39956. ** assert( assert_pager_state(pPager) );
  39957. **
  39958. ** This function runs many asserts to try to find inconsistencies in
  39959. ** the internal state of the Pager object.
  39960. */
  39961. static int assert_pager_state(Pager *p){
  39962. Pager *pPager = p;
  39963. /* State must be valid. */
  39964. assert( p->eState==PAGER_OPEN
  39965. || p->eState==PAGER_READER
  39966. || p->eState==PAGER_WRITER_LOCKED
  39967. || p->eState==PAGER_WRITER_CACHEMOD
  39968. || p->eState==PAGER_WRITER_DBMOD
  39969. || p->eState==PAGER_WRITER_FINISHED
  39970. || p->eState==PAGER_ERROR
  39971. );
  39972. /* Regardless of the current state, a temp-file connection always behaves
  39973. ** as if it has an exclusive lock on the database file. It never updates
  39974. ** the change-counter field, so the changeCountDone flag is always set.
  39975. */
  39976. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  39977. assert( p->tempFile==0 || pPager->changeCountDone );
  39978. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  39979. ** And if the journal-mode is "OFF", the journal file must not be open.
  39980. */
  39981. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  39982. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  39983. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  39984. ** this means an in-memory pager performs no IO at all, it cannot encounter
  39985. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  39986. ** a journal file. (although the in-memory journal implementation may
  39987. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  39988. ** is therefore not possible for an in-memory pager to enter the ERROR
  39989. ** state.
  39990. */
  39991. if( MEMDB ){
  39992. assert( p->noSync );
  39993. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  39994. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  39995. );
  39996. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  39997. assert( pagerUseWal(p)==0 );
  39998. }
  39999. /* If changeCountDone is set, a RESERVED lock or greater must be held
  40000. ** on the file.
  40001. */
  40002. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  40003. assert( p->eLock!=PENDING_LOCK );
  40004. switch( p->eState ){
  40005. case PAGER_OPEN:
  40006. assert( !MEMDB );
  40007. assert( pPager->errCode==SQLITE_OK );
  40008. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  40009. break;
  40010. case PAGER_READER:
  40011. assert( pPager->errCode==SQLITE_OK );
  40012. assert( p->eLock!=UNKNOWN_LOCK );
  40013. assert( p->eLock>=SHARED_LOCK );
  40014. break;
  40015. case PAGER_WRITER_LOCKED:
  40016. assert( p->eLock!=UNKNOWN_LOCK );
  40017. assert( pPager->errCode==SQLITE_OK );
  40018. if( !pagerUseWal(pPager) ){
  40019. assert( p->eLock>=RESERVED_LOCK );
  40020. }
  40021. assert( pPager->dbSize==pPager->dbOrigSize );
  40022. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40023. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40024. assert( pPager->setMaster==0 );
  40025. break;
  40026. case PAGER_WRITER_CACHEMOD:
  40027. assert( p->eLock!=UNKNOWN_LOCK );
  40028. assert( pPager->errCode==SQLITE_OK );
  40029. if( !pagerUseWal(pPager) ){
  40030. /* It is possible that if journal_mode=wal here that neither the
  40031. ** journal file nor the WAL file are open. This happens during
  40032. ** a rollback transaction that switches from journal_mode=off
  40033. ** to journal_mode=wal.
  40034. */
  40035. assert( p->eLock>=RESERVED_LOCK );
  40036. assert( isOpen(p->jfd)
  40037. || p->journalMode==PAGER_JOURNALMODE_OFF
  40038. || p->journalMode==PAGER_JOURNALMODE_WAL
  40039. );
  40040. }
  40041. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40042. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40043. break;
  40044. case PAGER_WRITER_DBMOD:
  40045. assert( p->eLock==EXCLUSIVE_LOCK );
  40046. assert( pPager->errCode==SQLITE_OK );
  40047. assert( !pagerUseWal(pPager) );
  40048. assert( p->eLock>=EXCLUSIVE_LOCK );
  40049. assert( isOpen(p->jfd)
  40050. || p->journalMode==PAGER_JOURNALMODE_OFF
  40051. || p->journalMode==PAGER_JOURNALMODE_WAL
  40052. );
  40053. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  40054. break;
  40055. case PAGER_WRITER_FINISHED:
  40056. assert( p->eLock==EXCLUSIVE_LOCK );
  40057. assert( pPager->errCode==SQLITE_OK );
  40058. assert( !pagerUseWal(pPager) );
  40059. assert( isOpen(p->jfd)
  40060. || p->journalMode==PAGER_JOURNALMODE_OFF
  40061. || p->journalMode==PAGER_JOURNALMODE_WAL
  40062. );
  40063. break;
  40064. case PAGER_ERROR:
  40065. /* There must be at least one outstanding reference to the pager if
  40066. ** in ERROR state. Otherwise the pager should have already dropped
  40067. ** back to OPEN state.
  40068. */
  40069. assert( pPager->errCode!=SQLITE_OK );
  40070. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  40071. break;
  40072. }
  40073. return 1;
  40074. }
  40075. #endif /* ifndef NDEBUG */
  40076. #ifdef SQLITE_DEBUG
  40077. /*
  40078. ** Return a pointer to a human readable string in a static buffer
  40079. ** containing the state of the Pager object passed as an argument. This
  40080. ** is intended to be used within debuggers. For example, as an alternative
  40081. ** to "print *pPager" in gdb:
  40082. **
  40083. ** (gdb) printf "%s", print_pager_state(pPager)
  40084. */
  40085. static char *print_pager_state(Pager *p){
  40086. static char zRet[1024];
  40087. sqlite3_snprintf(1024, zRet,
  40088. "Filename: %s\n"
  40089. "State: %s errCode=%d\n"
  40090. "Lock: %s\n"
  40091. "Locking mode: locking_mode=%s\n"
  40092. "Journal mode: journal_mode=%s\n"
  40093. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  40094. "Journal: journalOff=%lld journalHdr=%lld\n"
  40095. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  40096. , p->zFilename
  40097. , p->eState==PAGER_OPEN ? "OPEN" :
  40098. p->eState==PAGER_READER ? "READER" :
  40099. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  40100. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  40101. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  40102. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  40103. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  40104. , (int)p->errCode
  40105. , p->eLock==NO_LOCK ? "NO_LOCK" :
  40106. p->eLock==RESERVED_LOCK ? "RESERVED" :
  40107. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  40108. p->eLock==SHARED_LOCK ? "SHARED" :
  40109. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  40110. , p->exclusiveMode ? "exclusive" : "normal"
  40111. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  40112. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  40113. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  40114. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  40115. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  40116. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  40117. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  40118. , p->journalOff, p->journalHdr
  40119. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  40120. );
  40121. return zRet;
  40122. }
  40123. #endif
  40124. /*
  40125. ** Return true if it is necessary to write page *pPg into the sub-journal.
  40126. ** A page needs to be written into the sub-journal if there exists one
  40127. ** or more open savepoints for which:
  40128. **
  40129. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  40130. ** * The bit corresponding to the page-number is not set in
  40131. ** PagerSavepoint.pInSavepoint.
  40132. */
  40133. static int subjRequiresPage(PgHdr *pPg){
  40134. Pager *pPager = pPg->pPager;
  40135. PagerSavepoint *p;
  40136. Pgno pgno;
  40137. int i;
  40138. if( pPager->nSavepoint ){
  40139. pgno = pPg->pgno;
  40140. for(i=0; i<pPager->nSavepoint; i++){
  40141. p = &pPager->aSavepoint[i];
  40142. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  40143. return 1;
  40144. }
  40145. }
  40146. }
  40147. return 0;
  40148. }
  40149. /*
  40150. ** Return true if the page is already in the journal file.
  40151. */
  40152. static int pageInJournal(PgHdr *pPg){
  40153. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  40154. }
  40155. /*
  40156. ** Read a 32-bit integer from the given file descriptor. Store the integer
  40157. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  40158. ** error code is something goes wrong.
  40159. **
  40160. ** All values are stored on disk as big-endian.
  40161. */
  40162. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  40163. unsigned char ac[4];
  40164. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  40165. if( rc==SQLITE_OK ){
  40166. *pRes = sqlite3Get4byte(ac);
  40167. }
  40168. return rc;
  40169. }
  40170. /*
  40171. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  40172. */
  40173. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  40174. /*
  40175. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  40176. ** on success or an error code is something goes wrong.
  40177. */
  40178. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  40179. char ac[4];
  40180. put32bits(ac, val);
  40181. return sqlite3OsWrite(fd, ac, 4, offset);
  40182. }
  40183. /*
  40184. ** Unlock the database file to level eLock, which must be either NO_LOCK
  40185. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  40186. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  40187. **
  40188. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40189. ** called, do not modify it. See the comment above the #define of
  40190. ** UNKNOWN_LOCK for an explanation of this.
  40191. */
  40192. static int pagerUnlockDb(Pager *pPager, int eLock){
  40193. int rc = SQLITE_OK;
  40194. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  40195. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  40196. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  40197. if( isOpen(pPager->fd) ){
  40198. assert( pPager->eLock>=eLock );
  40199. rc = sqlite3OsUnlock(pPager->fd, eLock);
  40200. if( pPager->eLock!=UNKNOWN_LOCK ){
  40201. pPager->eLock = (u8)eLock;
  40202. }
  40203. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  40204. }
  40205. return rc;
  40206. }
  40207. /*
  40208. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  40209. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  40210. ** Pager.eLock variable to the new locking state.
  40211. **
  40212. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40213. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  40214. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  40215. ** of this.
  40216. */
  40217. static int pagerLockDb(Pager *pPager, int eLock){
  40218. int rc = SQLITE_OK;
  40219. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  40220. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  40221. rc = sqlite3OsLock(pPager->fd, eLock);
  40222. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  40223. pPager->eLock = (u8)eLock;
  40224. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  40225. }
  40226. }
  40227. return rc;
  40228. }
  40229. /*
  40230. ** This function determines whether or not the atomic-write optimization
  40231. ** can be used with this pager. The optimization can be used if:
  40232. **
  40233. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  40234. ** a database page may be written atomically, and
  40235. ** (b) the value returned by OsSectorSize() is less than or equal
  40236. ** to the page size.
  40237. **
  40238. ** The optimization is also always enabled for temporary files. It is
  40239. ** an error to call this function if pPager is opened on an in-memory
  40240. ** database.
  40241. **
  40242. ** If the optimization cannot be used, 0 is returned. If it can be used,
  40243. ** then the value returned is the size of the journal file when it
  40244. ** contains rollback data for exactly one page.
  40245. */
  40246. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40247. static int jrnlBufferSize(Pager *pPager){
  40248. assert( !MEMDB );
  40249. if( !pPager->tempFile ){
  40250. int dc; /* Device characteristics */
  40251. int nSector; /* Sector size */
  40252. int szPage; /* Page size */
  40253. assert( isOpen(pPager->fd) );
  40254. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40255. nSector = pPager->sectorSize;
  40256. szPage = pPager->pageSize;
  40257. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40258. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40259. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  40260. return 0;
  40261. }
  40262. }
  40263. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  40264. }
  40265. #endif
  40266. /*
  40267. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  40268. ** on the cache using a hash function. This is used for testing
  40269. ** and debugging only.
  40270. */
  40271. #ifdef SQLITE_CHECK_PAGES
  40272. /*
  40273. ** Return a 32-bit hash of the page data for pPage.
  40274. */
  40275. static u32 pager_datahash(int nByte, unsigned char *pData){
  40276. u32 hash = 0;
  40277. int i;
  40278. for(i=0; i<nByte; i++){
  40279. hash = (hash*1039) + pData[i];
  40280. }
  40281. return hash;
  40282. }
  40283. static u32 pager_pagehash(PgHdr *pPage){
  40284. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  40285. }
  40286. static void pager_set_pagehash(PgHdr *pPage){
  40287. pPage->pageHash = pager_pagehash(pPage);
  40288. }
  40289. /*
  40290. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  40291. ** is defined, and NDEBUG is not defined, an assert() statement checks
  40292. ** that the page is either dirty or still matches the calculated page-hash.
  40293. */
  40294. #define CHECK_PAGE(x) checkPage(x)
  40295. static void checkPage(PgHdr *pPg){
  40296. Pager *pPager = pPg->pPager;
  40297. assert( pPager->eState!=PAGER_ERROR );
  40298. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  40299. }
  40300. #else
  40301. #define pager_datahash(X,Y) 0
  40302. #define pager_pagehash(X) 0
  40303. #define pager_set_pagehash(X)
  40304. #define CHECK_PAGE(x)
  40305. #endif /* SQLITE_CHECK_PAGES */
  40306. /*
  40307. ** When this is called the journal file for pager pPager must be open.
  40308. ** This function attempts to read a master journal file name from the
  40309. ** end of the file and, if successful, copies it into memory supplied
  40310. ** by the caller. See comments above writeMasterJournal() for the format
  40311. ** used to store a master journal file name at the end of a journal file.
  40312. **
  40313. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  40314. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  40315. ** enough space to write the master journal name). If the master journal
  40316. ** name in the journal is longer than nMaster bytes (including a
  40317. ** nul-terminator), then this is handled as if no master journal name
  40318. ** were present in the journal.
  40319. **
  40320. ** If a master journal file name is present at the end of the journal
  40321. ** file, then it is copied into the buffer pointed to by zMaster. A
  40322. ** nul-terminator byte is appended to the buffer following the master
  40323. ** journal file name.
  40324. **
  40325. ** If it is determined that no master journal file name is present
  40326. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  40327. **
  40328. ** If an error occurs while reading from the journal file, an SQLite
  40329. ** error code is returned.
  40330. */
  40331. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  40332. int rc; /* Return code */
  40333. u32 len; /* Length in bytes of master journal name */
  40334. i64 szJ; /* Total size in bytes of journal file pJrnl */
  40335. u32 cksum; /* MJ checksum value read from journal */
  40336. u32 u; /* Unsigned loop counter */
  40337. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40338. zMaster[0] = '\0';
  40339. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  40340. || szJ<16
  40341. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  40342. || len>=nMaster
  40343. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  40344. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  40345. || memcmp(aMagic, aJournalMagic, 8)
  40346. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  40347. ){
  40348. return rc;
  40349. }
  40350. /* See if the checksum matches the master journal name */
  40351. for(u=0; u<len; u++){
  40352. cksum -= zMaster[u];
  40353. }
  40354. if( cksum ){
  40355. /* If the checksum doesn't add up, then one or more of the disk sectors
  40356. ** containing the master journal filename is corrupted. This means
  40357. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  40358. ** master-journal filename.
  40359. */
  40360. len = 0;
  40361. }
  40362. zMaster[len] = '\0';
  40363. return SQLITE_OK;
  40364. }
  40365. /*
  40366. ** Return the offset of the sector boundary at or immediately
  40367. ** following the value in pPager->journalOff, assuming a sector
  40368. ** size of pPager->sectorSize bytes.
  40369. **
  40370. ** i.e for a sector size of 512:
  40371. **
  40372. ** Pager.journalOff Return value
  40373. ** ---------------------------------------
  40374. ** 0 0
  40375. ** 512 512
  40376. ** 100 512
  40377. ** 2000 2048
  40378. **
  40379. */
  40380. static i64 journalHdrOffset(Pager *pPager){
  40381. i64 offset = 0;
  40382. i64 c = pPager->journalOff;
  40383. if( c ){
  40384. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  40385. }
  40386. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  40387. assert( offset>=c );
  40388. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  40389. return offset;
  40390. }
  40391. /*
  40392. ** The journal file must be open when this function is called.
  40393. **
  40394. ** This function is a no-op if the journal file has not been written to
  40395. ** within the current transaction (i.e. if Pager.journalOff==0).
  40396. **
  40397. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  40398. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  40399. ** zero the 28-byte header at the start of the journal file. In either case,
  40400. ** if the pager is not in no-sync mode, sync the journal file immediately
  40401. ** after writing or truncating it.
  40402. **
  40403. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  40404. ** following the truncation or zeroing described above the size of the
  40405. ** journal file in bytes is larger than this value, then truncate the
  40406. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  40407. ** not need to be synced following this operation.
  40408. **
  40409. ** If an IO error occurs, abandon processing and return the IO error code.
  40410. ** Otherwise, return SQLITE_OK.
  40411. */
  40412. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  40413. int rc = SQLITE_OK; /* Return code */
  40414. assert( isOpen(pPager->jfd) );
  40415. if( pPager->journalOff ){
  40416. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  40417. IOTRACE(("JZEROHDR %p\n", pPager))
  40418. if( doTruncate || iLimit==0 ){
  40419. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40420. }else{
  40421. static const char zeroHdr[28] = {0};
  40422. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  40423. }
  40424. if( rc==SQLITE_OK && !pPager->noSync ){
  40425. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  40426. }
  40427. /* At this point the transaction is committed but the write lock
  40428. ** is still held on the file. If there is a size limit configured for
  40429. ** the persistent journal and the journal file currently consumes more
  40430. ** space than that limit allows for, truncate it now. There is no need
  40431. ** to sync the file following this operation.
  40432. */
  40433. if( rc==SQLITE_OK && iLimit>0 ){
  40434. i64 sz;
  40435. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  40436. if( rc==SQLITE_OK && sz>iLimit ){
  40437. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  40438. }
  40439. }
  40440. }
  40441. return rc;
  40442. }
  40443. /*
  40444. ** The journal file must be open when this routine is called. A journal
  40445. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  40446. ** current location.
  40447. **
  40448. ** The format for the journal header is as follows:
  40449. ** - 8 bytes: Magic identifying journal format.
  40450. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  40451. ** - 4 bytes: Random number used for page hash.
  40452. ** - 4 bytes: Initial database page count.
  40453. ** - 4 bytes: Sector size used by the process that wrote this journal.
  40454. ** - 4 bytes: Database page size.
  40455. **
  40456. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  40457. */
  40458. static int writeJournalHdr(Pager *pPager){
  40459. int rc = SQLITE_OK; /* Return code */
  40460. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  40461. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  40462. u32 nWrite; /* Bytes of header sector written */
  40463. int ii; /* Loop counter */
  40464. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40465. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  40466. nHeader = JOURNAL_HDR_SZ(pPager);
  40467. }
  40468. /* If there are active savepoints and any of them were created
  40469. ** since the most recent journal header was written, update the
  40470. ** PagerSavepoint.iHdrOffset fields now.
  40471. */
  40472. for(ii=0; ii<pPager->nSavepoint; ii++){
  40473. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  40474. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  40475. }
  40476. }
  40477. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  40478. /*
  40479. ** Write the nRec Field - the number of page records that follow this
  40480. ** journal header. Normally, zero is written to this value at this time.
  40481. ** After the records are added to the journal (and the journal synced,
  40482. ** if in full-sync mode), the zero is overwritten with the true number
  40483. ** of records (see syncJournal()).
  40484. **
  40485. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  40486. ** reading the journal this value tells SQLite to assume that the
  40487. ** rest of the journal file contains valid page records. This assumption
  40488. ** is dangerous, as if a failure occurred whilst writing to the journal
  40489. ** file it may contain some garbage data. There are two scenarios
  40490. ** where this risk can be ignored:
  40491. **
  40492. ** * When the pager is in no-sync mode. Corruption can follow a
  40493. ** power failure in this case anyway.
  40494. **
  40495. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  40496. ** that garbage data is never appended to the journal file.
  40497. */
  40498. assert( isOpen(pPager->fd) || pPager->noSync );
  40499. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  40500. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  40501. ){
  40502. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  40503. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  40504. }else{
  40505. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  40506. }
  40507. /* The random check-hash initializer */
  40508. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  40509. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  40510. /* The initial database size */
  40511. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  40512. /* The assumed sector size for this process */
  40513. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  40514. /* The page size */
  40515. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  40516. /* Initializing the tail of the buffer is not necessary. Everything
  40517. ** works find if the following memset() is omitted. But initializing
  40518. ** the memory prevents valgrind from complaining, so we are willing to
  40519. ** take the performance hit.
  40520. */
  40521. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  40522. nHeader-(sizeof(aJournalMagic)+20));
  40523. /* In theory, it is only necessary to write the 28 bytes that the
  40524. ** journal header consumes to the journal file here. Then increment the
  40525. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  40526. ** record is written to the following sector (leaving a gap in the file
  40527. ** that will be implicitly filled in by the OS).
  40528. **
  40529. ** However it has been discovered that on some systems this pattern can
  40530. ** be significantly slower than contiguously writing data to the file,
  40531. ** even if that means explicitly writing data to the block of
  40532. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  40533. ** is done.
  40534. **
  40535. ** The loop is required here in case the sector-size is larger than the
  40536. ** database page size. Since the zHeader buffer is only Pager.pageSize
  40537. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  40538. ** to populate the entire journal header sector.
  40539. */
  40540. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  40541. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  40542. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  40543. assert( pPager->journalHdr <= pPager->journalOff );
  40544. pPager->journalOff += nHeader;
  40545. }
  40546. return rc;
  40547. }
  40548. /*
  40549. ** The journal file must be open when this is called. A journal header file
  40550. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  40551. ** file. The current location in the journal file is given by
  40552. ** pPager->journalOff. See comments above function writeJournalHdr() for
  40553. ** a description of the journal header format.
  40554. **
  40555. ** If the header is read successfully, *pNRec is set to the number of
  40556. ** page records following this header and *pDbSize is set to the size of the
  40557. ** database before the transaction began, in pages. Also, pPager->cksumInit
  40558. ** is set to the value read from the journal header. SQLITE_OK is returned
  40559. ** in this case.
  40560. **
  40561. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  40562. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  40563. ** cannot be read from the journal file an error code is returned.
  40564. */
  40565. static int readJournalHdr(
  40566. Pager *pPager, /* Pager object */
  40567. int isHot,
  40568. i64 journalSize, /* Size of the open journal file in bytes */
  40569. u32 *pNRec, /* OUT: Value read from the nRec field */
  40570. u32 *pDbSize /* OUT: Value of original database size field */
  40571. ){
  40572. int rc; /* Return code */
  40573. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40574. i64 iHdrOff; /* Offset of journal header being read */
  40575. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40576. /* Advance Pager.journalOff to the start of the next sector. If the
  40577. ** journal file is too small for there to be a header stored at this
  40578. ** point, return SQLITE_DONE.
  40579. */
  40580. pPager->journalOff = journalHdrOffset(pPager);
  40581. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  40582. return SQLITE_DONE;
  40583. }
  40584. iHdrOff = pPager->journalOff;
  40585. /* Read in the first 8 bytes of the journal header. If they do not match
  40586. ** the magic string found at the start of each journal header, return
  40587. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  40588. ** proceed.
  40589. */
  40590. if( isHot || iHdrOff!=pPager->journalHdr ){
  40591. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  40592. if( rc ){
  40593. return rc;
  40594. }
  40595. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  40596. return SQLITE_DONE;
  40597. }
  40598. }
  40599. /* Read the first three 32-bit fields of the journal header: The nRec
  40600. ** field, the checksum-initializer and the database size at the start
  40601. ** of the transaction. Return an error code if anything goes wrong.
  40602. */
  40603. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  40604. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  40605. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  40606. ){
  40607. return rc;
  40608. }
  40609. if( pPager->journalOff==0 ){
  40610. u32 iPageSize; /* Page-size field of journal header */
  40611. u32 iSectorSize; /* Sector-size field of journal header */
  40612. /* Read the page-size and sector-size journal header fields. */
  40613. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  40614. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  40615. ){
  40616. return rc;
  40617. }
  40618. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  40619. ** journal header to zero. In this case, assume that the Pager.pageSize
  40620. ** variable is already set to the correct page size.
  40621. */
  40622. if( iPageSize==0 ){
  40623. iPageSize = pPager->pageSize;
  40624. }
  40625. /* Check that the values read from the page-size and sector-size fields
  40626. ** are within range. To be 'in range', both values need to be a power
  40627. ** of two greater than or equal to 512 or 32, and not greater than their
  40628. ** respective compile time maximum limits.
  40629. */
  40630. if( iPageSize<512 || iSectorSize<32
  40631. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  40632. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  40633. ){
  40634. /* If the either the page-size or sector-size in the journal-header is
  40635. ** invalid, then the process that wrote the journal-header must have
  40636. ** crashed before the header was synced. In this case stop reading
  40637. ** the journal file here.
  40638. */
  40639. return SQLITE_DONE;
  40640. }
  40641. /* Update the page-size to match the value read from the journal.
  40642. ** Use a testcase() macro to make sure that malloc failure within
  40643. ** PagerSetPagesize() is tested.
  40644. */
  40645. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  40646. testcase( rc!=SQLITE_OK );
  40647. /* Update the assumed sector-size to match the value used by
  40648. ** the process that created this journal. If this journal was
  40649. ** created by a process other than this one, then this routine
  40650. ** is being called from within pager_playback(). The local value
  40651. ** of Pager.sectorSize is restored at the end of that routine.
  40652. */
  40653. pPager->sectorSize = iSectorSize;
  40654. }
  40655. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  40656. return rc;
  40657. }
  40658. /*
  40659. ** Write the supplied master journal name into the journal file for pager
  40660. ** pPager at the current location. The master journal name must be the last
  40661. ** thing written to a journal file. If the pager is in full-sync mode, the
  40662. ** journal file descriptor is advanced to the next sector boundary before
  40663. ** anything is written. The format is:
  40664. **
  40665. ** + 4 bytes: PAGER_MJ_PGNO.
  40666. ** + N bytes: Master journal filename in utf-8.
  40667. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  40668. ** + 4 bytes: Master journal name checksum.
  40669. ** + 8 bytes: aJournalMagic[].
  40670. **
  40671. ** The master journal page checksum is the sum of the bytes in the master
  40672. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  40673. **
  40674. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  40675. ** this call is a no-op.
  40676. */
  40677. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  40678. int rc; /* Return code */
  40679. int nMaster; /* Length of string zMaster */
  40680. i64 iHdrOff; /* Offset of header in journal file */
  40681. i64 jrnlSize; /* Size of journal file on disk */
  40682. u32 cksum = 0; /* Checksum of string zMaster */
  40683. assert( pPager->setMaster==0 );
  40684. assert( !pagerUseWal(pPager) );
  40685. if( !zMaster
  40686. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40687. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  40688. ){
  40689. return SQLITE_OK;
  40690. }
  40691. pPager->setMaster = 1;
  40692. assert( isOpen(pPager->jfd) );
  40693. assert( pPager->journalHdr <= pPager->journalOff );
  40694. /* Calculate the length in bytes and the checksum of zMaster */
  40695. for(nMaster=0; zMaster[nMaster]; nMaster++){
  40696. cksum += zMaster[nMaster];
  40697. }
  40698. /* If in full-sync mode, advance to the next disk sector before writing
  40699. ** the master journal name. This is in case the previous page written to
  40700. ** the journal has already been synced.
  40701. */
  40702. if( pPager->fullSync ){
  40703. pPager->journalOff = journalHdrOffset(pPager);
  40704. }
  40705. iHdrOff = pPager->journalOff;
  40706. /* Write the master journal data to the end of the journal file. If
  40707. ** an error occurs, return the error code to the caller.
  40708. */
  40709. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  40710. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  40711. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  40712. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  40713. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  40714. ){
  40715. return rc;
  40716. }
  40717. pPager->journalOff += (nMaster+20);
  40718. /* If the pager is in peristent-journal mode, then the physical
  40719. ** journal-file may extend past the end of the master-journal name
  40720. ** and 8 bytes of magic data just written to the file. This is
  40721. ** dangerous because the code to rollback a hot-journal file
  40722. ** will not be able to find the master-journal name to determine
  40723. ** whether or not the journal is hot.
  40724. **
  40725. ** Easiest thing to do in this scenario is to truncate the journal
  40726. ** file to the required size.
  40727. */
  40728. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  40729. && jrnlSize>pPager->journalOff
  40730. ){
  40731. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  40732. }
  40733. return rc;
  40734. }
  40735. /*
  40736. ** Find a page in the hash table given its page number. Return
  40737. ** a pointer to the page or NULL if the requested page is not
  40738. ** already in memory.
  40739. */
  40740. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  40741. PgHdr *p; /* Return value */
  40742. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  40743. ** fail, since no attempt to allocate dynamic memory will be made.
  40744. */
  40745. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  40746. return p;
  40747. }
  40748. /*
  40749. ** Discard the entire contents of the in-memory page-cache.
  40750. */
  40751. static void pager_reset(Pager *pPager){
  40752. sqlite3BackupRestart(pPager->pBackup);
  40753. sqlite3PcacheClear(pPager->pPCache);
  40754. }
  40755. /*
  40756. ** Free all structures in the Pager.aSavepoint[] array and set both
  40757. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  40758. ** if it is open and the pager is not in exclusive mode.
  40759. */
  40760. static void releaseAllSavepoints(Pager *pPager){
  40761. int ii; /* Iterator for looping through Pager.aSavepoint */
  40762. for(ii=0; ii<pPager->nSavepoint; ii++){
  40763. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  40764. }
  40765. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  40766. sqlite3OsClose(pPager->sjfd);
  40767. }
  40768. sqlite3_free(pPager->aSavepoint);
  40769. pPager->aSavepoint = 0;
  40770. pPager->nSavepoint = 0;
  40771. pPager->nSubRec = 0;
  40772. }
  40773. /*
  40774. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  40775. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  40776. ** or SQLITE_NOMEM if a malloc failure occurs.
  40777. */
  40778. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  40779. int ii; /* Loop counter */
  40780. int rc = SQLITE_OK; /* Result code */
  40781. for(ii=0; ii<pPager->nSavepoint; ii++){
  40782. PagerSavepoint *p = &pPager->aSavepoint[ii];
  40783. if( pgno<=p->nOrig ){
  40784. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  40785. testcase( rc==SQLITE_NOMEM );
  40786. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  40787. }
  40788. }
  40789. return rc;
  40790. }
  40791. /*
  40792. ** This function is a no-op if the pager is in exclusive mode and not
  40793. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  40794. ** state.
  40795. **
  40796. ** If the pager is not in exclusive-access mode, the database file is
  40797. ** completely unlocked. If the file is unlocked and the file-system does
  40798. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  40799. ** closed (if it is open).
  40800. **
  40801. ** If the pager is in ERROR state when this function is called, the
  40802. ** contents of the pager cache are discarded before switching back to
  40803. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  40804. ** or not, any journal file left in the file-system will be treated
  40805. ** as a hot-journal and rolled back the next time a read-transaction
  40806. ** is opened (by this or by any other connection).
  40807. */
  40808. static void pager_unlock(Pager *pPager){
  40809. assert( pPager->eState==PAGER_READER
  40810. || pPager->eState==PAGER_OPEN
  40811. || pPager->eState==PAGER_ERROR
  40812. );
  40813. sqlite3BitvecDestroy(pPager->pInJournal);
  40814. pPager->pInJournal = 0;
  40815. releaseAllSavepoints(pPager);
  40816. if( pagerUseWal(pPager) ){
  40817. assert( !isOpen(pPager->jfd) );
  40818. sqlite3WalEndReadTransaction(pPager->pWal);
  40819. pPager->eState = PAGER_OPEN;
  40820. }else if( !pPager->exclusiveMode ){
  40821. int rc; /* Error code returned by pagerUnlockDb() */
  40822. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  40823. /* If the operating system support deletion of open files, then
  40824. ** close the journal file when dropping the database lock. Otherwise
  40825. ** another connection with journal_mode=delete might delete the file
  40826. ** out from under us.
  40827. */
  40828. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  40829. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  40830. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  40831. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  40832. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  40833. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  40834. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  40835. || 1!=(pPager->journalMode & 5)
  40836. ){
  40837. sqlite3OsClose(pPager->jfd);
  40838. }
  40839. /* If the pager is in the ERROR state and the call to unlock the database
  40840. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  40841. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  40842. ** is necessary.
  40843. */
  40844. rc = pagerUnlockDb(pPager, NO_LOCK);
  40845. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  40846. pPager->eLock = UNKNOWN_LOCK;
  40847. }
  40848. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  40849. ** without clearing the error code. This is intentional - the error
  40850. ** code is cleared and the cache reset in the block below.
  40851. */
  40852. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  40853. pPager->changeCountDone = 0;
  40854. pPager->eState = PAGER_OPEN;
  40855. }
  40856. /* If Pager.errCode is set, the contents of the pager cache cannot be
  40857. ** trusted. Now that there are no outstanding references to the pager,
  40858. ** it can safely move back to PAGER_OPEN state. This happens in both
  40859. ** normal and exclusive-locking mode.
  40860. */
  40861. if( pPager->errCode ){
  40862. assert( !MEMDB );
  40863. pager_reset(pPager);
  40864. pPager->changeCountDone = pPager->tempFile;
  40865. pPager->eState = PAGER_OPEN;
  40866. pPager->errCode = SQLITE_OK;
  40867. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  40868. }
  40869. pPager->journalOff = 0;
  40870. pPager->journalHdr = 0;
  40871. pPager->setMaster = 0;
  40872. }
  40873. /*
  40874. ** This function is called whenever an IOERR or FULL error that requires
  40875. ** the pager to transition into the ERROR state may ahve occurred.
  40876. ** The first argument is a pointer to the pager structure, the second
  40877. ** the error-code about to be returned by a pager API function. The
  40878. ** value returned is a copy of the second argument to this function.
  40879. **
  40880. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  40881. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  40882. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  40883. ** all major API calls on the Pager will immediately return Pager.errCode.
  40884. **
  40885. ** The ERROR state indicates that the contents of the pager-cache
  40886. ** cannot be trusted. This state can be cleared by completely discarding
  40887. ** the contents of the pager-cache. If a transaction was active when
  40888. ** the persistent error occurred, then the rollback journal may need
  40889. ** to be replayed to restore the contents of the database file (as if
  40890. ** it were a hot-journal).
  40891. */
  40892. static int pager_error(Pager *pPager, int rc){
  40893. int rc2 = rc & 0xff;
  40894. assert( rc==SQLITE_OK || !MEMDB );
  40895. assert(
  40896. pPager->errCode==SQLITE_FULL ||
  40897. pPager->errCode==SQLITE_OK ||
  40898. (pPager->errCode & 0xff)==SQLITE_IOERR
  40899. );
  40900. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  40901. pPager->errCode = rc;
  40902. pPager->eState = PAGER_ERROR;
  40903. }
  40904. return rc;
  40905. }
  40906. static int pager_truncate(Pager *pPager, Pgno nPage);
  40907. /*
  40908. ** This routine ends a transaction. A transaction is usually ended by
  40909. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  40910. ** after rollback of a hot-journal, or if an error occurs while opening
  40911. ** the journal file or writing the very first journal-header of a
  40912. ** database transaction.
  40913. **
  40914. ** This routine is never called in PAGER_ERROR state. If it is called
  40915. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  40916. ** exclusive than a RESERVED lock, it is a no-op.
  40917. **
  40918. ** Otherwise, any active savepoints are released.
  40919. **
  40920. ** If the journal file is open, then it is "finalized". Once a journal
  40921. ** file has been finalized it is not possible to use it to roll back a
  40922. ** transaction. Nor will it be considered to be a hot-journal by this
  40923. ** or any other database connection. Exactly how a journal is finalized
  40924. ** depends on whether or not the pager is running in exclusive mode and
  40925. ** the current journal-mode (Pager.journalMode value), as follows:
  40926. **
  40927. ** journalMode==MEMORY
  40928. ** Journal file descriptor is simply closed. This destroys an
  40929. ** in-memory journal.
  40930. **
  40931. ** journalMode==TRUNCATE
  40932. ** Journal file is truncated to zero bytes in size.
  40933. **
  40934. ** journalMode==PERSIST
  40935. ** The first 28 bytes of the journal file are zeroed. This invalidates
  40936. ** the first journal header in the file, and hence the entire journal
  40937. ** file. An invalid journal file cannot be rolled back.
  40938. **
  40939. ** journalMode==DELETE
  40940. ** The journal file is closed and deleted using sqlite3OsDelete().
  40941. **
  40942. ** If the pager is running in exclusive mode, this method of finalizing
  40943. ** the journal file is never used. Instead, if the journalMode is
  40944. ** DELETE and the pager is in exclusive mode, the method described under
  40945. ** journalMode==PERSIST is used instead.
  40946. **
  40947. ** After the journal is finalized, the pager moves to PAGER_READER state.
  40948. ** If running in non-exclusive rollback mode, the lock on the file is
  40949. ** downgraded to a SHARED_LOCK.
  40950. **
  40951. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  40952. ** any of the IO operations to finalize the journal file or unlock the
  40953. ** database then the IO error code is returned to the user. If the
  40954. ** operation to finalize the journal file fails, then the code still
  40955. ** tries to unlock the database file if not in exclusive mode. If the
  40956. ** unlock operation fails as well, then the first error code related
  40957. ** to the first error encountered (the journal finalization one) is
  40958. ** returned.
  40959. */
  40960. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  40961. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  40962. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  40963. /* Do nothing if the pager does not have an open write transaction
  40964. ** or at least a RESERVED lock. This function may be called when there
  40965. ** is no write-transaction active but a RESERVED or greater lock is
  40966. ** held under two circumstances:
  40967. **
  40968. ** 1. After a successful hot-journal rollback, it is called with
  40969. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  40970. **
  40971. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  40972. ** lock switches back to locking_mode=normal and then executes a
  40973. ** read-transaction, this function is called with eState==PAGER_READER
  40974. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  40975. */
  40976. assert( assert_pager_state(pPager) );
  40977. assert( pPager->eState!=PAGER_ERROR );
  40978. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  40979. return SQLITE_OK;
  40980. }
  40981. releaseAllSavepoints(pPager);
  40982. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  40983. if( isOpen(pPager->jfd) ){
  40984. assert( !pagerUseWal(pPager) );
  40985. /* Finalize the journal file. */
  40986. if( sqlite3IsMemJournal(pPager->jfd) ){
  40987. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  40988. sqlite3OsClose(pPager->jfd);
  40989. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  40990. if( pPager->journalOff==0 ){
  40991. rc = SQLITE_OK;
  40992. }else{
  40993. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40994. }
  40995. pPager->journalOff = 0;
  40996. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40997. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  40998. ){
  40999. rc = zeroJournalHdr(pPager, hasMaster);
  41000. pPager->journalOff = 0;
  41001. }else{
  41002. /* This branch may be executed with Pager.journalMode==MEMORY if
  41003. ** a hot-journal was just rolled back. In this case the journal
  41004. ** file should be closed and deleted. If this connection writes to
  41005. ** the database file, it will do so using an in-memory journal.
  41006. */
  41007. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  41008. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  41009. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  41010. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  41011. );
  41012. sqlite3OsClose(pPager->jfd);
  41013. if( bDelete ){
  41014. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  41015. }
  41016. }
  41017. }
  41018. #ifdef SQLITE_CHECK_PAGES
  41019. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  41020. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  41021. PgHdr *p = pager_lookup(pPager, 1);
  41022. if( p ){
  41023. p->pageHash = 0;
  41024. sqlite3PagerUnref(p);
  41025. }
  41026. }
  41027. #endif
  41028. sqlite3BitvecDestroy(pPager->pInJournal);
  41029. pPager->pInJournal = 0;
  41030. pPager->nRec = 0;
  41031. sqlite3PcacheCleanAll(pPager->pPCache);
  41032. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  41033. if( pagerUseWal(pPager) ){
  41034. /* Drop the WAL write-lock, if any. Also, if the connection was in
  41035. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  41036. ** lock held on the database file.
  41037. */
  41038. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  41039. assert( rc2==SQLITE_OK );
  41040. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  41041. /* This branch is taken when committing a transaction in rollback-journal
  41042. ** mode if the database file on disk is larger than the database image.
  41043. ** At this point the journal has been finalized and the transaction
  41044. ** successfully committed, but the EXCLUSIVE lock is still held on the
  41045. ** file. So it is safe to truncate the database file to its minimum
  41046. ** required size. */
  41047. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41048. rc = pager_truncate(pPager, pPager->dbSize);
  41049. }
  41050. if( !pPager->exclusiveMode
  41051. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  41052. ){
  41053. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  41054. pPager->changeCountDone = 0;
  41055. }
  41056. pPager->eState = PAGER_READER;
  41057. pPager->setMaster = 0;
  41058. return (rc==SQLITE_OK?rc2:rc);
  41059. }
  41060. /*
  41061. ** Execute a rollback if a transaction is active and unlock the
  41062. ** database file.
  41063. **
  41064. ** If the pager has already entered the ERROR state, do not attempt
  41065. ** the rollback at this time. Instead, pager_unlock() is called. The
  41066. ** call to pager_unlock() will discard all in-memory pages, unlock
  41067. ** the database file and move the pager back to OPEN state. If this
  41068. ** means that there is a hot-journal left in the file-system, the next
  41069. ** connection to obtain a shared lock on the pager (which may be this one)
  41070. ** will roll it back.
  41071. **
  41072. ** If the pager has not already entered the ERROR state, but an IO or
  41073. ** malloc error occurs during a rollback, then this will itself cause
  41074. ** the pager to enter the ERROR state. Which will be cleared by the
  41075. ** call to pager_unlock(), as described above.
  41076. */
  41077. static void pagerUnlockAndRollback(Pager *pPager){
  41078. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  41079. assert( assert_pager_state(pPager) );
  41080. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  41081. sqlite3BeginBenignMalloc();
  41082. sqlite3PagerRollback(pPager);
  41083. sqlite3EndBenignMalloc();
  41084. }else if( !pPager->exclusiveMode ){
  41085. assert( pPager->eState==PAGER_READER );
  41086. pager_end_transaction(pPager, 0, 0);
  41087. }
  41088. }
  41089. pager_unlock(pPager);
  41090. }
  41091. /*
  41092. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  41093. ** of data. Compute and return a checksum based ont the contents of the
  41094. ** page of data and the current value of pPager->cksumInit.
  41095. **
  41096. ** This is not a real checksum. It is really just the sum of the
  41097. ** random initial value (pPager->cksumInit) and every 200th byte
  41098. ** of the page data, starting with byte offset (pPager->pageSize%200).
  41099. ** Each byte is interpreted as an 8-bit unsigned integer.
  41100. **
  41101. ** Changing the formula used to compute this checksum results in an
  41102. ** incompatible journal file format.
  41103. **
  41104. ** If journal corruption occurs due to a power failure, the most likely
  41105. ** scenario is that one end or the other of the record will be changed.
  41106. ** It is much less likely that the two ends of the journal record will be
  41107. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  41108. ** though fast and simple, catches the mostly likely kind of corruption.
  41109. */
  41110. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  41111. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  41112. int i = pPager->pageSize-200; /* Loop counter */
  41113. while( i>0 ){
  41114. cksum += aData[i];
  41115. i -= 200;
  41116. }
  41117. return cksum;
  41118. }
  41119. /*
  41120. ** Report the current page size and number of reserved bytes back
  41121. ** to the codec.
  41122. */
  41123. #ifdef SQLITE_HAS_CODEC
  41124. static void pagerReportSize(Pager *pPager){
  41125. if( pPager->xCodecSizeChng ){
  41126. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  41127. (int)pPager->nReserve);
  41128. }
  41129. }
  41130. #else
  41131. # define pagerReportSize(X) /* No-op if we do not support a codec */
  41132. #endif
  41133. /*
  41134. ** Read a single page from either the journal file (if isMainJrnl==1) or
  41135. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  41136. ** The page begins at offset *pOffset into the file. The *pOffset
  41137. ** value is increased to the start of the next page in the journal.
  41138. **
  41139. ** The main rollback journal uses checksums - the statement journal does
  41140. ** not.
  41141. **
  41142. ** If the page number of the page record read from the (sub-)journal file
  41143. ** is greater than the current value of Pager.dbSize, then playback is
  41144. ** skipped and SQLITE_OK is returned.
  41145. **
  41146. ** If pDone is not NULL, then it is a record of pages that have already
  41147. ** been played back. If the page at *pOffset has already been played back
  41148. ** (if the corresponding pDone bit is set) then skip the playback.
  41149. ** Make sure the pDone bit corresponding to the *pOffset page is set
  41150. ** prior to returning.
  41151. **
  41152. ** If the page record is successfully read from the (sub-)journal file
  41153. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  41154. ** while reading the record from the (sub-)journal file or while writing
  41155. ** to the database file, then the IO error code is returned. If data
  41156. ** is successfully read from the (sub-)journal file but appears to be
  41157. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  41158. ** two circumstances:
  41159. **
  41160. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  41161. ** * If the record is being rolled back from the main journal file
  41162. ** and the checksum field does not match the record content.
  41163. **
  41164. ** Neither of these two scenarios are possible during a savepoint rollback.
  41165. **
  41166. ** If this is a savepoint rollback, then memory may have to be dynamically
  41167. ** allocated by this function. If this is the case and an allocation fails,
  41168. ** SQLITE_NOMEM is returned.
  41169. */
  41170. static int pager_playback_one_page(
  41171. Pager *pPager, /* The pager being played back */
  41172. i64 *pOffset, /* Offset of record to playback */
  41173. Bitvec *pDone, /* Bitvec of pages already played back */
  41174. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  41175. int isSavepnt /* True for a savepoint rollback */
  41176. ){
  41177. int rc;
  41178. PgHdr *pPg; /* An existing page in the cache */
  41179. Pgno pgno; /* The page number of a page in journal */
  41180. u32 cksum; /* Checksum used for sanity checking */
  41181. char *aData; /* Temporary storage for the page */
  41182. sqlite3_file *jfd; /* The file descriptor for the journal file */
  41183. int isSynced; /* True if journal page is synced */
  41184. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  41185. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  41186. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  41187. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  41188. aData = pPager->pTmpSpace;
  41189. assert( aData ); /* Temp storage must have already been allocated */
  41190. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  41191. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  41192. ** or savepoint rollback done at the request of the caller) or this is
  41193. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  41194. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  41195. ** only reads from the main journal, not the sub-journal.
  41196. */
  41197. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  41198. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  41199. );
  41200. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  41201. /* Read the page number and page data from the journal or sub-journal
  41202. ** file. Return an error code to the caller if an IO error occurs.
  41203. */
  41204. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  41205. rc = read32bits(jfd, *pOffset, &pgno);
  41206. if( rc!=SQLITE_OK ) return rc;
  41207. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  41208. if( rc!=SQLITE_OK ) return rc;
  41209. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  41210. /* Sanity checking on the page. This is more important that I originally
  41211. ** thought. If a power failure occurs while the journal is being written,
  41212. ** it could cause invalid data to be written into the journal. We need to
  41213. ** detect this invalid data (with high probability) and ignore it.
  41214. */
  41215. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  41216. assert( !isSavepnt );
  41217. return SQLITE_DONE;
  41218. }
  41219. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  41220. return SQLITE_OK;
  41221. }
  41222. if( isMainJrnl ){
  41223. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  41224. if( rc ) return rc;
  41225. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  41226. return SQLITE_DONE;
  41227. }
  41228. }
  41229. /* If this page has already been played by before during the current
  41230. ** rollback, then don't bother to play it back again.
  41231. */
  41232. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  41233. return rc;
  41234. }
  41235. /* When playing back page 1, restore the nReserve setting
  41236. */
  41237. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  41238. pPager->nReserve = ((u8*)aData)[20];
  41239. pagerReportSize(pPager);
  41240. }
  41241. /* If the pager is in CACHEMOD state, then there must be a copy of this
  41242. ** page in the pager cache. In this case just update the pager cache,
  41243. ** not the database file. The page is left marked dirty in this case.
  41244. **
  41245. ** An exception to the above rule: If the database is in no-sync mode
  41246. ** and a page is moved during an incremental vacuum then the page may
  41247. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  41248. ** during a Movepage() call, then the page may not be in the cache
  41249. ** either. So the condition described in the above paragraph is not
  41250. ** assert()able.
  41251. **
  41252. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  41253. ** pager cache if it exists and the main file. The page is then marked
  41254. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  41255. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  41256. ** if the pager is in OPEN state.
  41257. **
  41258. ** Ticket #1171: The statement journal might contain page content that is
  41259. ** different from the page content at the start of the transaction.
  41260. ** This occurs when a page is changed prior to the start of a statement
  41261. ** then changed again within the statement. When rolling back such a
  41262. ** statement we must not write to the original database unless we know
  41263. ** for certain that original page contents are synced into the main rollback
  41264. ** journal. Otherwise, a power loss might leave modified data in the
  41265. ** database file without an entry in the rollback journal that can
  41266. ** restore the database to its original form. Two conditions must be
  41267. ** met before writing to the database files. (1) the database must be
  41268. ** locked. (2) we know that the original page content is fully synced
  41269. ** in the main journal either because the page is not in cache or else
  41270. ** the page is marked as needSync==0.
  41271. **
  41272. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  41273. ** is possible to fail a statement on a database that does not yet exist.
  41274. ** Do not attempt to write if database file has never been opened.
  41275. */
  41276. if( pagerUseWal(pPager) ){
  41277. pPg = 0;
  41278. }else{
  41279. pPg = pager_lookup(pPager, pgno);
  41280. }
  41281. assert( pPg || !MEMDB );
  41282. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  41283. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  41284. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  41285. (isMainJrnl?"main-journal":"sub-journal")
  41286. ));
  41287. if( isMainJrnl ){
  41288. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  41289. }else{
  41290. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  41291. }
  41292. if( isOpen(pPager->fd)
  41293. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41294. && isSynced
  41295. ){
  41296. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  41297. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  41298. assert( !pagerUseWal(pPager) );
  41299. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  41300. if( pgno>pPager->dbFileSize ){
  41301. pPager->dbFileSize = pgno;
  41302. }
  41303. if( pPager->pBackup ){
  41304. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  41305. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  41306. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  41307. }
  41308. }else if( !isMainJrnl && pPg==0 ){
  41309. /* If this is a rollback of a savepoint and data was not written to
  41310. ** the database and the page is not in-memory, there is a potential
  41311. ** problem. When the page is next fetched by the b-tree layer, it
  41312. ** will be read from the database file, which may or may not be
  41313. ** current.
  41314. **
  41315. ** There are a couple of different ways this can happen. All are quite
  41316. ** obscure. When running in synchronous mode, this can only happen
  41317. ** if the page is on the free-list at the start of the transaction, then
  41318. ** populated, then moved using sqlite3PagerMovepage().
  41319. **
  41320. ** The solution is to add an in-memory page to the cache containing
  41321. ** the data just read from the sub-journal. Mark the page as dirty
  41322. ** and if the pager requires a journal-sync, then mark the page as
  41323. ** requiring a journal-sync before it is written.
  41324. */
  41325. assert( isSavepnt );
  41326. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  41327. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  41328. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  41329. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  41330. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  41331. if( rc!=SQLITE_OK ) return rc;
  41332. pPg->flags &= ~PGHDR_NEED_READ;
  41333. sqlite3PcacheMakeDirty(pPg);
  41334. }
  41335. if( pPg ){
  41336. /* No page should ever be explicitly rolled back that is in use, except
  41337. ** for page 1 which is held in use in order to keep the lock on the
  41338. ** database active. However such a page may be rolled back as a result
  41339. ** of an internal error resulting in an automatic call to
  41340. ** sqlite3PagerRollback().
  41341. */
  41342. void *pData;
  41343. pData = pPg->pData;
  41344. memcpy(pData, (u8*)aData, pPager->pageSize);
  41345. pPager->xReiniter(pPg);
  41346. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  41347. /* If the contents of this page were just restored from the main
  41348. ** journal file, then its content must be as they were when the
  41349. ** transaction was first opened. In this case we can mark the page
  41350. ** as clean, since there will be no need to write it out to the
  41351. ** database.
  41352. **
  41353. ** There is one exception to this rule. If the page is being rolled
  41354. ** back as part of a savepoint (or statement) rollback from an
  41355. ** unsynced portion of the main journal file, then it is not safe
  41356. ** to mark the page as clean. This is because marking the page as
  41357. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  41358. ** already in the journal file (recorded in Pager.pInJournal) and
  41359. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  41360. ** again within this transaction, it will be marked as dirty but
  41361. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  41362. ** be written out into the database file before its journal file
  41363. ** segment is synced. If a crash occurs during or following this,
  41364. ** database corruption may ensue.
  41365. */
  41366. assert( !pagerUseWal(pPager) );
  41367. sqlite3PcacheMakeClean(pPg);
  41368. }
  41369. pager_set_pagehash(pPg);
  41370. /* If this was page 1, then restore the value of Pager.dbFileVers.
  41371. ** Do this before any decoding. */
  41372. if( pgno==1 ){
  41373. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  41374. }
  41375. /* Decode the page just read from disk */
  41376. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  41377. sqlite3PcacheRelease(pPg);
  41378. }
  41379. return rc;
  41380. }
  41381. /*
  41382. ** Parameter zMaster is the name of a master journal file. A single journal
  41383. ** file that referred to the master journal file has just been rolled back.
  41384. ** This routine checks if it is possible to delete the master journal file,
  41385. ** and does so if it is.
  41386. **
  41387. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  41388. ** available for use within this function.
  41389. **
  41390. ** When a master journal file is created, it is populated with the names
  41391. ** of all of its child journals, one after another, formatted as utf-8
  41392. ** encoded text. The end of each child journal file is marked with a
  41393. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  41394. ** file for a transaction involving two databases might be:
  41395. **
  41396. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  41397. **
  41398. ** A master journal file may only be deleted once all of its child
  41399. ** journals have been rolled back.
  41400. **
  41401. ** This function reads the contents of the master-journal file into
  41402. ** memory and loops through each of the child journal names. For
  41403. ** each child journal, it checks if:
  41404. **
  41405. ** * if the child journal exists, and if so
  41406. ** * if the child journal contains a reference to master journal
  41407. ** file zMaster
  41408. **
  41409. ** If a child journal can be found that matches both of the criteria
  41410. ** above, this function returns without doing anything. Otherwise, if
  41411. ** no such child journal can be found, file zMaster is deleted from
  41412. ** the file-system using sqlite3OsDelete().
  41413. **
  41414. ** If an IO error within this function, an error code is returned. This
  41415. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  41416. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  41417. ** occur, SQLITE_OK is returned.
  41418. **
  41419. ** TODO: This function allocates a single block of memory to load
  41420. ** the entire contents of the master journal file. This could be
  41421. ** a couple of kilobytes or so - potentially larger than the page
  41422. ** size.
  41423. */
  41424. static int pager_delmaster(Pager *pPager, const char *zMaster){
  41425. sqlite3_vfs *pVfs = pPager->pVfs;
  41426. int rc; /* Return code */
  41427. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  41428. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  41429. char *zMasterJournal = 0; /* Contents of master journal file */
  41430. i64 nMasterJournal; /* Size of master journal file */
  41431. char *zJournal; /* Pointer to one journal within MJ file */
  41432. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  41433. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  41434. /* Allocate space for both the pJournal and pMaster file descriptors.
  41435. ** If successful, open the master journal file for reading.
  41436. */
  41437. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  41438. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  41439. if( !pMaster ){
  41440. rc = SQLITE_NOMEM;
  41441. }else{
  41442. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  41443. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  41444. }
  41445. if( rc!=SQLITE_OK ) goto delmaster_out;
  41446. /* Load the entire master journal file into space obtained from
  41447. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  41448. ** sufficient space (in zMasterPtr) to hold the names of master
  41449. ** journal files extracted from regular rollback-journals.
  41450. */
  41451. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  41452. if( rc!=SQLITE_OK ) goto delmaster_out;
  41453. nMasterPtr = pVfs->mxPathname+1;
  41454. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  41455. if( !zMasterJournal ){
  41456. rc = SQLITE_NOMEM;
  41457. goto delmaster_out;
  41458. }
  41459. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  41460. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  41461. if( rc!=SQLITE_OK ) goto delmaster_out;
  41462. zMasterJournal[nMasterJournal] = 0;
  41463. zJournal = zMasterJournal;
  41464. while( (zJournal-zMasterJournal)<nMasterJournal ){
  41465. int exists;
  41466. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  41467. if( rc!=SQLITE_OK ){
  41468. goto delmaster_out;
  41469. }
  41470. if( exists ){
  41471. /* One of the journals pointed to by the master journal exists.
  41472. ** Open it and check if it points at the master journal. If
  41473. ** so, return without deleting the master journal file.
  41474. */
  41475. int c;
  41476. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  41477. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  41478. if( rc!=SQLITE_OK ){
  41479. goto delmaster_out;
  41480. }
  41481. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  41482. sqlite3OsClose(pJournal);
  41483. if( rc!=SQLITE_OK ){
  41484. goto delmaster_out;
  41485. }
  41486. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  41487. if( c ){
  41488. /* We have a match. Do not delete the master journal file. */
  41489. goto delmaster_out;
  41490. }
  41491. }
  41492. zJournal += (sqlite3Strlen30(zJournal)+1);
  41493. }
  41494. sqlite3OsClose(pMaster);
  41495. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  41496. delmaster_out:
  41497. sqlite3_free(zMasterJournal);
  41498. if( pMaster ){
  41499. sqlite3OsClose(pMaster);
  41500. assert( !isOpen(pJournal) );
  41501. sqlite3_free(pMaster);
  41502. }
  41503. return rc;
  41504. }
  41505. /*
  41506. ** This function is used to change the actual size of the database
  41507. ** file in the file-system. This only happens when committing a transaction,
  41508. ** or rolling back a transaction (including rolling back a hot-journal).
  41509. **
  41510. ** If the main database file is not open, or the pager is not in either
  41511. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  41512. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  41513. ** If the file on disk is currently larger than nPage pages, then use the VFS
  41514. ** xTruncate() method to truncate it.
  41515. **
  41516. ** Or, it might might be the case that the file on disk is smaller than
  41517. ** nPage pages. Some operating system implementations can get confused if
  41518. ** you try to truncate a file to some size that is larger than it
  41519. ** currently is, so detect this case and write a single zero byte to
  41520. ** the end of the new file instead.
  41521. **
  41522. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  41523. ** the database file, return the error code to the caller.
  41524. */
  41525. static int pager_truncate(Pager *pPager, Pgno nPage){
  41526. int rc = SQLITE_OK;
  41527. assert( pPager->eState!=PAGER_ERROR );
  41528. assert( pPager->eState!=PAGER_READER );
  41529. if( isOpen(pPager->fd)
  41530. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41531. ){
  41532. i64 currentSize, newSize;
  41533. int szPage = pPager->pageSize;
  41534. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41535. /* TODO: Is it safe to use Pager.dbFileSize here? */
  41536. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  41537. newSize = szPage*(i64)nPage;
  41538. if( rc==SQLITE_OK && currentSize!=newSize ){
  41539. if( currentSize>newSize ){
  41540. rc = sqlite3OsTruncate(pPager->fd, newSize);
  41541. }else if( (currentSize+szPage)<=newSize ){
  41542. char *pTmp = pPager->pTmpSpace;
  41543. memset(pTmp, 0, szPage);
  41544. testcase( (newSize-szPage) == currentSize );
  41545. testcase( (newSize-szPage) > currentSize );
  41546. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  41547. }
  41548. if( rc==SQLITE_OK ){
  41549. pPager->dbFileSize = nPage;
  41550. }
  41551. }
  41552. }
  41553. return rc;
  41554. }
  41555. /*
  41556. ** Return a sanitized version of the sector-size of OS file pFile. The
  41557. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  41558. */
  41559. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  41560. int iRet = sqlite3OsSectorSize(pFile);
  41561. if( iRet<32 ){
  41562. iRet = 512;
  41563. }else if( iRet>MAX_SECTOR_SIZE ){
  41564. assert( MAX_SECTOR_SIZE>=512 );
  41565. iRet = MAX_SECTOR_SIZE;
  41566. }
  41567. return iRet;
  41568. }
  41569. /*
  41570. ** Set the value of the Pager.sectorSize variable for the given
  41571. ** pager based on the value returned by the xSectorSize method
  41572. ** of the open database file. The sector size will be used used
  41573. ** to determine the size and alignment of journal header and
  41574. ** master journal pointers within created journal files.
  41575. **
  41576. ** For temporary files the effective sector size is always 512 bytes.
  41577. **
  41578. ** Otherwise, for non-temporary files, the effective sector size is
  41579. ** the value returned by the xSectorSize() method rounded up to 32 if
  41580. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  41581. ** is greater than MAX_SECTOR_SIZE.
  41582. **
  41583. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  41584. ** the effective sector size to its minimum value (512). The purpose of
  41585. ** pPager->sectorSize is to define the "blast radius" of bytes that
  41586. ** might change if a crash occurs while writing to a single byte in
  41587. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  41588. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  41589. ** size. For backwards compatibility of the rollback journal file format,
  41590. ** we cannot reduce the effective sector size below 512.
  41591. */
  41592. static void setSectorSize(Pager *pPager){
  41593. assert( isOpen(pPager->fd) || pPager->tempFile );
  41594. if( pPager->tempFile
  41595. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  41596. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  41597. ){
  41598. /* Sector size doesn't matter for temporary files. Also, the file
  41599. ** may not have been opened yet, in which case the OsSectorSize()
  41600. ** call will segfault. */
  41601. pPager->sectorSize = 512;
  41602. }else{
  41603. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  41604. }
  41605. }
  41606. /*
  41607. ** Playback the journal and thus restore the database file to
  41608. ** the state it was in before we started making changes.
  41609. **
  41610. ** The journal file format is as follows:
  41611. **
  41612. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  41613. ** (2) 4 byte big-endian integer which is the number of valid page records
  41614. ** in the journal. If this value is 0xffffffff, then compute the
  41615. ** number of page records from the journal size.
  41616. ** (3) 4 byte big-endian integer which is the initial value for the
  41617. ** sanity checksum.
  41618. ** (4) 4 byte integer which is the number of pages to truncate the
  41619. ** database to during a rollback.
  41620. ** (5) 4 byte big-endian integer which is the sector size. The header
  41621. ** is this many bytes in size.
  41622. ** (6) 4 byte big-endian integer which is the page size.
  41623. ** (7) zero padding out to the next sector size.
  41624. ** (8) Zero or more pages instances, each as follows:
  41625. ** + 4 byte page number.
  41626. ** + pPager->pageSize bytes of data.
  41627. ** + 4 byte checksum
  41628. **
  41629. ** When we speak of the journal header, we mean the first 7 items above.
  41630. ** Each entry in the journal is an instance of the 8th item.
  41631. **
  41632. ** Call the value from the second bullet "nRec". nRec is the number of
  41633. ** valid page entries in the journal. In most cases, you can compute the
  41634. ** value of nRec from the size of the journal file. But if a power
  41635. ** failure occurred while the journal was being written, it could be the
  41636. ** case that the size of the journal file had already been increased but
  41637. ** the extra entries had not yet made it safely to disk. In such a case,
  41638. ** the value of nRec computed from the file size would be too large. For
  41639. ** that reason, we always use the nRec value in the header.
  41640. **
  41641. ** If the nRec value is 0xffffffff it means that nRec should be computed
  41642. ** from the file size. This value is used when the user selects the
  41643. ** no-sync option for the journal. A power failure could lead to corruption
  41644. ** in this case. But for things like temporary table (which will be
  41645. ** deleted when the power is restored) we don't care.
  41646. **
  41647. ** If the file opened as the journal file is not a well-formed
  41648. ** journal file then all pages up to the first corrupted page are rolled
  41649. ** back (or no pages if the journal header is corrupted). The journal file
  41650. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  41651. ** been encountered.
  41652. **
  41653. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  41654. ** and an error code is returned.
  41655. **
  41656. ** The isHot parameter indicates that we are trying to rollback a journal
  41657. ** that might be a hot journal. Or, it could be that the journal is
  41658. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  41659. ** If the journal really is hot, reset the pager cache prior rolling
  41660. ** back any content. If the journal is merely persistent, no reset is
  41661. ** needed.
  41662. */
  41663. static int pager_playback(Pager *pPager, int isHot){
  41664. sqlite3_vfs *pVfs = pPager->pVfs;
  41665. i64 szJ; /* Size of the journal file in bytes */
  41666. u32 nRec; /* Number of Records in the journal */
  41667. u32 u; /* Unsigned loop counter */
  41668. Pgno mxPg = 0; /* Size of the original file in pages */
  41669. int rc; /* Result code of a subroutine */
  41670. int res = 1; /* Value returned by sqlite3OsAccess() */
  41671. char *zMaster = 0; /* Name of master journal file if any */
  41672. int needPagerReset; /* True to reset page prior to first page rollback */
  41673. int nPlayback = 0; /* Total number of pages restored from journal */
  41674. /* Figure out how many records are in the journal. Abort early if
  41675. ** the journal is empty.
  41676. */
  41677. assert( isOpen(pPager->jfd) );
  41678. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  41679. if( rc!=SQLITE_OK ){
  41680. goto end_playback;
  41681. }
  41682. /* Read the master journal name from the journal, if it is present.
  41683. ** If a master journal file name is specified, but the file is not
  41684. ** present on disk, then the journal is not hot and does not need to be
  41685. ** played back.
  41686. **
  41687. ** TODO: Technically the following is an error because it assumes that
  41688. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  41689. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  41690. ** mxPathname is 512, which is the same as the minimum allowable value
  41691. ** for pageSize.
  41692. */
  41693. zMaster = pPager->pTmpSpace;
  41694. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41695. if( rc==SQLITE_OK && zMaster[0] ){
  41696. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  41697. }
  41698. zMaster = 0;
  41699. if( rc!=SQLITE_OK || !res ){
  41700. goto end_playback;
  41701. }
  41702. pPager->journalOff = 0;
  41703. needPagerReset = isHot;
  41704. /* This loop terminates either when a readJournalHdr() or
  41705. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  41706. ** occurs.
  41707. */
  41708. while( 1 ){
  41709. /* Read the next journal header from the journal file. If there are
  41710. ** not enough bytes left in the journal file for a complete header, or
  41711. ** it is corrupted, then a process must have failed while writing it.
  41712. ** This indicates nothing more needs to be rolled back.
  41713. */
  41714. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  41715. if( rc!=SQLITE_OK ){
  41716. if( rc==SQLITE_DONE ){
  41717. rc = SQLITE_OK;
  41718. }
  41719. goto end_playback;
  41720. }
  41721. /* If nRec is 0xffffffff, then this journal was created by a process
  41722. ** working in no-sync mode. This means that the rest of the journal
  41723. ** file consists of pages, there are no more journal headers. Compute
  41724. ** the value of nRec based on this assumption.
  41725. */
  41726. if( nRec==0xffffffff ){
  41727. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  41728. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  41729. }
  41730. /* If nRec is 0 and this rollback is of a transaction created by this
  41731. ** process and if this is the final header in the journal, then it means
  41732. ** that this part of the journal was being filled but has not yet been
  41733. ** synced to disk. Compute the number of pages based on the remaining
  41734. ** size of the file.
  41735. **
  41736. ** The third term of the test was added to fix ticket #2565.
  41737. ** When rolling back a hot journal, nRec==0 always means that the next
  41738. ** chunk of the journal contains zero pages to be rolled back. But
  41739. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  41740. ** the journal, it means that the journal might contain additional
  41741. ** pages that need to be rolled back and that the number of pages
  41742. ** should be computed based on the journal file size.
  41743. */
  41744. if( nRec==0 && !isHot &&
  41745. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  41746. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  41747. }
  41748. /* If this is the first header read from the journal, truncate the
  41749. ** database file back to its original size.
  41750. */
  41751. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  41752. rc = pager_truncate(pPager, mxPg);
  41753. if( rc!=SQLITE_OK ){
  41754. goto end_playback;
  41755. }
  41756. pPager->dbSize = mxPg;
  41757. }
  41758. /* Copy original pages out of the journal and back into the
  41759. ** database file and/or page cache.
  41760. */
  41761. for(u=0; u<nRec; u++){
  41762. if( needPagerReset ){
  41763. pager_reset(pPager);
  41764. needPagerReset = 0;
  41765. }
  41766. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  41767. if( rc==SQLITE_OK ){
  41768. nPlayback++;
  41769. }else{
  41770. if( rc==SQLITE_DONE ){
  41771. pPager->journalOff = szJ;
  41772. break;
  41773. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  41774. /* If the journal has been truncated, simply stop reading and
  41775. ** processing the journal. This might happen if the journal was
  41776. ** not completely written and synced prior to a crash. In that
  41777. ** case, the database should have never been written in the
  41778. ** first place so it is OK to simply abandon the rollback. */
  41779. rc = SQLITE_OK;
  41780. goto end_playback;
  41781. }else{
  41782. /* If we are unable to rollback, quit and return the error
  41783. ** code. This will cause the pager to enter the error state
  41784. ** so that no further harm will be done. Perhaps the next
  41785. ** process to come along will be able to rollback the database.
  41786. */
  41787. goto end_playback;
  41788. }
  41789. }
  41790. }
  41791. }
  41792. /*NOTREACHED*/
  41793. assert( 0 );
  41794. end_playback:
  41795. /* Following a rollback, the database file should be back in its original
  41796. ** state prior to the start of the transaction, so invoke the
  41797. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  41798. ** assertion that the transaction counter was modified.
  41799. */
  41800. #ifdef SQLITE_DEBUG
  41801. if( pPager->fd->pMethods ){
  41802. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  41803. }
  41804. #endif
  41805. /* If this playback is happening automatically as a result of an IO or
  41806. ** malloc error that occurred after the change-counter was updated but
  41807. ** before the transaction was committed, then the change-counter
  41808. ** modification may just have been reverted. If this happens in exclusive
  41809. ** mode, then subsequent transactions performed by the connection will not
  41810. ** update the change-counter at all. This may lead to cache inconsistency
  41811. ** problems for other processes at some point in the future. So, just
  41812. ** in case this has happened, clear the changeCountDone flag now.
  41813. */
  41814. pPager->changeCountDone = pPager->tempFile;
  41815. if( rc==SQLITE_OK ){
  41816. zMaster = pPager->pTmpSpace;
  41817. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41818. testcase( rc!=SQLITE_OK );
  41819. }
  41820. if( rc==SQLITE_OK
  41821. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41822. ){
  41823. rc = sqlite3PagerSync(pPager);
  41824. }
  41825. if( rc==SQLITE_OK ){
  41826. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  41827. testcase( rc!=SQLITE_OK );
  41828. }
  41829. if( rc==SQLITE_OK && zMaster[0] && res ){
  41830. /* If there was a master journal and this routine will return success,
  41831. ** see if it is possible to delete the master journal.
  41832. */
  41833. rc = pager_delmaster(pPager, zMaster);
  41834. testcase( rc!=SQLITE_OK );
  41835. }
  41836. if( isHot && nPlayback ){
  41837. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  41838. nPlayback, pPager->zJournal);
  41839. }
  41840. /* The Pager.sectorSize variable may have been updated while rolling
  41841. ** back a journal created by a process with a different sector size
  41842. ** value. Reset it to the correct value for this process.
  41843. */
  41844. setSectorSize(pPager);
  41845. return rc;
  41846. }
  41847. /*
  41848. ** Read the content for page pPg out of the database file and into
  41849. ** pPg->pData. A shared lock or greater must be held on the database
  41850. ** file before this function is called.
  41851. **
  41852. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  41853. ** the value read from the database file.
  41854. **
  41855. ** If an IO error occurs, then the IO error is returned to the caller.
  41856. ** Otherwise, SQLITE_OK is returned.
  41857. */
  41858. static int readDbPage(PgHdr *pPg, u32 iFrame){
  41859. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  41860. Pgno pgno = pPg->pgno; /* Page number to read */
  41861. int rc = SQLITE_OK; /* Return code */
  41862. int pgsz = pPager->pageSize; /* Number of bytes to read */
  41863. assert( pPager->eState>=PAGER_READER && !MEMDB );
  41864. assert( isOpen(pPager->fd) );
  41865. #ifndef SQLITE_OMIT_WAL
  41866. if( iFrame ){
  41867. /* Try to pull the page from the write-ahead log. */
  41868. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  41869. }else
  41870. #endif
  41871. {
  41872. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  41873. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  41874. if( rc==SQLITE_IOERR_SHORT_READ ){
  41875. rc = SQLITE_OK;
  41876. }
  41877. }
  41878. if( pgno==1 ){
  41879. if( rc ){
  41880. /* If the read is unsuccessful, set the dbFileVers[] to something
  41881. ** that will never be a valid file version. dbFileVers[] is a copy
  41882. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  41883. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  41884. ** should be page numbers which are never 0xffffffff. So filling
  41885. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  41886. **
  41887. ** For an encrypted database, the situation is more complex: bytes
  41888. ** 24..39 of the database are white noise. But the probability of
  41889. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  41890. ** we should still be ok.
  41891. */
  41892. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  41893. }else{
  41894. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  41895. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  41896. }
  41897. }
  41898. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  41899. PAGER_INCR(sqlite3_pager_readdb_count);
  41900. PAGER_INCR(pPager->nRead);
  41901. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  41902. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  41903. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  41904. return rc;
  41905. }
  41906. /*
  41907. ** Update the value of the change-counter at offsets 24 and 92 in
  41908. ** the header and the sqlite version number at offset 96.
  41909. **
  41910. ** This is an unconditional update. See also the pager_incr_changecounter()
  41911. ** routine which only updates the change-counter if the update is actually
  41912. ** needed, as determined by the pPager->changeCountDone state variable.
  41913. */
  41914. static void pager_write_changecounter(PgHdr *pPg){
  41915. u32 change_counter;
  41916. /* Increment the value just read and write it back to byte 24. */
  41917. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  41918. put32bits(((char*)pPg->pData)+24, change_counter);
  41919. /* Also store the SQLite version number in bytes 96..99 and in
  41920. ** bytes 92..95 store the change counter for which the version number
  41921. ** is valid. */
  41922. put32bits(((char*)pPg->pData)+92, change_counter);
  41923. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  41924. }
  41925. #ifndef SQLITE_OMIT_WAL
  41926. /*
  41927. ** This function is invoked once for each page that has already been
  41928. ** written into the log file when a WAL transaction is rolled back.
  41929. ** Parameter iPg is the page number of said page. The pCtx argument
  41930. ** is actually a pointer to the Pager structure.
  41931. **
  41932. ** If page iPg is present in the cache, and has no outstanding references,
  41933. ** it is discarded. Otherwise, if there are one or more outstanding
  41934. ** references, the page content is reloaded from the database. If the
  41935. ** attempt to reload content from the database is required and fails,
  41936. ** return an SQLite error code. Otherwise, SQLITE_OK.
  41937. */
  41938. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  41939. int rc = SQLITE_OK;
  41940. Pager *pPager = (Pager *)pCtx;
  41941. PgHdr *pPg;
  41942. assert( pagerUseWal(pPager) );
  41943. pPg = sqlite3PagerLookup(pPager, iPg);
  41944. if( pPg ){
  41945. if( sqlite3PcachePageRefcount(pPg)==1 ){
  41946. sqlite3PcacheDrop(pPg);
  41947. }else{
  41948. u32 iFrame = 0;
  41949. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  41950. if( rc==SQLITE_OK ){
  41951. rc = readDbPage(pPg, iFrame);
  41952. }
  41953. if( rc==SQLITE_OK ){
  41954. pPager->xReiniter(pPg);
  41955. }
  41956. sqlite3PagerUnref(pPg);
  41957. }
  41958. }
  41959. /* Normally, if a transaction is rolled back, any backup processes are
  41960. ** updated as data is copied out of the rollback journal and into the
  41961. ** database. This is not generally possible with a WAL database, as
  41962. ** rollback involves simply truncating the log file. Therefore, if one
  41963. ** or more frames have already been written to the log (and therefore
  41964. ** also copied into the backup databases) as part of this transaction,
  41965. ** the backups must be restarted.
  41966. */
  41967. sqlite3BackupRestart(pPager->pBackup);
  41968. return rc;
  41969. }
  41970. /*
  41971. ** This function is called to rollback a transaction on a WAL database.
  41972. */
  41973. static int pagerRollbackWal(Pager *pPager){
  41974. int rc; /* Return Code */
  41975. PgHdr *pList; /* List of dirty pages to revert */
  41976. /* For all pages in the cache that are currently dirty or have already
  41977. ** been written (but not committed) to the log file, do one of the
  41978. ** following:
  41979. **
  41980. ** + Discard the cached page (if refcount==0), or
  41981. ** + Reload page content from the database (if refcount>0).
  41982. */
  41983. pPager->dbSize = pPager->dbOrigSize;
  41984. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  41985. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41986. while( pList && rc==SQLITE_OK ){
  41987. PgHdr *pNext = pList->pDirty;
  41988. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  41989. pList = pNext;
  41990. }
  41991. return rc;
  41992. }
  41993. /*
  41994. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  41995. ** the contents of the list of pages headed by pList (connected by pDirty),
  41996. ** this function notifies any active backup processes that the pages have
  41997. ** changed.
  41998. **
  41999. ** The list of pages passed into this routine is always sorted by page number.
  42000. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  42001. */
  42002. static int pagerWalFrames(
  42003. Pager *pPager, /* Pager object */
  42004. PgHdr *pList, /* List of frames to log */
  42005. Pgno nTruncate, /* Database size after this commit */
  42006. int isCommit /* True if this is a commit */
  42007. ){
  42008. int rc; /* Return code */
  42009. int nList; /* Number of pages in pList */
  42010. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  42011. PgHdr *p; /* For looping over pages */
  42012. #endif
  42013. assert( pPager->pWal );
  42014. assert( pList );
  42015. #ifdef SQLITE_DEBUG
  42016. /* Verify that the page list is in accending order */
  42017. for(p=pList; p && p->pDirty; p=p->pDirty){
  42018. assert( p->pgno < p->pDirty->pgno );
  42019. }
  42020. #endif
  42021. assert( pList->pDirty==0 || isCommit );
  42022. if( isCommit ){
  42023. /* If a WAL transaction is being committed, there is no point in writing
  42024. ** any pages with page numbers greater than nTruncate into the WAL file.
  42025. ** They will never be read by any client. So remove them from the pDirty
  42026. ** list here. */
  42027. PgHdr *p;
  42028. PgHdr **ppNext = &pList;
  42029. nList = 0;
  42030. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  42031. if( p->pgno<=nTruncate ){
  42032. ppNext = &p->pDirty;
  42033. nList++;
  42034. }
  42035. }
  42036. assert( pList );
  42037. }else{
  42038. nList = 1;
  42039. }
  42040. pPager->aStat[PAGER_STAT_WRITE] += nList;
  42041. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42042. rc = sqlite3WalFrames(pPager->pWal,
  42043. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  42044. );
  42045. if( rc==SQLITE_OK && pPager->pBackup ){
  42046. PgHdr *p;
  42047. for(p=pList; p; p=p->pDirty){
  42048. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  42049. }
  42050. }
  42051. #ifdef SQLITE_CHECK_PAGES
  42052. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  42053. for(p=pList; p; p=p->pDirty){
  42054. pager_set_pagehash(p);
  42055. }
  42056. #endif
  42057. return rc;
  42058. }
  42059. /*
  42060. ** Begin a read transaction on the WAL.
  42061. **
  42062. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  42063. ** makes a snapshot of the database at the current point in time and preserves
  42064. ** that snapshot for use by the reader in spite of concurrently changes by
  42065. ** other writers or checkpointers.
  42066. */
  42067. static int pagerBeginReadTransaction(Pager *pPager){
  42068. int rc; /* Return code */
  42069. int changed = 0; /* True if cache must be reset */
  42070. assert( pagerUseWal(pPager) );
  42071. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  42072. /* sqlite3WalEndReadTransaction() was not called for the previous
  42073. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  42074. ** are in locking_mode=NORMAL and EndRead() was previously called,
  42075. ** the duplicate call is harmless.
  42076. */
  42077. sqlite3WalEndReadTransaction(pPager->pWal);
  42078. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  42079. if( rc!=SQLITE_OK || changed ){
  42080. pager_reset(pPager);
  42081. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  42082. }
  42083. return rc;
  42084. }
  42085. #endif
  42086. /*
  42087. ** This function is called as part of the transition from PAGER_OPEN
  42088. ** to PAGER_READER state to determine the size of the database file
  42089. ** in pages (assuming the page size currently stored in Pager.pageSize).
  42090. **
  42091. ** If no error occurs, SQLITE_OK is returned and the size of the database
  42092. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  42093. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  42094. */
  42095. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  42096. Pgno nPage; /* Value to return via *pnPage */
  42097. /* Query the WAL sub-system for the database size. The WalDbsize()
  42098. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  42099. ** if the database size is not available. The database size is not
  42100. ** available from the WAL sub-system if the log file is empty or
  42101. ** contains no valid committed transactions.
  42102. */
  42103. assert( pPager->eState==PAGER_OPEN );
  42104. assert( pPager->eLock>=SHARED_LOCK );
  42105. nPage = sqlite3WalDbsize(pPager->pWal);
  42106. /* If the database size was not available from the WAL sub-system,
  42107. ** determine it based on the size of the database file. If the size
  42108. ** of the database file is not an integer multiple of the page-size,
  42109. ** round down to the nearest page. Except, any file larger than 0
  42110. ** bytes in size is considered to contain at least one page.
  42111. */
  42112. if( nPage==0 ){
  42113. i64 n = 0; /* Size of db file in bytes */
  42114. assert( isOpen(pPager->fd) || pPager->tempFile );
  42115. if( isOpen(pPager->fd) ){
  42116. int rc = sqlite3OsFileSize(pPager->fd, &n);
  42117. if( rc!=SQLITE_OK ){
  42118. return rc;
  42119. }
  42120. }
  42121. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  42122. }
  42123. /* If the current number of pages in the file is greater than the
  42124. ** configured maximum pager number, increase the allowed limit so
  42125. ** that the file can be read.
  42126. */
  42127. if( nPage>pPager->mxPgno ){
  42128. pPager->mxPgno = (Pgno)nPage;
  42129. }
  42130. *pnPage = nPage;
  42131. return SQLITE_OK;
  42132. }
  42133. #ifndef SQLITE_OMIT_WAL
  42134. /*
  42135. ** Check if the *-wal file that corresponds to the database opened by pPager
  42136. ** exists if the database is not empy, or verify that the *-wal file does
  42137. ** not exist (by deleting it) if the database file is empty.
  42138. **
  42139. ** If the database is not empty and the *-wal file exists, open the pager
  42140. ** in WAL mode. If the database is empty or if no *-wal file exists and
  42141. ** if no error occurs, make sure Pager.journalMode is not set to
  42142. ** PAGER_JOURNALMODE_WAL.
  42143. **
  42144. ** Return SQLITE_OK or an error code.
  42145. **
  42146. ** The caller must hold a SHARED lock on the database file to call this
  42147. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  42148. ** a WAL on a none-empty database, this ensures there is no race condition
  42149. ** between the xAccess() below and an xDelete() being executed by some
  42150. ** other connection.
  42151. */
  42152. static int pagerOpenWalIfPresent(Pager *pPager){
  42153. int rc = SQLITE_OK;
  42154. assert( pPager->eState==PAGER_OPEN );
  42155. assert( pPager->eLock>=SHARED_LOCK );
  42156. if( !pPager->tempFile ){
  42157. int isWal; /* True if WAL file exists */
  42158. Pgno nPage; /* Size of the database file */
  42159. rc = pagerPagecount(pPager, &nPage);
  42160. if( rc ) return rc;
  42161. if( nPage==0 ){
  42162. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  42163. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  42164. isWal = 0;
  42165. }else{
  42166. rc = sqlite3OsAccess(
  42167. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  42168. );
  42169. }
  42170. if( rc==SQLITE_OK ){
  42171. if( isWal ){
  42172. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  42173. rc = sqlite3PagerOpenWal(pPager, 0);
  42174. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  42175. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  42176. }
  42177. }
  42178. }
  42179. return rc;
  42180. }
  42181. #endif
  42182. /*
  42183. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  42184. ** the entire master journal file. The case pSavepoint==NULL occurs when
  42185. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  42186. ** savepoint.
  42187. **
  42188. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  42189. ** being rolled back), then the rollback consists of up to three stages,
  42190. ** performed in the order specified:
  42191. **
  42192. ** * Pages are played back from the main journal starting at byte
  42193. ** offset PagerSavepoint.iOffset and continuing to
  42194. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  42195. ** file if PagerSavepoint.iHdrOffset is zero.
  42196. **
  42197. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  42198. ** back starting from the journal header immediately following
  42199. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  42200. **
  42201. ** * Pages are then played back from the sub-journal file, starting
  42202. ** with the PagerSavepoint.iSubRec and continuing to the end of
  42203. ** the journal file.
  42204. **
  42205. ** Throughout the rollback process, each time a page is rolled back, the
  42206. ** corresponding bit is set in a bitvec structure (variable pDone in the
  42207. ** implementation below). This is used to ensure that a page is only
  42208. ** rolled back the first time it is encountered in either journal.
  42209. **
  42210. ** If pSavepoint is NULL, then pages are only played back from the main
  42211. ** journal file. There is no need for a bitvec in this case.
  42212. **
  42213. ** In either case, before playback commences the Pager.dbSize variable
  42214. ** is reset to the value that it held at the start of the savepoint
  42215. ** (or transaction). No page with a page-number greater than this value
  42216. ** is played back. If one is encountered it is simply skipped.
  42217. */
  42218. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  42219. i64 szJ; /* Effective size of the main journal */
  42220. i64 iHdrOff; /* End of first segment of main-journal records */
  42221. int rc = SQLITE_OK; /* Return code */
  42222. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  42223. assert( pPager->eState!=PAGER_ERROR );
  42224. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  42225. /* Allocate a bitvec to use to store the set of pages rolled back */
  42226. if( pSavepoint ){
  42227. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  42228. if( !pDone ){
  42229. return SQLITE_NOMEM;
  42230. }
  42231. }
  42232. /* Set the database size back to the value it was before the savepoint
  42233. ** being reverted was opened.
  42234. */
  42235. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  42236. pPager->changeCountDone = pPager->tempFile;
  42237. if( !pSavepoint && pagerUseWal(pPager) ){
  42238. return pagerRollbackWal(pPager);
  42239. }
  42240. /* Use pPager->journalOff as the effective size of the main rollback
  42241. ** journal. The actual file might be larger than this in
  42242. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  42243. ** past pPager->journalOff is off-limits to us.
  42244. */
  42245. szJ = pPager->journalOff;
  42246. assert( pagerUseWal(pPager)==0 || szJ==0 );
  42247. /* Begin by rolling back records from the main journal starting at
  42248. ** PagerSavepoint.iOffset and continuing to the next journal header.
  42249. ** There might be records in the main journal that have a page number
  42250. ** greater than the current database size (pPager->dbSize) but those
  42251. ** will be skipped automatically. Pages are added to pDone as they
  42252. ** are played back.
  42253. */
  42254. if( pSavepoint && !pagerUseWal(pPager) ){
  42255. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  42256. pPager->journalOff = pSavepoint->iOffset;
  42257. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  42258. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42259. }
  42260. assert( rc!=SQLITE_DONE );
  42261. }else{
  42262. pPager->journalOff = 0;
  42263. }
  42264. /* Continue rolling back records out of the main journal starting at
  42265. ** the first journal header seen and continuing until the effective end
  42266. ** of the main journal file. Continue to skip out-of-range pages and
  42267. ** continue adding pages rolled back to pDone.
  42268. */
  42269. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  42270. u32 ii; /* Loop counter */
  42271. u32 nJRec = 0; /* Number of Journal Records */
  42272. u32 dummy;
  42273. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  42274. assert( rc!=SQLITE_DONE );
  42275. /*
  42276. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  42277. ** test is related to ticket #2565. See the discussion in the
  42278. ** pager_playback() function for additional information.
  42279. */
  42280. if( nJRec==0
  42281. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  42282. ){
  42283. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  42284. }
  42285. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  42286. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42287. }
  42288. assert( rc!=SQLITE_DONE );
  42289. }
  42290. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  42291. /* Finally, rollback pages from the sub-journal. Page that were
  42292. ** previously rolled back out of the main journal (and are hence in pDone)
  42293. ** will be skipped. Out-of-range pages are also skipped.
  42294. */
  42295. if( pSavepoint ){
  42296. u32 ii; /* Loop counter */
  42297. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  42298. if( pagerUseWal(pPager) ){
  42299. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  42300. }
  42301. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  42302. assert( offset==(i64)ii*(4+pPager->pageSize) );
  42303. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  42304. }
  42305. assert( rc!=SQLITE_DONE );
  42306. }
  42307. sqlite3BitvecDestroy(pDone);
  42308. if( rc==SQLITE_OK ){
  42309. pPager->journalOff = szJ;
  42310. }
  42311. return rc;
  42312. }
  42313. /*
  42314. ** Change the maximum number of in-memory pages that are allowed.
  42315. */
  42316. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  42317. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  42318. }
  42319. /*
  42320. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  42321. */
  42322. static void pagerFixMaplimit(Pager *pPager){
  42323. #if SQLITE_MAX_MMAP_SIZE>0
  42324. sqlite3_file *fd = pPager->fd;
  42325. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  42326. sqlite3_int64 sz;
  42327. sz = pPager->szMmap;
  42328. pPager->bUseFetch = (sz>0);
  42329. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  42330. }
  42331. #endif
  42332. }
  42333. /*
  42334. ** Change the maximum size of any memory mapping made of the database file.
  42335. */
  42336. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  42337. pPager->szMmap = szMmap;
  42338. pagerFixMaplimit(pPager);
  42339. }
  42340. /*
  42341. ** Free as much memory as possible from the pager.
  42342. */
  42343. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  42344. sqlite3PcacheShrink(pPager->pPCache);
  42345. }
  42346. /*
  42347. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  42348. **
  42349. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  42350. ** of the database to damage due to OS crashes or power failures by
  42351. ** changing the number of syncs()s when writing the journals.
  42352. ** There are three levels:
  42353. **
  42354. ** OFF sqlite3OsSync() is never called. This is the default
  42355. ** for temporary and transient files.
  42356. **
  42357. ** NORMAL The journal is synced once before writes begin on the
  42358. ** database. This is normally adequate protection, but
  42359. ** it is theoretically possible, though very unlikely,
  42360. ** that an inopertune power failure could leave the journal
  42361. ** in a state which would cause damage to the database
  42362. ** when it is rolled back.
  42363. **
  42364. ** FULL The journal is synced twice before writes begin on the
  42365. ** database (with some additional information - the nRec field
  42366. ** of the journal header - being written in between the two
  42367. ** syncs). If we assume that writing a
  42368. ** single disk sector is atomic, then this mode provides
  42369. ** assurance that the journal will not be corrupted to the
  42370. ** point of causing damage to the database during rollback.
  42371. **
  42372. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  42373. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  42374. ** prior to the start of checkpoint and that the database file is synced
  42375. ** at the conclusion of the checkpoint if the entire content of the WAL
  42376. ** was written back into the database. But no sync operations occur for
  42377. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  42378. ** file is synced following each commit operation, in addition to the
  42379. ** syncs associated with NORMAL.
  42380. **
  42381. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  42382. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  42383. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  42384. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  42385. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  42386. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  42387. ** the xSync primitive is called and is relevant to all platforms.
  42388. **
  42389. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  42390. ** and FULL=3.
  42391. */
  42392. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  42393. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  42394. Pager *pPager, /* The pager to set safety level for */
  42395. unsigned pgFlags /* Various flags */
  42396. ){
  42397. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  42398. assert( level>=1 && level<=3 );
  42399. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  42400. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  42401. if( pPager->noSync ){
  42402. pPager->syncFlags = 0;
  42403. pPager->ckptSyncFlags = 0;
  42404. }else if( pgFlags & PAGER_FULLFSYNC ){
  42405. pPager->syncFlags = SQLITE_SYNC_FULL;
  42406. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42407. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  42408. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42409. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42410. }else{
  42411. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42412. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42413. }
  42414. pPager->walSyncFlags = pPager->syncFlags;
  42415. if( pPager->fullSync ){
  42416. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  42417. }
  42418. if( pgFlags & PAGER_CACHESPILL ){
  42419. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  42420. }else{
  42421. pPager->doNotSpill |= SPILLFLAG_OFF;
  42422. }
  42423. }
  42424. #endif
  42425. /*
  42426. ** The following global variable is incremented whenever the library
  42427. ** attempts to open a temporary file. This information is used for
  42428. ** testing and analysis only.
  42429. */
  42430. #ifdef SQLITE_TEST
  42431. SQLITE_API int sqlite3_opentemp_count = 0;
  42432. #endif
  42433. /*
  42434. ** Open a temporary file.
  42435. **
  42436. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  42437. ** or some other error code if we fail. The OS will automatically
  42438. ** delete the temporary file when it is closed.
  42439. **
  42440. ** The flags passed to the VFS layer xOpen() call are those specified
  42441. ** by parameter vfsFlags ORed with the following:
  42442. **
  42443. ** SQLITE_OPEN_READWRITE
  42444. ** SQLITE_OPEN_CREATE
  42445. ** SQLITE_OPEN_EXCLUSIVE
  42446. ** SQLITE_OPEN_DELETEONCLOSE
  42447. */
  42448. static int pagerOpentemp(
  42449. Pager *pPager, /* The pager object */
  42450. sqlite3_file *pFile, /* Write the file descriptor here */
  42451. int vfsFlags /* Flags passed through to the VFS */
  42452. ){
  42453. int rc; /* Return code */
  42454. #ifdef SQLITE_TEST
  42455. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  42456. #endif
  42457. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  42458. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  42459. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  42460. assert( rc!=SQLITE_OK || isOpen(pFile) );
  42461. return rc;
  42462. }
  42463. /*
  42464. ** Set the busy handler function.
  42465. **
  42466. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  42467. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  42468. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  42469. ** lock. It does *not* invoke the busy handler when upgrading from
  42470. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  42471. ** (which occurs during hot-journal rollback). Summary:
  42472. **
  42473. ** Transition | Invokes xBusyHandler
  42474. ** --------------------------------------------------------
  42475. ** NO_LOCK -> SHARED_LOCK | Yes
  42476. ** SHARED_LOCK -> RESERVED_LOCK | No
  42477. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  42478. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  42479. **
  42480. ** If the busy-handler callback returns non-zero, the lock is
  42481. ** retried. If it returns zero, then the SQLITE_BUSY error is
  42482. ** returned to the caller of the pager API function.
  42483. */
  42484. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  42485. Pager *pPager, /* Pager object */
  42486. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  42487. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  42488. ){
  42489. pPager->xBusyHandler = xBusyHandler;
  42490. pPager->pBusyHandlerArg = pBusyHandlerArg;
  42491. if( isOpen(pPager->fd) ){
  42492. void **ap = (void **)&pPager->xBusyHandler;
  42493. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  42494. assert( ap[1]==pBusyHandlerArg );
  42495. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  42496. }
  42497. }
  42498. /*
  42499. ** Change the page size used by the Pager object. The new page size
  42500. ** is passed in *pPageSize.
  42501. **
  42502. ** If the pager is in the error state when this function is called, it
  42503. ** is a no-op. The value returned is the error state error code (i.e.
  42504. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  42505. **
  42506. ** Otherwise, if all of the following are true:
  42507. **
  42508. ** * the new page size (value of *pPageSize) is valid (a power
  42509. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  42510. **
  42511. ** * there are no outstanding page references, and
  42512. **
  42513. ** * the database is either not an in-memory database or it is
  42514. ** an in-memory database that currently consists of zero pages.
  42515. **
  42516. ** then the pager object page size is set to *pPageSize.
  42517. **
  42518. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  42519. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  42520. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  42521. ** In all other cases, SQLITE_OK is returned.
  42522. **
  42523. ** If the page size is not changed, either because one of the enumerated
  42524. ** conditions above is not true, the pager was in error state when this
  42525. ** function was called, or because the memory allocation attempt failed,
  42526. ** then *pPageSize is set to the old, retained page size before returning.
  42527. */
  42528. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  42529. int rc = SQLITE_OK;
  42530. /* It is not possible to do a full assert_pager_state() here, as this
  42531. ** function may be called from within PagerOpen(), before the state
  42532. ** of the Pager object is internally consistent.
  42533. **
  42534. ** At one point this function returned an error if the pager was in
  42535. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  42536. ** there is at least one outstanding page reference, this function
  42537. ** is a no-op for that case anyhow.
  42538. */
  42539. u32 pageSize = *pPageSize;
  42540. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  42541. if( (pPager->memDb==0 || pPager->dbSize==0)
  42542. && sqlite3PcacheRefCount(pPager->pPCache)==0
  42543. && pageSize && pageSize!=(u32)pPager->pageSize
  42544. ){
  42545. char *pNew = NULL; /* New temp space */
  42546. i64 nByte = 0;
  42547. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  42548. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  42549. }
  42550. if( rc==SQLITE_OK ){
  42551. pNew = (char *)sqlite3PageMalloc(pageSize);
  42552. if( !pNew ) rc = SQLITE_NOMEM;
  42553. }
  42554. if( rc==SQLITE_OK ){
  42555. pager_reset(pPager);
  42556. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  42557. pPager->pageSize = pageSize;
  42558. sqlite3PageFree(pPager->pTmpSpace);
  42559. pPager->pTmpSpace = pNew;
  42560. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  42561. }
  42562. }
  42563. *pPageSize = pPager->pageSize;
  42564. if( rc==SQLITE_OK ){
  42565. if( nReserve<0 ) nReserve = pPager->nReserve;
  42566. assert( nReserve>=0 && nReserve<1000 );
  42567. pPager->nReserve = (i16)nReserve;
  42568. pagerReportSize(pPager);
  42569. pagerFixMaplimit(pPager);
  42570. }
  42571. return rc;
  42572. }
  42573. /*
  42574. ** Return a pointer to the "temporary page" buffer held internally
  42575. ** by the pager. This is a buffer that is big enough to hold the
  42576. ** entire content of a database page. This buffer is used internally
  42577. ** during rollback and will be overwritten whenever a rollback
  42578. ** occurs. But other modules are free to use it too, as long as
  42579. ** no rollbacks are happening.
  42580. */
  42581. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  42582. return pPager->pTmpSpace;
  42583. }
  42584. /*
  42585. ** Attempt to set the maximum database page count if mxPage is positive.
  42586. ** Make no changes if mxPage is zero or negative. And never reduce the
  42587. ** maximum page count below the current size of the database.
  42588. **
  42589. ** Regardless of mxPage, return the current maximum page count.
  42590. */
  42591. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  42592. if( mxPage>0 ){
  42593. pPager->mxPgno = mxPage;
  42594. }
  42595. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  42596. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  42597. return pPager->mxPgno;
  42598. }
  42599. /*
  42600. ** The following set of routines are used to disable the simulated
  42601. ** I/O error mechanism. These routines are used to avoid simulated
  42602. ** errors in places where we do not care about errors.
  42603. **
  42604. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  42605. ** and generate no code.
  42606. */
  42607. #ifdef SQLITE_TEST
  42608. SQLITE_API extern int sqlite3_io_error_pending;
  42609. SQLITE_API extern int sqlite3_io_error_hit;
  42610. static int saved_cnt;
  42611. void disable_simulated_io_errors(void){
  42612. saved_cnt = sqlite3_io_error_pending;
  42613. sqlite3_io_error_pending = -1;
  42614. }
  42615. void enable_simulated_io_errors(void){
  42616. sqlite3_io_error_pending = saved_cnt;
  42617. }
  42618. #else
  42619. # define disable_simulated_io_errors()
  42620. # define enable_simulated_io_errors()
  42621. #endif
  42622. /*
  42623. ** Read the first N bytes from the beginning of the file into memory
  42624. ** that pDest points to.
  42625. **
  42626. ** If the pager was opened on a transient file (zFilename==""), or
  42627. ** opened on a file less than N bytes in size, the output buffer is
  42628. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  42629. ** function is used to read database headers, and a new transient or
  42630. ** zero sized database has a header than consists entirely of zeroes.
  42631. **
  42632. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  42633. ** the error code is returned to the caller and the contents of the
  42634. ** output buffer undefined.
  42635. */
  42636. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  42637. int rc = SQLITE_OK;
  42638. memset(pDest, 0, N);
  42639. assert( isOpen(pPager->fd) || pPager->tempFile );
  42640. /* This routine is only called by btree immediately after creating
  42641. ** the Pager object. There has not been an opportunity to transition
  42642. ** to WAL mode yet.
  42643. */
  42644. assert( !pagerUseWal(pPager) );
  42645. if( isOpen(pPager->fd) ){
  42646. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  42647. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  42648. if( rc==SQLITE_IOERR_SHORT_READ ){
  42649. rc = SQLITE_OK;
  42650. }
  42651. }
  42652. return rc;
  42653. }
  42654. /*
  42655. ** This function may only be called when a read-transaction is open on
  42656. ** the pager. It returns the total number of pages in the database.
  42657. **
  42658. ** However, if the file is between 1 and <page-size> bytes in size, then
  42659. ** this is considered a 1 page file.
  42660. */
  42661. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  42662. assert( pPager->eState>=PAGER_READER );
  42663. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  42664. *pnPage = (int)pPager->dbSize;
  42665. }
  42666. /*
  42667. ** Try to obtain a lock of type locktype on the database file. If
  42668. ** a similar or greater lock is already held, this function is a no-op
  42669. ** (returning SQLITE_OK immediately).
  42670. **
  42671. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  42672. ** the busy callback if the lock is currently not available. Repeat
  42673. ** until the busy callback returns false or until the attempt to
  42674. ** obtain the lock succeeds.
  42675. **
  42676. ** Return SQLITE_OK on success and an error code if we cannot obtain
  42677. ** the lock. If the lock is obtained successfully, set the Pager.state
  42678. ** variable to locktype before returning.
  42679. */
  42680. static int pager_wait_on_lock(Pager *pPager, int locktype){
  42681. int rc; /* Return code */
  42682. /* Check that this is either a no-op (because the requested lock is
  42683. ** already held, or one of the transistions that the busy-handler
  42684. ** may be invoked during, according to the comment above
  42685. ** sqlite3PagerSetBusyhandler().
  42686. */
  42687. assert( (pPager->eLock>=locktype)
  42688. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  42689. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  42690. );
  42691. do {
  42692. rc = pagerLockDb(pPager, locktype);
  42693. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  42694. return rc;
  42695. }
  42696. /*
  42697. ** Function assertTruncateConstraint(pPager) checks that one of the
  42698. ** following is true for all dirty pages currently in the page-cache:
  42699. **
  42700. ** a) The page number is less than or equal to the size of the
  42701. ** current database image, in pages, OR
  42702. **
  42703. ** b) if the page content were written at this time, it would not
  42704. ** be necessary to write the current content out to the sub-journal
  42705. ** (as determined by function subjRequiresPage()).
  42706. **
  42707. ** If the condition asserted by this function were not true, and the
  42708. ** dirty page were to be discarded from the cache via the pagerStress()
  42709. ** routine, pagerStress() would not write the current page content to
  42710. ** the database file. If a savepoint transaction were rolled back after
  42711. ** this happened, the correct behavior would be to restore the current
  42712. ** content of the page. However, since this content is not present in either
  42713. ** the database file or the portion of the rollback journal and
  42714. ** sub-journal rolled back the content could not be restored and the
  42715. ** database image would become corrupt. It is therefore fortunate that
  42716. ** this circumstance cannot arise.
  42717. */
  42718. #if defined(SQLITE_DEBUG)
  42719. static void assertTruncateConstraintCb(PgHdr *pPg){
  42720. assert( pPg->flags&PGHDR_DIRTY );
  42721. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  42722. }
  42723. static void assertTruncateConstraint(Pager *pPager){
  42724. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  42725. }
  42726. #else
  42727. # define assertTruncateConstraint(pPager)
  42728. #endif
  42729. /*
  42730. ** Truncate the in-memory database file image to nPage pages. This
  42731. ** function does not actually modify the database file on disk. It
  42732. ** just sets the internal state of the pager object so that the
  42733. ** truncation will be done when the current transaction is committed.
  42734. **
  42735. ** This function is only called right before committing a transaction.
  42736. ** Once this function has been called, the transaction must either be
  42737. ** rolled back or committed. It is not safe to call this function and
  42738. ** then continue writing to the database.
  42739. */
  42740. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  42741. assert( pPager->dbSize>=nPage );
  42742. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  42743. pPager->dbSize = nPage;
  42744. /* At one point the code here called assertTruncateConstraint() to
  42745. ** ensure that all pages being truncated away by this operation are,
  42746. ** if one or more savepoints are open, present in the savepoint
  42747. ** journal so that they can be restored if the savepoint is rolled
  42748. ** back. This is no longer necessary as this function is now only
  42749. ** called right before committing a transaction. So although the
  42750. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  42751. ** they cannot be rolled back. So the assertTruncateConstraint() call
  42752. ** is no longer correct. */
  42753. }
  42754. /*
  42755. ** This function is called before attempting a hot-journal rollback. It
  42756. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  42757. ** size of the journal file so that the pager_playback() routine knows
  42758. ** that the entire journal file has been synced.
  42759. **
  42760. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  42761. ** that if a power-failure occurs during the rollback, the process that
  42762. ** attempts rollback following system recovery sees the same journal
  42763. ** content as this process.
  42764. **
  42765. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  42766. ** an SQLite error code.
  42767. */
  42768. static int pagerSyncHotJournal(Pager *pPager){
  42769. int rc = SQLITE_OK;
  42770. if( !pPager->noSync ){
  42771. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  42772. }
  42773. if( rc==SQLITE_OK ){
  42774. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  42775. }
  42776. return rc;
  42777. }
  42778. /*
  42779. ** Obtain a reference to a memory mapped page object for page number pgno.
  42780. ** The new object will use the pointer pData, obtained from xFetch().
  42781. ** If successful, set *ppPage to point to the new page reference
  42782. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  42783. ** *ppPage to zero.
  42784. **
  42785. ** Page references obtained by calling this function should be released
  42786. ** by calling pagerReleaseMapPage().
  42787. */
  42788. static int pagerAcquireMapPage(
  42789. Pager *pPager, /* Pager object */
  42790. Pgno pgno, /* Page number */
  42791. void *pData, /* xFetch()'d data for this page */
  42792. PgHdr **ppPage /* OUT: Acquired page object */
  42793. ){
  42794. PgHdr *p; /* Memory mapped page to return */
  42795. if( pPager->pMmapFreelist ){
  42796. *ppPage = p = pPager->pMmapFreelist;
  42797. pPager->pMmapFreelist = p->pDirty;
  42798. p->pDirty = 0;
  42799. memset(p->pExtra, 0, pPager->nExtra);
  42800. }else{
  42801. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  42802. if( p==0 ){
  42803. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  42804. return SQLITE_NOMEM;
  42805. }
  42806. p->pExtra = (void *)&p[1];
  42807. p->flags = PGHDR_MMAP;
  42808. p->nRef = 1;
  42809. p->pPager = pPager;
  42810. }
  42811. assert( p->pExtra==(void *)&p[1] );
  42812. assert( p->pPage==0 );
  42813. assert( p->flags==PGHDR_MMAP );
  42814. assert( p->pPager==pPager );
  42815. assert( p->nRef==1 );
  42816. p->pgno = pgno;
  42817. p->pData = pData;
  42818. pPager->nMmapOut++;
  42819. return SQLITE_OK;
  42820. }
  42821. /*
  42822. ** Release a reference to page pPg. pPg must have been returned by an
  42823. ** earlier call to pagerAcquireMapPage().
  42824. */
  42825. static void pagerReleaseMapPage(PgHdr *pPg){
  42826. Pager *pPager = pPg->pPager;
  42827. pPager->nMmapOut--;
  42828. pPg->pDirty = pPager->pMmapFreelist;
  42829. pPager->pMmapFreelist = pPg;
  42830. assert( pPager->fd->pMethods->iVersion>=3 );
  42831. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  42832. }
  42833. /*
  42834. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  42835. */
  42836. static void pagerFreeMapHdrs(Pager *pPager){
  42837. PgHdr *p;
  42838. PgHdr *pNext;
  42839. for(p=pPager->pMmapFreelist; p; p=pNext){
  42840. pNext = p->pDirty;
  42841. sqlite3_free(p);
  42842. }
  42843. }
  42844. /*
  42845. ** Shutdown the page cache. Free all memory and close all files.
  42846. **
  42847. ** If a transaction was in progress when this routine is called, that
  42848. ** transaction is rolled back. All outstanding pages are invalidated
  42849. ** and their memory is freed. Any attempt to use a page associated
  42850. ** with this page cache after this function returns will likely
  42851. ** result in a coredump.
  42852. **
  42853. ** This function always succeeds. If a transaction is active an attempt
  42854. ** is made to roll it back. If an error occurs during the rollback
  42855. ** a hot journal may be left in the filesystem but no error is returned
  42856. ** to the caller.
  42857. */
  42858. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  42859. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  42860. assert( assert_pager_state(pPager) );
  42861. disable_simulated_io_errors();
  42862. sqlite3BeginBenignMalloc();
  42863. pagerFreeMapHdrs(pPager);
  42864. /* pPager->errCode = 0; */
  42865. pPager->exclusiveMode = 0;
  42866. #ifndef SQLITE_OMIT_WAL
  42867. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  42868. pPager->pWal = 0;
  42869. #endif
  42870. pager_reset(pPager);
  42871. if( MEMDB ){
  42872. pager_unlock(pPager);
  42873. }else{
  42874. /* If it is open, sync the journal file before calling UnlockAndRollback.
  42875. ** If this is not done, then an unsynced portion of the open journal
  42876. ** file may be played back into the database. If a power failure occurs
  42877. ** while this is happening, the database could become corrupt.
  42878. **
  42879. ** If an error occurs while trying to sync the journal, shift the pager
  42880. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  42881. ** database and close the journal file without attempting to roll it
  42882. ** back or finalize it. The next database user will have to do hot-journal
  42883. ** rollback before accessing the database file.
  42884. */
  42885. if( isOpen(pPager->jfd) ){
  42886. pager_error(pPager, pagerSyncHotJournal(pPager));
  42887. }
  42888. pagerUnlockAndRollback(pPager);
  42889. }
  42890. sqlite3EndBenignMalloc();
  42891. enable_simulated_io_errors();
  42892. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  42893. IOTRACE(("CLOSE %p\n", pPager))
  42894. sqlite3OsClose(pPager->jfd);
  42895. sqlite3OsClose(pPager->fd);
  42896. sqlite3PageFree(pTmp);
  42897. sqlite3PcacheClose(pPager->pPCache);
  42898. #ifdef SQLITE_HAS_CODEC
  42899. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  42900. #endif
  42901. assert( !pPager->aSavepoint && !pPager->pInJournal );
  42902. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  42903. sqlite3_free(pPager);
  42904. return SQLITE_OK;
  42905. }
  42906. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  42907. /*
  42908. ** Return the page number for page pPg.
  42909. */
  42910. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  42911. return pPg->pgno;
  42912. }
  42913. #endif
  42914. /*
  42915. ** Increment the reference count for page pPg.
  42916. */
  42917. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  42918. sqlite3PcacheRef(pPg);
  42919. }
  42920. /*
  42921. ** Sync the journal. In other words, make sure all the pages that have
  42922. ** been written to the journal have actually reached the surface of the
  42923. ** disk and can be restored in the event of a hot-journal rollback.
  42924. **
  42925. ** If the Pager.noSync flag is set, then this function is a no-op.
  42926. ** Otherwise, the actions required depend on the journal-mode and the
  42927. ** device characteristics of the file-system, as follows:
  42928. **
  42929. ** * If the journal file is an in-memory journal file, no action need
  42930. ** be taken.
  42931. **
  42932. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  42933. ** then the nRec field of the most recently written journal header
  42934. ** is updated to contain the number of journal records that have
  42935. ** been written following it. If the pager is operating in full-sync
  42936. ** mode, then the journal file is synced before this field is updated.
  42937. **
  42938. ** * If the device does not support the SEQUENTIAL property, then
  42939. ** journal file is synced.
  42940. **
  42941. ** Or, in pseudo-code:
  42942. **
  42943. ** if( NOT <in-memory journal> ){
  42944. ** if( NOT SAFE_APPEND ){
  42945. ** if( <full-sync mode> ) xSync(<journal file>);
  42946. ** <update nRec field>
  42947. ** }
  42948. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  42949. ** }
  42950. **
  42951. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  42952. ** page currently held in memory before returning SQLITE_OK. If an IO
  42953. ** error is encountered, then the IO error code is returned to the caller.
  42954. */
  42955. static int syncJournal(Pager *pPager, int newHdr){
  42956. int rc; /* Return code */
  42957. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42958. || pPager->eState==PAGER_WRITER_DBMOD
  42959. );
  42960. assert( assert_pager_state(pPager) );
  42961. assert( !pagerUseWal(pPager) );
  42962. rc = sqlite3PagerExclusiveLock(pPager);
  42963. if( rc!=SQLITE_OK ) return rc;
  42964. if( !pPager->noSync ){
  42965. assert( !pPager->tempFile );
  42966. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  42967. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42968. assert( isOpen(pPager->jfd) );
  42969. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42970. /* This block deals with an obscure problem. If the last connection
  42971. ** that wrote to this database was operating in persistent-journal
  42972. ** mode, then the journal file may at this point actually be larger
  42973. ** than Pager.journalOff bytes. If the next thing in the journal
  42974. ** file happens to be a journal-header (written as part of the
  42975. ** previous connection's transaction), and a crash or power-failure
  42976. ** occurs after nRec is updated but before this connection writes
  42977. ** anything else to the journal file (or commits/rolls back its
  42978. ** transaction), then SQLite may become confused when doing the
  42979. ** hot-journal rollback following recovery. It may roll back all
  42980. ** of this connections data, then proceed to rolling back the old,
  42981. ** out-of-date data that follows it. Database corruption.
  42982. **
  42983. ** To work around this, if the journal file does appear to contain
  42984. ** a valid header following Pager.journalOff, then write a 0x00
  42985. ** byte to the start of it to prevent it from being recognized.
  42986. **
  42987. ** Variable iNextHdrOffset is set to the offset at which this
  42988. ** problematic header will occur, if it exists. aMagic is used
  42989. ** as a temporary buffer to inspect the first couple of bytes of
  42990. ** the potential journal header.
  42991. */
  42992. i64 iNextHdrOffset;
  42993. u8 aMagic[8];
  42994. u8 zHeader[sizeof(aJournalMagic)+4];
  42995. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42996. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  42997. iNextHdrOffset = journalHdrOffset(pPager);
  42998. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  42999. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  43000. static const u8 zerobyte = 0;
  43001. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  43002. }
  43003. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43004. return rc;
  43005. }
  43006. /* Write the nRec value into the journal file header. If in
  43007. ** full-synchronous mode, sync the journal first. This ensures that
  43008. ** all data has really hit the disk before nRec is updated to mark
  43009. ** it as a candidate for rollback.
  43010. **
  43011. ** This is not required if the persistent media supports the
  43012. ** SAFE_APPEND property. Because in this case it is not possible
  43013. ** for garbage data to be appended to the file, the nRec field
  43014. ** is populated with 0xFFFFFFFF when the journal header is written
  43015. ** and never needs to be updated.
  43016. */
  43017. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43018. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43019. IOTRACE(("JSYNC %p\n", pPager))
  43020. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  43021. if( rc!=SQLITE_OK ) return rc;
  43022. }
  43023. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  43024. rc = sqlite3OsWrite(
  43025. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  43026. );
  43027. if( rc!=SQLITE_OK ) return rc;
  43028. }
  43029. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43030. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43031. IOTRACE(("JSYNC %p\n", pPager))
  43032. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  43033. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  43034. );
  43035. if( rc!=SQLITE_OK ) return rc;
  43036. }
  43037. pPager->journalHdr = pPager->journalOff;
  43038. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  43039. pPager->nRec = 0;
  43040. rc = writeJournalHdr(pPager);
  43041. if( rc!=SQLITE_OK ) return rc;
  43042. }
  43043. }else{
  43044. pPager->journalHdr = pPager->journalOff;
  43045. }
  43046. }
  43047. /* Unless the pager is in noSync mode, the journal file was just
  43048. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  43049. ** all pages.
  43050. */
  43051. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  43052. pPager->eState = PAGER_WRITER_DBMOD;
  43053. assert( assert_pager_state(pPager) );
  43054. return SQLITE_OK;
  43055. }
  43056. /*
  43057. ** The argument is the first in a linked list of dirty pages connected
  43058. ** by the PgHdr.pDirty pointer. This function writes each one of the
  43059. ** in-memory pages in the list to the database file. The argument may
  43060. ** be NULL, representing an empty list. In this case this function is
  43061. ** a no-op.
  43062. **
  43063. ** The pager must hold at least a RESERVED lock when this function
  43064. ** is called. Before writing anything to the database file, this lock
  43065. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  43066. ** SQLITE_BUSY is returned and no data is written to the database file.
  43067. **
  43068. ** If the pager is a temp-file pager and the actual file-system file
  43069. ** is not yet open, it is created and opened before any data is
  43070. ** written out.
  43071. **
  43072. ** Once the lock has been upgraded and, if necessary, the file opened,
  43073. ** the pages are written out to the database file in list order. Writing
  43074. ** a page is skipped if it meets either of the following criteria:
  43075. **
  43076. ** * The page number is greater than Pager.dbSize, or
  43077. ** * The PGHDR_DONT_WRITE flag is set on the page.
  43078. **
  43079. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  43080. ** is updated accordingly. If page 1 is written out, then the value cached
  43081. ** in Pager.dbFileVers[] is updated to match the new value stored in
  43082. ** the database file.
  43083. **
  43084. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43085. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  43086. ** be obtained, SQLITE_BUSY is returned.
  43087. */
  43088. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  43089. int rc = SQLITE_OK; /* Return code */
  43090. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  43091. assert( !pagerUseWal(pPager) );
  43092. assert( pPager->eState==PAGER_WRITER_DBMOD );
  43093. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43094. /* If the file is a temp-file has not yet been opened, open it now. It
  43095. ** is not possible for rc to be other than SQLITE_OK if this branch
  43096. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  43097. */
  43098. if( !isOpen(pPager->fd) ){
  43099. assert( pPager->tempFile && rc==SQLITE_OK );
  43100. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  43101. }
  43102. /* Before the first write, give the VFS a hint of what the final
  43103. ** file size will be.
  43104. */
  43105. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  43106. if( rc==SQLITE_OK
  43107. && pPager->dbHintSize<pPager->dbSize
  43108. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  43109. ){
  43110. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  43111. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  43112. pPager->dbHintSize = pPager->dbSize;
  43113. }
  43114. while( rc==SQLITE_OK && pList ){
  43115. Pgno pgno = pList->pgno;
  43116. /* If there are dirty pages in the page cache with page numbers greater
  43117. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  43118. ** make the file smaller (presumably by auto-vacuum code). Do not write
  43119. ** any such pages to the file.
  43120. **
  43121. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  43122. ** set (set by sqlite3PagerDontWrite()).
  43123. */
  43124. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  43125. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  43126. char *pData; /* Data to write */
  43127. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  43128. if( pList->pgno==1 ) pager_write_changecounter(pList);
  43129. /* Encode the database */
  43130. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  43131. /* Write out the page data. */
  43132. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  43133. /* If page 1 was just written, update Pager.dbFileVers to match
  43134. ** the value now stored in the database file. If writing this
  43135. ** page caused the database file to grow, update dbFileSize.
  43136. */
  43137. if( pgno==1 ){
  43138. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  43139. }
  43140. if( pgno>pPager->dbFileSize ){
  43141. pPager->dbFileSize = pgno;
  43142. }
  43143. pPager->aStat[PAGER_STAT_WRITE]++;
  43144. /* Update any backup objects copying the contents of this pager. */
  43145. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  43146. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  43147. PAGERID(pPager), pgno, pager_pagehash(pList)));
  43148. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  43149. PAGER_INCR(sqlite3_pager_writedb_count);
  43150. }else{
  43151. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  43152. }
  43153. pager_set_pagehash(pList);
  43154. pList = pList->pDirty;
  43155. }
  43156. return rc;
  43157. }
  43158. /*
  43159. ** Ensure that the sub-journal file is open. If it is already open, this
  43160. ** function is a no-op.
  43161. **
  43162. ** SQLITE_OK is returned if everything goes according to plan. An
  43163. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  43164. ** fails.
  43165. */
  43166. static int openSubJournal(Pager *pPager){
  43167. int rc = SQLITE_OK;
  43168. if( !isOpen(pPager->sjfd) ){
  43169. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  43170. sqlite3MemJournalOpen(pPager->sjfd);
  43171. }else{
  43172. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  43173. }
  43174. }
  43175. return rc;
  43176. }
  43177. /*
  43178. ** Append a record of the current state of page pPg to the sub-journal.
  43179. ** It is the callers responsibility to use subjRequiresPage() to check
  43180. ** that it is really required before calling this function.
  43181. **
  43182. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  43183. ** for all open savepoints before returning.
  43184. **
  43185. ** This function returns SQLITE_OK if everything is successful, an IO
  43186. ** error code if the attempt to write to the sub-journal fails, or
  43187. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  43188. ** bitvec.
  43189. */
  43190. static int subjournalPage(PgHdr *pPg){
  43191. int rc = SQLITE_OK;
  43192. Pager *pPager = pPg->pPager;
  43193. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  43194. /* Open the sub-journal, if it has not already been opened */
  43195. assert( pPager->useJournal );
  43196. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  43197. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  43198. assert( pagerUseWal(pPager)
  43199. || pageInJournal(pPg)
  43200. || pPg->pgno>pPager->dbOrigSize
  43201. );
  43202. rc = openSubJournal(pPager);
  43203. /* If the sub-journal was opened successfully (or was already open),
  43204. ** write the journal record into the file. */
  43205. if( rc==SQLITE_OK ){
  43206. void *pData = pPg->pData;
  43207. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  43208. char *pData2;
  43209. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  43210. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  43211. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  43212. if( rc==SQLITE_OK ){
  43213. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  43214. }
  43215. }
  43216. }
  43217. if( rc==SQLITE_OK ){
  43218. pPager->nSubRec++;
  43219. assert( pPager->nSavepoint>0 );
  43220. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  43221. }
  43222. return rc;
  43223. }
  43224. /*
  43225. ** This function is called by the pcache layer when it has reached some
  43226. ** soft memory limit. The first argument is a pointer to a Pager object
  43227. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  43228. ** database). The second argument is a reference to a page that is
  43229. ** currently dirty but has no outstanding references. The page
  43230. ** is always associated with the Pager object passed as the first
  43231. ** argument.
  43232. **
  43233. ** The job of this function is to make pPg clean by writing its contents
  43234. ** out to the database file, if possible. This may involve syncing the
  43235. ** journal file.
  43236. **
  43237. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  43238. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  43239. ** page clean, the IO error code is returned. If the page cannot be
  43240. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  43241. ** is returned by sqlite3PcacheMakeClean() is not called.
  43242. */
  43243. static int pagerStress(void *p, PgHdr *pPg){
  43244. Pager *pPager = (Pager *)p;
  43245. int rc = SQLITE_OK;
  43246. assert( pPg->pPager==pPager );
  43247. assert( pPg->flags&PGHDR_DIRTY );
  43248. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  43249. ** journal (and adding a new header) is not allowed. This occurs
  43250. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  43251. ** pages belonging to the same sector.
  43252. **
  43253. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  43254. ** regardless of whether or not a sync is required. This is set during
  43255. ** a rollback or by user request, respectively.
  43256. **
  43257. ** Spilling is also prohibited when in an error state since that could
  43258. ** lead to database corruption. In the current implementaton it
  43259. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  43260. ** while in the error state, hence it is impossible for this routine to
  43261. ** be called in the error state. Nevertheless, we include a NEVER()
  43262. ** test for the error state as a safeguard against future changes.
  43263. */
  43264. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  43265. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  43266. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  43267. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  43268. if( pPager->doNotSpill
  43269. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  43270. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  43271. ){
  43272. return SQLITE_OK;
  43273. }
  43274. pPg->pDirty = 0;
  43275. if( pagerUseWal(pPager) ){
  43276. /* Write a single frame for this page to the log. */
  43277. if( subjRequiresPage(pPg) ){
  43278. rc = subjournalPage(pPg);
  43279. }
  43280. if( rc==SQLITE_OK ){
  43281. rc = pagerWalFrames(pPager, pPg, 0, 0);
  43282. }
  43283. }else{
  43284. /* Sync the journal file if required. */
  43285. if( pPg->flags&PGHDR_NEED_SYNC
  43286. || pPager->eState==PAGER_WRITER_CACHEMOD
  43287. ){
  43288. rc = syncJournal(pPager, 1);
  43289. }
  43290. /* If the page number of this page is larger than the current size of
  43291. ** the database image, it may need to be written to the sub-journal.
  43292. ** This is because the call to pager_write_pagelist() below will not
  43293. ** actually write data to the file in this case.
  43294. **
  43295. ** Consider the following sequence of events:
  43296. **
  43297. ** BEGIN;
  43298. ** <journal page X>
  43299. ** <modify page X>
  43300. ** SAVEPOINT sp;
  43301. ** <shrink database file to Y pages>
  43302. ** pagerStress(page X)
  43303. ** ROLLBACK TO sp;
  43304. **
  43305. ** If (X>Y), then when pagerStress is called page X will not be written
  43306. ** out to the database file, but will be dropped from the cache. Then,
  43307. ** following the "ROLLBACK TO sp" statement, reading page X will read
  43308. ** data from the database file. This will be the copy of page X as it
  43309. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  43310. ** was executed.
  43311. **
  43312. ** The solution is to write the current data for page X into the
  43313. ** sub-journal file now (if it is not already there), so that it will
  43314. ** be restored to its current value when the "ROLLBACK TO sp" is
  43315. ** executed.
  43316. */
  43317. if( NEVER(
  43318. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  43319. ) ){
  43320. rc = subjournalPage(pPg);
  43321. }
  43322. /* Write the contents of the page out to the database file. */
  43323. if( rc==SQLITE_OK ){
  43324. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  43325. rc = pager_write_pagelist(pPager, pPg);
  43326. }
  43327. }
  43328. /* Mark the page as clean. */
  43329. if( rc==SQLITE_OK ){
  43330. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  43331. sqlite3PcacheMakeClean(pPg);
  43332. }
  43333. return pager_error(pPager, rc);
  43334. }
  43335. /*
  43336. ** Allocate and initialize a new Pager object and put a pointer to it
  43337. ** in *ppPager. The pager should eventually be freed by passing it
  43338. ** to sqlite3PagerClose().
  43339. **
  43340. ** The zFilename argument is the path to the database file to open.
  43341. ** If zFilename is NULL then a randomly-named temporary file is created
  43342. ** and used as the file to be cached. Temporary files are be deleted
  43343. ** automatically when they are closed. If zFilename is ":memory:" then
  43344. ** all information is held in cache. It is never written to disk.
  43345. ** This can be used to implement an in-memory database.
  43346. **
  43347. ** The nExtra parameter specifies the number of bytes of space allocated
  43348. ** along with each page reference. This space is available to the user
  43349. ** via the sqlite3PagerGetExtra() API.
  43350. **
  43351. ** The flags argument is used to specify properties that affect the
  43352. ** operation of the pager. It should be passed some bitwise combination
  43353. ** of the PAGER_* flags.
  43354. **
  43355. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  43356. ** of the xOpen() method of the supplied VFS when opening files.
  43357. **
  43358. ** If the pager object is allocated and the specified file opened
  43359. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  43360. ** the new pager object. If an error occurs, *ppPager is set to NULL
  43361. ** and error code returned. This function may return SQLITE_NOMEM
  43362. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  43363. ** various SQLITE_IO_XXX errors.
  43364. */
  43365. SQLITE_PRIVATE int sqlite3PagerOpen(
  43366. sqlite3_vfs *pVfs, /* The virtual file system to use */
  43367. Pager **ppPager, /* OUT: Return the Pager structure here */
  43368. const char *zFilename, /* Name of the database file to open */
  43369. int nExtra, /* Extra bytes append to each in-memory page */
  43370. int flags, /* flags controlling this file */
  43371. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  43372. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  43373. ){
  43374. u8 *pPtr;
  43375. Pager *pPager = 0; /* Pager object to allocate and return */
  43376. int rc = SQLITE_OK; /* Return code */
  43377. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  43378. int memDb = 0; /* True if this is an in-memory file */
  43379. int readOnly = 0; /* True if this is a read-only file */
  43380. int journalFileSize; /* Bytes to allocate for each journal fd */
  43381. char *zPathname = 0; /* Full path to database file */
  43382. int nPathname = 0; /* Number of bytes in zPathname */
  43383. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  43384. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  43385. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  43386. const char *zUri = 0; /* URI args to copy */
  43387. int nUri = 0; /* Number of bytes of URI args at *zUri */
  43388. /* Figure out how much space is required for each journal file-handle
  43389. ** (there are two of them, the main journal and the sub-journal). This
  43390. ** is the maximum space required for an in-memory journal file handle
  43391. ** and a regular journal file-handle. Note that a "regular journal-handle"
  43392. ** may be a wrapper capable of caching the first portion of the journal
  43393. ** file in memory to implement the atomic-write optimization (see
  43394. ** source file journal.c).
  43395. */
  43396. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  43397. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  43398. }else{
  43399. journalFileSize = ROUND8(sqlite3MemJournalSize());
  43400. }
  43401. /* Set the output variable to NULL in case an error occurs. */
  43402. *ppPager = 0;
  43403. #ifndef SQLITE_OMIT_MEMORYDB
  43404. if( flags & PAGER_MEMORY ){
  43405. memDb = 1;
  43406. if( zFilename && zFilename[0] ){
  43407. zPathname = sqlite3DbStrDup(0, zFilename);
  43408. if( zPathname==0 ) return SQLITE_NOMEM;
  43409. nPathname = sqlite3Strlen30(zPathname);
  43410. zFilename = 0;
  43411. }
  43412. }
  43413. #endif
  43414. /* Compute and store the full pathname in an allocated buffer pointed
  43415. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  43416. ** leave both nPathname and zPathname set to 0.
  43417. */
  43418. if( zFilename && zFilename[0] ){
  43419. const char *z;
  43420. nPathname = pVfs->mxPathname+1;
  43421. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  43422. if( zPathname==0 ){
  43423. return SQLITE_NOMEM;
  43424. }
  43425. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  43426. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  43427. nPathname = sqlite3Strlen30(zPathname);
  43428. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  43429. while( *z ){
  43430. z += sqlite3Strlen30(z)+1;
  43431. z += sqlite3Strlen30(z)+1;
  43432. }
  43433. nUri = (int)(&z[1] - zUri);
  43434. assert( nUri>=0 );
  43435. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  43436. /* This branch is taken when the journal path required by
  43437. ** the database being opened will be more than pVfs->mxPathname
  43438. ** bytes in length. This means the database cannot be opened,
  43439. ** as it will not be possible to open the journal file or even
  43440. ** check for a hot-journal before reading.
  43441. */
  43442. rc = SQLITE_CANTOPEN_BKPT;
  43443. }
  43444. if( rc!=SQLITE_OK ){
  43445. sqlite3DbFree(0, zPathname);
  43446. return rc;
  43447. }
  43448. }
  43449. /* Allocate memory for the Pager structure, PCache object, the
  43450. ** three file descriptors, the database file name and the journal
  43451. ** file name. The layout in memory is as follows:
  43452. **
  43453. ** Pager object (sizeof(Pager) bytes)
  43454. ** PCache object (sqlite3PcacheSize() bytes)
  43455. ** Database file handle (pVfs->szOsFile bytes)
  43456. ** Sub-journal file handle (journalFileSize bytes)
  43457. ** Main journal file handle (journalFileSize bytes)
  43458. ** Database file name (nPathname+1 bytes)
  43459. ** Journal file name (nPathname+8+1 bytes)
  43460. */
  43461. pPtr = (u8 *)sqlite3MallocZero(
  43462. ROUND8(sizeof(*pPager)) + /* Pager structure */
  43463. ROUND8(pcacheSize) + /* PCache object */
  43464. ROUND8(pVfs->szOsFile) + /* The main db file */
  43465. journalFileSize * 2 + /* The two journal files */
  43466. nPathname + 1 + nUri + /* zFilename */
  43467. nPathname + 8 + 2 /* zJournal */
  43468. #ifndef SQLITE_OMIT_WAL
  43469. + nPathname + 4 + 2 /* zWal */
  43470. #endif
  43471. );
  43472. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  43473. if( !pPtr ){
  43474. sqlite3DbFree(0, zPathname);
  43475. return SQLITE_NOMEM;
  43476. }
  43477. pPager = (Pager*)(pPtr);
  43478. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  43479. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  43480. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  43481. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  43482. pPager->zFilename = (char*)(pPtr += journalFileSize);
  43483. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  43484. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  43485. if( zPathname ){
  43486. assert( nPathname>0 );
  43487. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  43488. memcpy(pPager->zFilename, zPathname, nPathname);
  43489. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  43490. memcpy(pPager->zJournal, zPathname, nPathname);
  43491. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  43492. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  43493. #ifndef SQLITE_OMIT_WAL
  43494. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  43495. memcpy(pPager->zWal, zPathname, nPathname);
  43496. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  43497. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  43498. #endif
  43499. sqlite3DbFree(0, zPathname);
  43500. }
  43501. pPager->pVfs = pVfs;
  43502. pPager->vfsFlags = vfsFlags;
  43503. /* Open the pager file.
  43504. */
  43505. if( zFilename && zFilename[0] ){
  43506. int fout = 0; /* VFS flags returned by xOpen() */
  43507. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  43508. assert( !memDb );
  43509. readOnly = (fout&SQLITE_OPEN_READONLY);
  43510. /* If the file was successfully opened for read/write access,
  43511. ** choose a default page size in case we have to create the
  43512. ** database file. The default page size is the maximum of:
  43513. **
  43514. ** + SQLITE_DEFAULT_PAGE_SIZE,
  43515. ** + The value returned by sqlite3OsSectorSize()
  43516. ** + The largest page size that can be written atomically.
  43517. */
  43518. if( rc==SQLITE_OK && !readOnly ){
  43519. setSectorSize(pPager);
  43520. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  43521. if( szPageDflt<pPager->sectorSize ){
  43522. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  43523. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  43524. }else{
  43525. szPageDflt = (u32)pPager->sectorSize;
  43526. }
  43527. }
  43528. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43529. {
  43530. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  43531. int ii;
  43532. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  43533. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  43534. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  43535. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  43536. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  43537. szPageDflt = ii;
  43538. }
  43539. }
  43540. }
  43541. #endif
  43542. }
  43543. }else{
  43544. /* If a temporary file is requested, it is not opened immediately.
  43545. ** In this case we accept the default page size and delay actually
  43546. ** opening the file until the first call to OsWrite().
  43547. **
  43548. ** This branch is also run for an in-memory database. An in-memory
  43549. ** database is the same as a temp-file that is never written out to
  43550. ** disk and uses an in-memory rollback journal.
  43551. */
  43552. tempFile = 1;
  43553. pPager->eState = PAGER_READER;
  43554. pPager->eLock = EXCLUSIVE_LOCK;
  43555. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  43556. }
  43557. /* The following call to PagerSetPagesize() serves to set the value of
  43558. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  43559. */
  43560. if( rc==SQLITE_OK ){
  43561. assert( pPager->memDb==0 );
  43562. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  43563. testcase( rc!=SQLITE_OK );
  43564. }
  43565. /* If an error occurred in either of the blocks above, free the
  43566. ** Pager structure and close the file.
  43567. */
  43568. if( rc!=SQLITE_OK ){
  43569. assert( !pPager->pTmpSpace );
  43570. sqlite3OsClose(pPager->fd);
  43571. sqlite3_free(pPager);
  43572. return rc;
  43573. }
  43574. /* Initialize the PCache object. */
  43575. assert( nExtra<1000 );
  43576. nExtra = ROUND8(nExtra);
  43577. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  43578. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  43579. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  43580. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  43581. pPager->useJournal = (u8)useJournal;
  43582. /* pPager->stmtOpen = 0; */
  43583. /* pPager->stmtInUse = 0; */
  43584. /* pPager->nRef = 0; */
  43585. /* pPager->stmtSize = 0; */
  43586. /* pPager->stmtJSize = 0; */
  43587. /* pPager->nPage = 0; */
  43588. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  43589. /* pPager->state = PAGER_UNLOCK; */
  43590. #if 0
  43591. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  43592. #endif
  43593. /* pPager->errMask = 0; */
  43594. pPager->tempFile = (u8)tempFile;
  43595. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  43596. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  43597. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  43598. pPager->exclusiveMode = (u8)tempFile;
  43599. pPager->changeCountDone = pPager->tempFile;
  43600. pPager->memDb = (u8)memDb;
  43601. pPager->readOnly = (u8)readOnly;
  43602. assert( useJournal || pPager->tempFile );
  43603. pPager->noSync = pPager->tempFile;
  43604. if( pPager->noSync ){
  43605. assert( pPager->fullSync==0 );
  43606. assert( pPager->syncFlags==0 );
  43607. assert( pPager->walSyncFlags==0 );
  43608. assert( pPager->ckptSyncFlags==0 );
  43609. }else{
  43610. pPager->fullSync = 1;
  43611. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43612. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  43613. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  43614. }
  43615. /* pPager->pFirst = 0; */
  43616. /* pPager->pFirstSynced = 0; */
  43617. /* pPager->pLast = 0; */
  43618. pPager->nExtra = (u16)nExtra;
  43619. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  43620. assert( isOpen(pPager->fd) || tempFile );
  43621. setSectorSize(pPager);
  43622. if( !useJournal ){
  43623. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  43624. }else if( memDb ){
  43625. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  43626. }
  43627. /* pPager->xBusyHandler = 0; */
  43628. /* pPager->pBusyHandlerArg = 0; */
  43629. pPager->xReiniter = xReinit;
  43630. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  43631. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  43632. *ppPager = pPager;
  43633. return SQLITE_OK;
  43634. }
  43635. /*
  43636. ** This function is called after transitioning from PAGER_UNLOCK to
  43637. ** PAGER_SHARED state. It tests if there is a hot journal present in
  43638. ** the file-system for the given pager. A hot journal is one that
  43639. ** needs to be played back. According to this function, a hot-journal
  43640. ** file exists if the following criteria are met:
  43641. **
  43642. ** * The journal file exists in the file system, and
  43643. ** * No process holds a RESERVED or greater lock on the database file, and
  43644. ** * The database file itself is greater than 0 bytes in size, and
  43645. ** * The first byte of the journal file exists and is not 0x00.
  43646. **
  43647. ** If the current size of the database file is 0 but a journal file
  43648. ** exists, that is probably an old journal left over from a prior
  43649. ** database with the same name. In this case the journal file is
  43650. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  43651. ** is returned.
  43652. **
  43653. ** This routine does not check if there is a master journal filename
  43654. ** at the end of the file. If there is, and that master journal file
  43655. ** does not exist, then the journal file is not really hot. In this
  43656. ** case this routine will return a false-positive. The pager_playback()
  43657. ** routine will discover that the journal file is not really hot and
  43658. ** will not roll it back.
  43659. **
  43660. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  43661. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  43662. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  43663. ** to determine whether or not a hot-journal file exists, the IO error
  43664. ** code is returned and the value of *pExists is undefined.
  43665. */
  43666. static int hasHotJournal(Pager *pPager, int *pExists){
  43667. sqlite3_vfs * const pVfs = pPager->pVfs;
  43668. int rc = SQLITE_OK; /* Return code */
  43669. int exists = 1; /* True if a journal file is present */
  43670. int jrnlOpen = !!isOpen(pPager->jfd);
  43671. assert( pPager->useJournal );
  43672. assert( isOpen(pPager->fd) );
  43673. assert( pPager->eState==PAGER_OPEN );
  43674. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  43675. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  43676. ));
  43677. *pExists = 0;
  43678. if( !jrnlOpen ){
  43679. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  43680. }
  43681. if( rc==SQLITE_OK && exists ){
  43682. int locked = 0; /* True if some process holds a RESERVED lock */
  43683. /* Race condition here: Another process might have been holding the
  43684. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  43685. ** call above, but then delete the journal and drop the lock before
  43686. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  43687. ** is the case, this routine might think there is a hot journal when
  43688. ** in fact there is none. This results in a false-positive which will
  43689. ** be dealt with by the playback routine. Ticket #3883.
  43690. */
  43691. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  43692. if( rc==SQLITE_OK && !locked ){
  43693. Pgno nPage; /* Number of pages in database file */
  43694. /* Check the size of the database file. If it consists of 0 pages,
  43695. ** then delete the journal file. See the header comment above for
  43696. ** the reasoning here. Delete the obsolete journal file under
  43697. ** a RESERVED lock to avoid race conditions and to avoid violating
  43698. ** [H33020].
  43699. */
  43700. rc = pagerPagecount(pPager, &nPage);
  43701. if( rc==SQLITE_OK ){
  43702. if( nPage==0 ){
  43703. sqlite3BeginBenignMalloc();
  43704. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  43705. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  43706. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  43707. }
  43708. sqlite3EndBenignMalloc();
  43709. }else{
  43710. /* The journal file exists and no other connection has a reserved
  43711. ** or greater lock on the database file. Now check that there is
  43712. ** at least one non-zero bytes at the start of the journal file.
  43713. ** If there is, then we consider this journal to be hot. If not,
  43714. ** it can be ignored.
  43715. */
  43716. if( !jrnlOpen ){
  43717. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  43718. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  43719. }
  43720. if( rc==SQLITE_OK ){
  43721. u8 first = 0;
  43722. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  43723. if( rc==SQLITE_IOERR_SHORT_READ ){
  43724. rc = SQLITE_OK;
  43725. }
  43726. if( !jrnlOpen ){
  43727. sqlite3OsClose(pPager->jfd);
  43728. }
  43729. *pExists = (first!=0);
  43730. }else if( rc==SQLITE_CANTOPEN ){
  43731. /* If we cannot open the rollback journal file in order to see if
  43732. ** its has a zero header, that might be due to an I/O error, or
  43733. ** it might be due to the race condition described above and in
  43734. ** ticket #3883. Either way, assume that the journal is hot.
  43735. ** This might be a false positive. But if it is, then the
  43736. ** automatic journal playback and recovery mechanism will deal
  43737. ** with it under an EXCLUSIVE lock where we do not need to
  43738. ** worry so much with race conditions.
  43739. */
  43740. *pExists = 1;
  43741. rc = SQLITE_OK;
  43742. }
  43743. }
  43744. }
  43745. }
  43746. }
  43747. return rc;
  43748. }
  43749. /*
  43750. ** This function is called to obtain a shared lock on the database file.
  43751. ** It is illegal to call sqlite3PagerAcquire() until after this function
  43752. ** has been successfully called. If a shared-lock is already held when
  43753. ** this function is called, it is a no-op.
  43754. **
  43755. ** The following operations are also performed by this function.
  43756. **
  43757. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  43758. ** on the database file), then an attempt is made to obtain a
  43759. ** SHARED lock on the database file. Immediately after obtaining
  43760. ** the SHARED lock, the file-system is checked for a hot-journal,
  43761. ** which is played back if present. Following any hot-journal
  43762. ** rollback, the contents of the cache are validated by checking
  43763. ** the 'change-counter' field of the database file header and
  43764. ** discarded if they are found to be invalid.
  43765. **
  43766. ** 2) If the pager is running in exclusive-mode, and there are currently
  43767. ** no outstanding references to any pages, and is in the error state,
  43768. ** then an attempt is made to clear the error state by discarding
  43769. ** the contents of the page cache and rolling back any open journal
  43770. ** file.
  43771. **
  43772. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43773. ** occurs while locking the database, checking for a hot-journal file or
  43774. ** rolling back a journal file, the IO error code is returned.
  43775. */
  43776. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  43777. int rc = SQLITE_OK; /* Return code */
  43778. /* This routine is only called from b-tree and only when there are no
  43779. ** outstanding pages. This implies that the pager state should either
  43780. ** be OPEN or READER. READER is only possible if the pager is or was in
  43781. ** exclusive access mode.
  43782. */
  43783. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  43784. assert( assert_pager_state(pPager) );
  43785. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  43786. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  43787. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  43788. int bHotJournal = 1; /* True if there exists a hot journal-file */
  43789. assert( !MEMDB );
  43790. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  43791. if( rc!=SQLITE_OK ){
  43792. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  43793. goto failed;
  43794. }
  43795. /* If a journal file exists, and there is no RESERVED lock on the
  43796. ** database file, then it either needs to be played back or deleted.
  43797. */
  43798. if( pPager->eLock<=SHARED_LOCK ){
  43799. rc = hasHotJournal(pPager, &bHotJournal);
  43800. }
  43801. if( rc!=SQLITE_OK ){
  43802. goto failed;
  43803. }
  43804. if( bHotJournal ){
  43805. if( pPager->readOnly ){
  43806. rc = SQLITE_READONLY_ROLLBACK;
  43807. goto failed;
  43808. }
  43809. /* Get an EXCLUSIVE lock on the database file. At this point it is
  43810. ** important that a RESERVED lock is not obtained on the way to the
  43811. ** EXCLUSIVE lock. If it were, another process might open the
  43812. ** database file, detect the RESERVED lock, and conclude that the
  43813. ** database is safe to read while this process is still rolling the
  43814. ** hot-journal back.
  43815. **
  43816. ** Because the intermediate RESERVED lock is not requested, any
  43817. ** other process attempting to access the database file will get to
  43818. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  43819. ** on the database file.
  43820. **
  43821. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  43822. ** downgraded to SHARED_LOCK before this function returns.
  43823. */
  43824. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  43825. if( rc!=SQLITE_OK ){
  43826. goto failed;
  43827. }
  43828. /* If it is not already open and the file exists on disk, open the
  43829. ** journal for read/write access. Write access is required because
  43830. ** in exclusive-access mode the file descriptor will be kept open
  43831. ** and possibly used for a transaction later on. Also, write-access
  43832. ** is usually required to finalize the journal in journal_mode=persist
  43833. ** mode (and also for journal_mode=truncate on some systems).
  43834. **
  43835. ** If the journal does not exist, it usually means that some
  43836. ** other connection managed to get in and roll it back before
  43837. ** this connection obtained the exclusive lock above. Or, it
  43838. ** may mean that the pager was in the error-state when this
  43839. ** function was called and the journal file does not exist.
  43840. */
  43841. if( !isOpen(pPager->jfd) ){
  43842. sqlite3_vfs * const pVfs = pPager->pVfs;
  43843. int bExists; /* True if journal file exists */
  43844. rc = sqlite3OsAccess(
  43845. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  43846. if( rc==SQLITE_OK && bExists ){
  43847. int fout = 0;
  43848. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  43849. assert( !pPager->tempFile );
  43850. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  43851. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  43852. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  43853. rc = SQLITE_CANTOPEN_BKPT;
  43854. sqlite3OsClose(pPager->jfd);
  43855. }
  43856. }
  43857. }
  43858. /* Playback and delete the journal. Drop the database write
  43859. ** lock and reacquire the read lock. Purge the cache before
  43860. ** playing back the hot-journal so that we don't end up with
  43861. ** an inconsistent cache. Sync the hot journal before playing
  43862. ** it back since the process that crashed and left the hot journal
  43863. ** probably did not sync it and we are required to always sync
  43864. ** the journal before playing it back.
  43865. */
  43866. if( isOpen(pPager->jfd) ){
  43867. assert( rc==SQLITE_OK );
  43868. rc = pagerSyncHotJournal(pPager);
  43869. if( rc==SQLITE_OK ){
  43870. rc = pager_playback(pPager, 1);
  43871. pPager->eState = PAGER_OPEN;
  43872. }
  43873. }else if( !pPager->exclusiveMode ){
  43874. pagerUnlockDb(pPager, SHARED_LOCK);
  43875. }
  43876. if( rc!=SQLITE_OK ){
  43877. /* This branch is taken if an error occurs while trying to open
  43878. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  43879. ** pager_unlock() routine will be called before returning to unlock
  43880. ** the file. If the unlock attempt fails, then Pager.eLock must be
  43881. ** set to UNKNOWN_LOCK (see the comment above the #define for
  43882. ** UNKNOWN_LOCK above for an explanation).
  43883. **
  43884. ** In order to get pager_unlock() to do this, set Pager.eState to
  43885. ** PAGER_ERROR now. This is not actually counted as a transition
  43886. ** to ERROR state in the state diagram at the top of this file,
  43887. ** since we know that the same call to pager_unlock() will very
  43888. ** shortly transition the pager object to the OPEN state. Calling
  43889. ** assert_pager_state() would fail now, as it should not be possible
  43890. ** to be in ERROR state when there are zero outstanding page
  43891. ** references.
  43892. */
  43893. pager_error(pPager, rc);
  43894. goto failed;
  43895. }
  43896. assert( pPager->eState==PAGER_OPEN );
  43897. assert( (pPager->eLock==SHARED_LOCK)
  43898. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  43899. );
  43900. }
  43901. if( !pPager->tempFile && (
  43902. pPager->pBackup
  43903. || sqlite3PcachePagecount(pPager->pPCache)>0
  43904. || USEFETCH(pPager)
  43905. )){
  43906. /* The shared-lock has just been acquired on the database file
  43907. ** and there are already pages in the cache (from a previous
  43908. ** read or write transaction). Check to see if the database
  43909. ** has been modified. If the database has changed, flush the
  43910. ** cache.
  43911. **
  43912. ** Database changes is detected by looking at 15 bytes beginning
  43913. ** at offset 24 into the file. The first 4 of these 16 bytes are
  43914. ** a 32-bit counter that is incremented with each change. The
  43915. ** other bytes change randomly with each file change when
  43916. ** a codec is in use.
  43917. **
  43918. ** There is a vanishingly small chance that a change will not be
  43919. ** detected. The chance of an undetected change is so small that
  43920. ** it can be neglected.
  43921. */
  43922. Pgno nPage = 0;
  43923. char dbFileVers[sizeof(pPager->dbFileVers)];
  43924. rc = pagerPagecount(pPager, &nPage);
  43925. if( rc ) goto failed;
  43926. if( nPage>0 ){
  43927. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  43928. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  43929. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43930. goto failed;
  43931. }
  43932. }else{
  43933. memset(dbFileVers, 0, sizeof(dbFileVers));
  43934. }
  43935. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  43936. pager_reset(pPager);
  43937. /* Unmap the database file. It is possible that external processes
  43938. ** may have truncated the database file and then extended it back
  43939. ** to its original size while this process was not holding a lock.
  43940. ** In this case there may exist a Pager.pMap mapping that appears
  43941. ** to be the right size but is not actually valid. Avoid this
  43942. ** possibility by unmapping the db here. */
  43943. if( USEFETCH(pPager) ){
  43944. sqlite3OsUnfetch(pPager->fd, 0, 0);
  43945. }
  43946. }
  43947. }
  43948. /* If there is a WAL file in the file-system, open this database in WAL
  43949. ** mode. Otherwise, the following function call is a no-op.
  43950. */
  43951. rc = pagerOpenWalIfPresent(pPager);
  43952. #ifndef SQLITE_OMIT_WAL
  43953. assert( pPager->pWal==0 || rc==SQLITE_OK );
  43954. #endif
  43955. }
  43956. if( pagerUseWal(pPager) ){
  43957. assert( rc==SQLITE_OK );
  43958. rc = pagerBeginReadTransaction(pPager);
  43959. }
  43960. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  43961. rc = pagerPagecount(pPager, &pPager->dbSize);
  43962. }
  43963. failed:
  43964. if( rc!=SQLITE_OK ){
  43965. assert( !MEMDB );
  43966. pager_unlock(pPager);
  43967. assert( pPager->eState==PAGER_OPEN );
  43968. }else{
  43969. pPager->eState = PAGER_READER;
  43970. }
  43971. return rc;
  43972. }
  43973. /*
  43974. ** If the reference count has reached zero, rollback any active
  43975. ** transaction and unlock the pager.
  43976. **
  43977. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  43978. ** the rollback journal, the unlock is not performed and there is
  43979. ** nothing to rollback, so this routine is a no-op.
  43980. */
  43981. static void pagerUnlockIfUnused(Pager *pPager){
  43982. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  43983. pagerUnlockAndRollback(pPager);
  43984. }
  43985. }
  43986. /*
  43987. ** Acquire a reference to page number pgno in pager pPager (a page
  43988. ** reference has type DbPage*). If the requested reference is
  43989. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  43990. **
  43991. ** If the requested page is already in the cache, it is returned.
  43992. ** Otherwise, a new page object is allocated and populated with data
  43993. ** read from the database file. In some cases, the pcache module may
  43994. ** choose not to allocate a new page object and may reuse an existing
  43995. ** object with no outstanding references.
  43996. **
  43997. ** The extra data appended to a page is always initialized to zeros the
  43998. ** first time a page is loaded into memory. If the page requested is
  43999. ** already in the cache when this function is called, then the extra
  44000. ** data is left as it was when the page object was last used.
  44001. **
  44002. ** If the database image is smaller than the requested page or if a
  44003. ** non-zero value is passed as the noContent parameter and the
  44004. ** requested page is not already stored in the cache, then no
  44005. ** actual disk read occurs. In this case the memory image of the
  44006. ** page is initialized to all zeros.
  44007. **
  44008. ** If noContent is true, it means that we do not care about the contents
  44009. ** of the page. This occurs in two scenarios:
  44010. **
  44011. ** a) When reading a free-list leaf page from the database, and
  44012. **
  44013. ** b) When a savepoint is being rolled back and we need to load
  44014. ** a new page into the cache to be filled with the data read
  44015. ** from the savepoint journal.
  44016. **
  44017. ** If noContent is true, then the data returned is zeroed instead of
  44018. ** being read from the database. Additionally, the bits corresponding
  44019. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  44020. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  44021. ** savepoints are set. This means if the page is made writable at any
  44022. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  44023. ** will not be journaled. This saves IO.
  44024. **
  44025. ** The acquisition might fail for several reasons. In all cases,
  44026. ** an appropriate error code is returned and *ppPage is set to NULL.
  44027. **
  44028. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  44029. ** to find a page in the in-memory cache first. If the page is not already
  44030. ** in memory, this routine goes to disk to read it in whereas Lookup()
  44031. ** just returns 0. This routine acquires a read-lock the first time it
  44032. ** has to go to disk, and could also playback an old journal if necessary.
  44033. ** Since Lookup() never goes to disk, it never has to deal with locks
  44034. ** or journal files.
  44035. */
  44036. SQLITE_PRIVATE int sqlite3PagerAcquire(
  44037. Pager *pPager, /* The pager open on the database file */
  44038. Pgno pgno, /* Page number to fetch */
  44039. DbPage **ppPage, /* Write a pointer to the page here */
  44040. int flags /* PAGER_GET_XXX flags */
  44041. ){
  44042. int rc = SQLITE_OK;
  44043. PgHdr *pPg = 0;
  44044. u32 iFrame = 0; /* Frame to read from WAL file */
  44045. const int noContent = (flags & PAGER_GET_NOCONTENT);
  44046. /* It is acceptable to use a read-only (mmap) page for any page except
  44047. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  44048. ** flag was specified by the caller. And so long as the db is not a
  44049. ** temporary or in-memory database. */
  44050. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  44051. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  44052. #ifdef SQLITE_HAS_CODEC
  44053. && pPager->xCodec==0
  44054. #endif
  44055. );
  44056. assert( pPager->eState>=PAGER_READER );
  44057. assert( assert_pager_state(pPager) );
  44058. assert( noContent==0 || bMmapOk==0 );
  44059. if( pgno==0 ){
  44060. return SQLITE_CORRUPT_BKPT;
  44061. }
  44062. /* If the pager is in the error state, return an error immediately.
  44063. ** Otherwise, request the page from the PCache layer. */
  44064. if( pPager->errCode!=SQLITE_OK ){
  44065. rc = pPager->errCode;
  44066. }else{
  44067. if( bMmapOk && pagerUseWal(pPager) ){
  44068. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44069. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44070. }
  44071. if( iFrame==0 && bMmapOk ){
  44072. void *pData = 0;
  44073. rc = sqlite3OsFetch(pPager->fd,
  44074. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  44075. );
  44076. if( rc==SQLITE_OK && pData ){
  44077. if( pPager->eState>PAGER_READER ){
  44078. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  44079. }
  44080. if( pPg==0 ){
  44081. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  44082. }else{
  44083. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  44084. }
  44085. if( pPg ){
  44086. assert( rc==SQLITE_OK );
  44087. *ppPage = pPg;
  44088. return SQLITE_OK;
  44089. }
  44090. }
  44091. if( rc!=SQLITE_OK ){
  44092. goto pager_acquire_err;
  44093. }
  44094. }
  44095. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  44096. }
  44097. if( rc!=SQLITE_OK ){
  44098. /* Either the call to sqlite3PcacheFetch() returned an error or the
  44099. ** pager was already in the error-state when this function was called.
  44100. ** Set pPg to 0 and jump to the exception handler. */
  44101. pPg = 0;
  44102. goto pager_acquire_err;
  44103. }
  44104. assert( (*ppPage)->pgno==pgno );
  44105. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  44106. if( (*ppPage)->pPager && !noContent ){
  44107. /* In this case the pcache already contains an initialized copy of
  44108. ** the page. Return without further ado. */
  44109. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  44110. pPager->aStat[PAGER_STAT_HIT]++;
  44111. return SQLITE_OK;
  44112. }else{
  44113. /* The pager cache has created a new page. Its content needs to
  44114. ** be initialized. */
  44115. pPg = *ppPage;
  44116. pPg->pPager = pPager;
  44117. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  44118. ** number greater than this, or the unused locking-page, is requested. */
  44119. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  44120. rc = SQLITE_CORRUPT_BKPT;
  44121. goto pager_acquire_err;
  44122. }
  44123. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  44124. if( pgno>pPager->mxPgno ){
  44125. rc = SQLITE_FULL;
  44126. goto pager_acquire_err;
  44127. }
  44128. if( noContent ){
  44129. /* Failure to set the bits in the InJournal bit-vectors is benign.
  44130. ** It merely means that we might do some extra work to journal a
  44131. ** page that does not need to be journaled. Nevertheless, be sure
  44132. ** to test the case where a malloc error occurs while trying to set
  44133. ** a bit in a bit vector.
  44134. */
  44135. sqlite3BeginBenignMalloc();
  44136. if( pgno<=pPager->dbOrigSize ){
  44137. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  44138. testcase( rc==SQLITE_NOMEM );
  44139. }
  44140. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  44141. testcase( rc==SQLITE_NOMEM );
  44142. sqlite3EndBenignMalloc();
  44143. }
  44144. memset(pPg->pData, 0, pPager->pageSize);
  44145. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  44146. }else{
  44147. if( pagerUseWal(pPager) && bMmapOk==0 ){
  44148. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44149. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44150. }
  44151. assert( pPg->pPager==pPager );
  44152. pPager->aStat[PAGER_STAT_MISS]++;
  44153. rc = readDbPage(pPg, iFrame);
  44154. if( rc!=SQLITE_OK ){
  44155. goto pager_acquire_err;
  44156. }
  44157. }
  44158. pager_set_pagehash(pPg);
  44159. }
  44160. return SQLITE_OK;
  44161. pager_acquire_err:
  44162. assert( rc!=SQLITE_OK );
  44163. if( pPg ){
  44164. sqlite3PcacheDrop(pPg);
  44165. }
  44166. pagerUnlockIfUnused(pPager);
  44167. *ppPage = 0;
  44168. return rc;
  44169. }
  44170. /*
  44171. ** Acquire a page if it is already in the in-memory cache. Do
  44172. ** not read the page from disk. Return a pointer to the page,
  44173. ** or 0 if the page is not in cache.
  44174. **
  44175. ** See also sqlite3PagerGet(). The difference between this routine
  44176. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  44177. ** in the page if the page is not already in cache. This routine
  44178. ** returns NULL if the page is not in cache or if a disk I/O error
  44179. ** has ever happened.
  44180. */
  44181. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  44182. PgHdr *pPg = 0;
  44183. assert( pPager!=0 );
  44184. assert( pgno!=0 );
  44185. assert( pPager->pPCache!=0 );
  44186. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  44187. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  44188. return pPg;
  44189. }
  44190. /*
  44191. ** Release a page reference.
  44192. **
  44193. ** If the number of references to the page drop to zero, then the
  44194. ** page is added to the LRU list. When all references to all pages
  44195. ** are released, a rollback occurs and the lock on the database is
  44196. ** removed.
  44197. */
  44198. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  44199. if( pPg ){
  44200. Pager *pPager = pPg->pPager;
  44201. if( pPg->flags & PGHDR_MMAP ){
  44202. pagerReleaseMapPage(pPg);
  44203. }else{
  44204. sqlite3PcacheRelease(pPg);
  44205. }
  44206. pagerUnlockIfUnused(pPager);
  44207. }
  44208. }
  44209. /*
  44210. ** This function is called at the start of every write transaction.
  44211. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  44212. ** file when this routine is called.
  44213. **
  44214. ** Open the journal file for pager pPager and write a journal header
  44215. ** to the start of it. If there are active savepoints, open the sub-journal
  44216. ** as well. This function is only used when the journal file is being
  44217. ** opened to write a rollback log for a transaction. It is not used
  44218. ** when opening a hot journal file to roll it back.
  44219. **
  44220. ** If the journal file is already open (as it may be in exclusive mode),
  44221. ** then this function just writes a journal header to the start of the
  44222. ** already open file.
  44223. **
  44224. ** Whether or not the journal file is opened by this function, the
  44225. ** Pager.pInJournal bitvec structure is allocated.
  44226. **
  44227. ** Return SQLITE_OK if everything is successful. Otherwise, return
  44228. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  44229. ** an IO error code if opening or writing the journal file fails.
  44230. */
  44231. static int pager_open_journal(Pager *pPager){
  44232. int rc = SQLITE_OK; /* Return code */
  44233. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  44234. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44235. assert( assert_pager_state(pPager) );
  44236. assert( pPager->pInJournal==0 );
  44237. /* If already in the error state, this function is a no-op. But on
  44238. ** the other hand, this routine is never called if we are already in
  44239. ** an error state. */
  44240. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44241. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44242. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  44243. if( pPager->pInJournal==0 ){
  44244. return SQLITE_NOMEM;
  44245. }
  44246. /* Open the journal file if it is not already open. */
  44247. if( !isOpen(pPager->jfd) ){
  44248. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  44249. sqlite3MemJournalOpen(pPager->jfd);
  44250. }else{
  44251. const int flags = /* VFS flags to open journal file */
  44252. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  44253. (pPager->tempFile ?
  44254. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  44255. (SQLITE_OPEN_MAIN_JOURNAL)
  44256. );
  44257. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44258. rc = sqlite3JournalOpen(
  44259. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  44260. );
  44261. #else
  44262. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  44263. #endif
  44264. }
  44265. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44266. }
  44267. /* Write the first journal header to the journal file and open
  44268. ** the sub-journal if necessary.
  44269. */
  44270. if( rc==SQLITE_OK ){
  44271. /* TODO: Check if all of these are really required. */
  44272. pPager->nRec = 0;
  44273. pPager->journalOff = 0;
  44274. pPager->setMaster = 0;
  44275. pPager->journalHdr = 0;
  44276. rc = writeJournalHdr(pPager);
  44277. }
  44278. }
  44279. if( rc!=SQLITE_OK ){
  44280. sqlite3BitvecDestroy(pPager->pInJournal);
  44281. pPager->pInJournal = 0;
  44282. }else{
  44283. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44284. pPager->eState = PAGER_WRITER_CACHEMOD;
  44285. }
  44286. return rc;
  44287. }
  44288. /*
  44289. ** Begin a write-transaction on the specified pager object. If a
  44290. ** write-transaction has already been opened, this function is a no-op.
  44291. **
  44292. ** If the exFlag argument is false, then acquire at least a RESERVED
  44293. ** lock on the database file. If exFlag is true, then acquire at least
  44294. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  44295. ** functions need be called.
  44296. **
  44297. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  44298. ** within this transaction will be opened as an in-memory file. This
  44299. ** has no effect if the sub-journal is already opened (as it may be when
  44300. ** running in exclusive mode) or if the transaction does not require a
  44301. ** sub-journal. If the subjInMemory argument is zero, then any required
  44302. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  44303. ** or using a temporary file otherwise.
  44304. */
  44305. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  44306. int rc = SQLITE_OK;
  44307. if( pPager->errCode ) return pPager->errCode;
  44308. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  44309. pPager->subjInMemory = (u8)subjInMemory;
  44310. if( ALWAYS(pPager->eState==PAGER_READER) ){
  44311. assert( pPager->pInJournal==0 );
  44312. if( pagerUseWal(pPager) ){
  44313. /* If the pager is configured to use locking_mode=exclusive, and an
  44314. ** exclusive lock on the database is not already held, obtain it now.
  44315. */
  44316. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  44317. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44318. if( rc!=SQLITE_OK ){
  44319. return rc;
  44320. }
  44321. sqlite3WalExclusiveMode(pPager->pWal, 1);
  44322. }
  44323. /* Grab the write lock on the log file. If successful, upgrade to
  44324. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  44325. ** The busy-handler is not invoked if another connection already
  44326. ** holds the write-lock. If possible, the upper layer will call it.
  44327. */
  44328. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  44329. }else{
  44330. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  44331. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  44332. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  44333. ** lock, but not when obtaining the RESERVED lock.
  44334. */
  44335. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44336. if( rc==SQLITE_OK && exFlag ){
  44337. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44338. }
  44339. }
  44340. if( rc==SQLITE_OK ){
  44341. /* Change to WRITER_LOCKED state.
  44342. **
  44343. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  44344. ** when it has an open transaction, but never to DBMOD or FINISHED.
  44345. ** This is because in those states the code to roll back savepoint
  44346. ** transactions may copy data from the sub-journal into the database
  44347. ** file as well as into the page cache. Which would be incorrect in
  44348. ** WAL mode.
  44349. */
  44350. pPager->eState = PAGER_WRITER_LOCKED;
  44351. pPager->dbHintSize = pPager->dbSize;
  44352. pPager->dbFileSize = pPager->dbSize;
  44353. pPager->dbOrigSize = pPager->dbSize;
  44354. pPager->journalOff = 0;
  44355. }
  44356. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  44357. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  44358. assert( assert_pager_state(pPager) );
  44359. }
  44360. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  44361. return rc;
  44362. }
  44363. /*
  44364. ** Mark a single data page as writeable. The page is written into the
  44365. ** main journal or sub-journal as required. If the page is written into
  44366. ** one of the journals, the corresponding bit is set in the
  44367. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  44368. ** of any open savepoints as appropriate.
  44369. */
  44370. static int pager_write(PgHdr *pPg){
  44371. void *pData = pPg->pData;
  44372. Pager *pPager = pPg->pPager;
  44373. int rc = SQLITE_OK;
  44374. /* This routine is not called unless a write-transaction has already
  44375. ** been started. The journal file may or may not be open at this point.
  44376. ** It is never called in the ERROR state.
  44377. */
  44378. assert( pPager->eState==PAGER_WRITER_LOCKED
  44379. || pPager->eState==PAGER_WRITER_CACHEMOD
  44380. || pPager->eState==PAGER_WRITER_DBMOD
  44381. );
  44382. assert( assert_pager_state(pPager) );
  44383. /* If an error has been previously detected, report the same error
  44384. ** again. This should not happen, but the check provides robustness. */
  44385. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44386. /* Higher-level routines never call this function if database is not
  44387. ** writable. But check anyway, just for robustness. */
  44388. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  44389. CHECK_PAGE(pPg);
  44390. /* The journal file needs to be opened. Higher level routines have already
  44391. ** obtained the necessary locks to begin the write-transaction, but the
  44392. ** rollback journal might not yet be open. Open it now if this is the case.
  44393. **
  44394. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  44395. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  44396. ** an error might occur and the pager would end up in WRITER_LOCKED state
  44397. ** with pages marked as dirty in the cache.
  44398. */
  44399. if( pPager->eState==PAGER_WRITER_LOCKED ){
  44400. rc = pager_open_journal(pPager);
  44401. if( rc!=SQLITE_OK ) return rc;
  44402. }
  44403. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44404. assert( assert_pager_state(pPager) );
  44405. /* Mark the page as dirty. If the page has already been written
  44406. ** to the journal then we can return right away.
  44407. */
  44408. sqlite3PcacheMakeDirty(pPg);
  44409. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  44410. assert( !pagerUseWal(pPager) );
  44411. }else{
  44412. /* The transaction journal now exists and we have a RESERVED or an
  44413. ** EXCLUSIVE lock on the main database file. Write the current page to
  44414. ** the transaction journal if it is not there already.
  44415. */
  44416. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  44417. assert( pagerUseWal(pPager)==0 );
  44418. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  44419. u32 cksum;
  44420. char *pData2;
  44421. i64 iOff = pPager->journalOff;
  44422. /* We should never write to the journal file the page that
  44423. ** contains the database locks. The following assert verifies
  44424. ** that we do not. */
  44425. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  44426. assert( pPager->journalHdr<=pPager->journalOff );
  44427. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44428. cksum = pager_cksum(pPager, (u8*)pData2);
  44429. /* Even if an IO or diskfull error occurs while journalling the
  44430. ** page in the block above, set the need-sync flag for the page.
  44431. ** Otherwise, when the transaction is rolled back, the logic in
  44432. ** playback_one_page() will think that the page needs to be restored
  44433. ** in the database file. And if an IO error occurs while doing so,
  44434. ** then corruption may follow.
  44435. */
  44436. pPg->flags |= PGHDR_NEED_SYNC;
  44437. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  44438. if( rc!=SQLITE_OK ) return rc;
  44439. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  44440. if( rc!=SQLITE_OK ) return rc;
  44441. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  44442. if( rc!=SQLITE_OK ) return rc;
  44443. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  44444. pPager->journalOff, pPager->pageSize));
  44445. PAGER_INCR(sqlite3_pager_writej_count);
  44446. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  44447. PAGERID(pPager), pPg->pgno,
  44448. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  44449. pPager->journalOff += 8 + pPager->pageSize;
  44450. pPager->nRec++;
  44451. assert( pPager->pInJournal!=0 );
  44452. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  44453. testcase( rc==SQLITE_NOMEM );
  44454. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  44455. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  44456. if( rc!=SQLITE_OK ){
  44457. assert( rc==SQLITE_NOMEM );
  44458. return rc;
  44459. }
  44460. }else{
  44461. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  44462. pPg->flags |= PGHDR_NEED_SYNC;
  44463. }
  44464. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  44465. PAGERID(pPager), pPg->pgno,
  44466. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  44467. }
  44468. }
  44469. /* If the statement journal is open and the page is not in it,
  44470. ** then write the current page to the statement journal. Note that
  44471. ** the statement journal format differs from the standard journal format
  44472. ** in that it omits the checksums and the header.
  44473. */
  44474. if( subjRequiresPage(pPg) ){
  44475. rc = subjournalPage(pPg);
  44476. }
  44477. }
  44478. /* Update the database size and return.
  44479. */
  44480. if( pPager->dbSize<pPg->pgno ){
  44481. pPager->dbSize = pPg->pgno;
  44482. }
  44483. return rc;
  44484. }
  44485. /*
  44486. ** Mark a data page as writeable. This routine must be called before
  44487. ** making changes to a page. The caller must check the return value
  44488. ** of this function and be careful not to change any page data unless
  44489. ** this routine returns SQLITE_OK.
  44490. **
  44491. ** The difference between this function and pager_write() is that this
  44492. ** function also deals with the special case where 2 or more pages
  44493. ** fit on a single disk sector. In this case all co-resident pages
  44494. ** must have been written to the journal file before returning.
  44495. **
  44496. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  44497. ** as appropriate. Otherwise, SQLITE_OK.
  44498. */
  44499. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  44500. int rc = SQLITE_OK;
  44501. PgHdr *pPg = pDbPage;
  44502. Pager *pPager = pPg->pPager;
  44503. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  44504. assert( (pPg->flags & PGHDR_MMAP)==0 );
  44505. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44506. assert( pPager->eState!=PAGER_ERROR );
  44507. assert( assert_pager_state(pPager) );
  44508. if( nPagePerSector>1 ){
  44509. Pgno nPageCount; /* Total number of pages in database file */
  44510. Pgno pg1; /* First page of the sector pPg is located on. */
  44511. int nPage = 0; /* Number of pages starting at pg1 to journal */
  44512. int ii; /* Loop counter */
  44513. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  44514. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  44515. ** a journal header to be written between the pages journaled by
  44516. ** this function.
  44517. */
  44518. assert( !MEMDB );
  44519. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  44520. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  44521. /* This trick assumes that both the page-size and sector-size are
  44522. ** an integer power of 2. It sets variable pg1 to the identifier
  44523. ** of the first page of the sector pPg is located on.
  44524. */
  44525. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  44526. nPageCount = pPager->dbSize;
  44527. if( pPg->pgno>nPageCount ){
  44528. nPage = (pPg->pgno - pg1)+1;
  44529. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  44530. nPage = nPageCount+1-pg1;
  44531. }else{
  44532. nPage = nPagePerSector;
  44533. }
  44534. assert(nPage>0);
  44535. assert(pg1<=pPg->pgno);
  44536. assert((pg1+nPage)>pPg->pgno);
  44537. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  44538. Pgno pg = pg1+ii;
  44539. PgHdr *pPage;
  44540. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  44541. if( pg!=PAGER_MJ_PGNO(pPager) ){
  44542. rc = sqlite3PagerGet(pPager, pg, &pPage);
  44543. if( rc==SQLITE_OK ){
  44544. rc = pager_write(pPage);
  44545. if( pPage->flags&PGHDR_NEED_SYNC ){
  44546. needSync = 1;
  44547. }
  44548. sqlite3PagerUnref(pPage);
  44549. }
  44550. }
  44551. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  44552. if( pPage->flags&PGHDR_NEED_SYNC ){
  44553. needSync = 1;
  44554. }
  44555. sqlite3PagerUnref(pPage);
  44556. }
  44557. }
  44558. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  44559. ** starting at pg1, then it needs to be set for all of them. Because
  44560. ** writing to any of these nPage pages may damage the others, the
  44561. ** journal file must contain sync()ed copies of all of them
  44562. ** before any of them can be written out to the database file.
  44563. */
  44564. if( rc==SQLITE_OK && needSync ){
  44565. assert( !MEMDB );
  44566. for(ii=0; ii<nPage; ii++){
  44567. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  44568. if( pPage ){
  44569. pPage->flags |= PGHDR_NEED_SYNC;
  44570. sqlite3PagerUnref(pPage);
  44571. }
  44572. }
  44573. }
  44574. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  44575. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  44576. }else{
  44577. rc = pager_write(pDbPage);
  44578. }
  44579. return rc;
  44580. }
  44581. /*
  44582. ** Return TRUE if the page given in the argument was previously passed
  44583. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  44584. ** to change the content of the page.
  44585. */
  44586. #ifndef NDEBUG
  44587. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  44588. return pPg->flags&PGHDR_DIRTY;
  44589. }
  44590. #endif
  44591. /*
  44592. ** A call to this routine tells the pager that it is not necessary to
  44593. ** write the information on page pPg back to the disk, even though
  44594. ** that page might be marked as dirty. This happens, for example, when
  44595. ** the page has been added as a leaf of the freelist and so its
  44596. ** content no longer matters.
  44597. **
  44598. ** The overlying software layer calls this routine when all of the data
  44599. ** on the given page is unused. The pager marks the page as clean so
  44600. ** that it does not get written to disk.
  44601. **
  44602. ** Tests show that this optimization can quadruple the speed of large
  44603. ** DELETE operations.
  44604. */
  44605. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  44606. Pager *pPager = pPg->pPager;
  44607. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  44608. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  44609. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  44610. pPg->flags |= PGHDR_DONT_WRITE;
  44611. pager_set_pagehash(pPg);
  44612. }
  44613. }
  44614. /*
  44615. ** This routine is called to increment the value of the database file
  44616. ** change-counter, stored as a 4-byte big-endian integer starting at
  44617. ** byte offset 24 of the pager file. The secondary change counter at
  44618. ** 92 is also updated, as is the SQLite version number at offset 96.
  44619. **
  44620. ** But this only happens if the pPager->changeCountDone flag is false.
  44621. ** To avoid excess churning of page 1, the update only happens once.
  44622. ** See also the pager_write_changecounter() routine that does an
  44623. ** unconditional update of the change counters.
  44624. **
  44625. ** If the isDirectMode flag is zero, then this is done by calling
  44626. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  44627. ** page data. In this case the file will be updated when the current
  44628. ** transaction is committed.
  44629. **
  44630. ** The isDirectMode flag may only be non-zero if the library was compiled
  44631. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  44632. ** if isDirect is non-zero, then the database file is updated directly
  44633. ** by writing an updated version of page 1 using a call to the
  44634. ** sqlite3OsWrite() function.
  44635. */
  44636. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  44637. int rc = SQLITE_OK;
  44638. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44639. || pPager->eState==PAGER_WRITER_DBMOD
  44640. );
  44641. assert( assert_pager_state(pPager) );
  44642. /* Declare and initialize constant integer 'isDirect'. If the
  44643. ** atomic-write optimization is enabled in this build, then isDirect
  44644. ** is initialized to the value passed as the isDirectMode parameter
  44645. ** to this function. Otherwise, it is always set to zero.
  44646. **
  44647. ** The idea is that if the atomic-write optimization is not
  44648. ** enabled at compile time, the compiler can omit the tests of
  44649. ** 'isDirect' below, as well as the block enclosed in the
  44650. ** "if( isDirect )" condition.
  44651. */
  44652. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  44653. # define DIRECT_MODE 0
  44654. assert( isDirectMode==0 );
  44655. UNUSED_PARAMETER(isDirectMode);
  44656. #else
  44657. # define DIRECT_MODE isDirectMode
  44658. #endif
  44659. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  44660. PgHdr *pPgHdr; /* Reference to page 1 */
  44661. assert( !pPager->tempFile && isOpen(pPager->fd) );
  44662. /* Open page 1 of the file for writing. */
  44663. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  44664. assert( pPgHdr==0 || rc==SQLITE_OK );
  44665. /* If page one was fetched successfully, and this function is not
  44666. ** operating in direct-mode, make page 1 writable. When not in
  44667. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  44668. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  44669. */
  44670. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  44671. rc = sqlite3PagerWrite(pPgHdr);
  44672. }
  44673. if( rc==SQLITE_OK ){
  44674. /* Actually do the update of the change counter */
  44675. pager_write_changecounter(pPgHdr);
  44676. /* If running in direct mode, write the contents of page 1 to the file. */
  44677. if( DIRECT_MODE ){
  44678. const void *zBuf;
  44679. assert( pPager->dbFileSize>0 );
  44680. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  44681. if( rc==SQLITE_OK ){
  44682. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  44683. pPager->aStat[PAGER_STAT_WRITE]++;
  44684. }
  44685. if( rc==SQLITE_OK ){
  44686. /* Update the pager's copy of the change-counter. Otherwise, the
  44687. ** next time a read transaction is opened the cache will be
  44688. ** flushed (as the change-counter values will not match). */
  44689. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  44690. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  44691. pPager->changeCountDone = 1;
  44692. }
  44693. }else{
  44694. pPager->changeCountDone = 1;
  44695. }
  44696. }
  44697. /* Release the page reference. */
  44698. sqlite3PagerUnref(pPgHdr);
  44699. }
  44700. return rc;
  44701. }
  44702. /*
  44703. ** Sync the database file to disk. This is a no-op for in-memory databases
  44704. ** or pages with the Pager.noSync flag set.
  44705. **
  44706. ** If successful, or if called on a pager for which it is a no-op, this
  44707. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  44708. */
  44709. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  44710. int rc = SQLITE_OK;
  44711. if( !pPager->noSync ){
  44712. assert( !MEMDB );
  44713. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  44714. }else if( isOpen(pPager->fd) ){
  44715. assert( !MEMDB );
  44716. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  44717. if( rc==SQLITE_NOTFOUND ){
  44718. rc = SQLITE_OK;
  44719. }
  44720. }
  44721. return rc;
  44722. }
  44723. /*
  44724. ** This function may only be called while a write-transaction is active in
  44725. ** rollback. If the connection is in WAL mode, this call is a no-op.
  44726. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  44727. ** the database file, an attempt is made to obtain one.
  44728. **
  44729. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  44730. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  44731. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  44732. ** returned.
  44733. */
  44734. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  44735. int rc = SQLITE_OK;
  44736. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44737. || pPager->eState==PAGER_WRITER_DBMOD
  44738. || pPager->eState==PAGER_WRITER_LOCKED
  44739. );
  44740. assert( assert_pager_state(pPager) );
  44741. if( 0==pagerUseWal(pPager) ){
  44742. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44743. }
  44744. return rc;
  44745. }
  44746. /*
  44747. ** Sync the database file for the pager pPager. zMaster points to the name
  44748. ** of a master journal file that should be written into the individual
  44749. ** journal file. zMaster may be NULL, which is interpreted as no master
  44750. ** journal (a single database transaction).
  44751. **
  44752. ** This routine ensures that:
  44753. **
  44754. ** * The database file change-counter is updated,
  44755. ** * the journal is synced (unless the atomic-write optimization is used),
  44756. ** * all dirty pages are written to the database file,
  44757. ** * the database file is truncated (if required), and
  44758. ** * the database file synced.
  44759. **
  44760. ** The only thing that remains to commit the transaction is to finalize
  44761. ** (delete, truncate or zero the first part of) the journal file (or
  44762. ** delete the master journal file if specified).
  44763. **
  44764. ** Note that if zMaster==NULL, this does not overwrite a previous value
  44765. ** passed to an sqlite3PagerCommitPhaseOne() call.
  44766. **
  44767. ** If the final parameter - noSync - is true, then the database file itself
  44768. ** is not synced. The caller must call sqlite3PagerSync() directly to
  44769. ** sync the database file before calling CommitPhaseTwo() to delete the
  44770. ** journal file in this case.
  44771. */
  44772. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  44773. Pager *pPager, /* Pager object */
  44774. const char *zMaster, /* If not NULL, the master journal name */
  44775. int noSync /* True to omit the xSync on the db file */
  44776. ){
  44777. int rc = SQLITE_OK; /* Return code */
  44778. assert( pPager->eState==PAGER_WRITER_LOCKED
  44779. || pPager->eState==PAGER_WRITER_CACHEMOD
  44780. || pPager->eState==PAGER_WRITER_DBMOD
  44781. || pPager->eState==PAGER_ERROR
  44782. );
  44783. assert( assert_pager_state(pPager) );
  44784. /* If a prior error occurred, report that error again. */
  44785. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44786. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  44787. pPager->zFilename, zMaster, pPager->dbSize));
  44788. /* If no database changes have been made, return early. */
  44789. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  44790. if( MEMDB ){
  44791. /* If this is an in-memory db, or no pages have been written to, or this
  44792. ** function has already been called, it is mostly a no-op. However, any
  44793. ** backup in progress needs to be restarted.
  44794. */
  44795. sqlite3BackupRestart(pPager->pBackup);
  44796. }else{
  44797. if( pagerUseWal(pPager) ){
  44798. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44799. PgHdr *pPageOne = 0;
  44800. if( pList==0 ){
  44801. /* Must have at least one page for the WAL commit flag.
  44802. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  44803. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  44804. pList = pPageOne;
  44805. pList->pDirty = 0;
  44806. }
  44807. assert( rc==SQLITE_OK );
  44808. if( ALWAYS(pList) ){
  44809. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  44810. }
  44811. sqlite3PagerUnref(pPageOne);
  44812. if( rc==SQLITE_OK ){
  44813. sqlite3PcacheCleanAll(pPager->pPCache);
  44814. }
  44815. }else{
  44816. /* The following block updates the change-counter. Exactly how it
  44817. ** does this depends on whether or not the atomic-update optimization
  44818. ** was enabled at compile time, and if this transaction meets the
  44819. ** runtime criteria to use the operation:
  44820. **
  44821. ** * The file-system supports the atomic-write property for
  44822. ** blocks of size page-size, and
  44823. ** * This commit is not part of a multi-file transaction, and
  44824. ** * Exactly one page has been modified and store in the journal file.
  44825. **
  44826. ** If the optimization was not enabled at compile time, then the
  44827. ** pager_incr_changecounter() function is called to update the change
  44828. ** counter in 'indirect-mode'. If the optimization is compiled in but
  44829. ** is not applicable to this transaction, call sqlite3JournalCreate()
  44830. ** to make sure the journal file has actually been created, then call
  44831. ** pager_incr_changecounter() to update the change-counter in indirect
  44832. ** mode.
  44833. **
  44834. ** Otherwise, if the optimization is both enabled and applicable,
  44835. ** then call pager_incr_changecounter() to update the change-counter
  44836. ** in 'direct' mode. In this case the journal file will never be
  44837. ** created for this transaction.
  44838. */
  44839. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44840. PgHdr *pPg;
  44841. assert( isOpen(pPager->jfd)
  44842. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  44843. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  44844. );
  44845. if( !zMaster && isOpen(pPager->jfd)
  44846. && pPager->journalOff==jrnlBufferSize(pPager)
  44847. && pPager->dbSize>=pPager->dbOrigSize
  44848. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  44849. ){
  44850. /* Update the db file change counter via the direct-write method. The
  44851. ** following call will modify the in-memory representation of page 1
  44852. ** to include the updated change counter and then write page 1
  44853. ** directly to the database file. Because of the atomic-write
  44854. ** property of the host file-system, this is safe.
  44855. */
  44856. rc = pager_incr_changecounter(pPager, 1);
  44857. }else{
  44858. rc = sqlite3JournalCreate(pPager->jfd);
  44859. if( rc==SQLITE_OK ){
  44860. rc = pager_incr_changecounter(pPager, 0);
  44861. }
  44862. }
  44863. #else
  44864. rc = pager_incr_changecounter(pPager, 0);
  44865. #endif
  44866. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44867. /* Write the master journal name into the journal file. If a master
  44868. ** journal file name has already been written to the journal file,
  44869. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  44870. */
  44871. rc = writeMasterJournal(pPager, zMaster);
  44872. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44873. /* Sync the journal file and write all dirty pages to the database.
  44874. ** If the atomic-update optimization is being used, this sync will not
  44875. ** create the journal file or perform any real IO.
  44876. **
  44877. ** Because the change-counter page was just modified, unless the
  44878. ** atomic-update optimization is used it is almost certain that the
  44879. ** journal requires a sync here. However, in locking_mode=exclusive
  44880. ** on a system under memory pressure it is just possible that this is
  44881. ** not the case. In this case it is likely enough that the redundant
  44882. ** xSync() call will be changed to a no-op by the OS anyhow.
  44883. */
  44884. rc = syncJournal(pPager, 0);
  44885. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44886. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  44887. if( rc!=SQLITE_OK ){
  44888. assert( rc!=SQLITE_IOERR_BLOCKED );
  44889. goto commit_phase_one_exit;
  44890. }
  44891. sqlite3PcacheCleanAll(pPager->pPCache);
  44892. /* If the file on disk is smaller than the database image, use
  44893. ** pager_truncate to grow the file here. This can happen if the database
  44894. ** image was extended as part of the current transaction and then the
  44895. ** last page in the db image moved to the free-list. In this case the
  44896. ** last page is never written out to disk, leaving the database file
  44897. ** undersized. Fix this now if it is the case. */
  44898. if( pPager->dbSize>pPager->dbFileSize ){
  44899. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  44900. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44901. rc = pager_truncate(pPager, nNew);
  44902. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44903. }
  44904. /* Finally, sync the database file. */
  44905. if( !noSync ){
  44906. rc = sqlite3PagerSync(pPager);
  44907. }
  44908. IOTRACE(("DBSYNC %p\n", pPager))
  44909. }
  44910. }
  44911. commit_phase_one_exit:
  44912. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  44913. pPager->eState = PAGER_WRITER_FINISHED;
  44914. }
  44915. return rc;
  44916. }
  44917. /*
  44918. ** When this function is called, the database file has been completely
  44919. ** updated to reflect the changes made by the current transaction and
  44920. ** synced to disk. The journal file still exists in the file-system
  44921. ** though, and if a failure occurs at this point it will eventually
  44922. ** be used as a hot-journal and the current transaction rolled back.
  44923. **
  44924. ** This function finalizes the journal file, either by deleting,
  44925. ** truncating or partially zeroing it, so that it cannot be used
  44926. ** for hot-journal rollback. Once this is done the transaction is
  44927. ** irrevocably committed.
  44928. **
  44929. ** If an error occurs, an IO error code is returned and the pager
  44930. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  44931. */
  44932. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  44933. int rc = SQLITE_OK; /* Return code */
  44934. /* This routine should not be called if a prior error has occurred.
  44935. ** But if (due to a coding error elsewhere in the system) it does get
  44936. ** called, just return the same error code without doing anything. */
  44937. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44938. assert( pPager->eState==PAGER_WRITER_LOCKED
  44939. || pPager->eState==PAGER_WRITER_FINISHED
  44940. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  44941. );
  44942. assert( assert_pager_state(pPager) );
  44943. /* An optimization. If the database was not actually modified during
  44944. ** this transaction, the pager is running in exclusive-mode and is
  44945. ** using persistent journals, then this function is a no-op.
  44946. **
  44947. ** The start of the journal file currently contains a single journal
  44948. ** header with the nRec field set to 0. If such a journal is used as
  44949. ** a hot-journal during hot-journal rollback, 0 changes will be made
  44950. ** to the database file. So there is no need to zero the journal
  44951. ** header. Since the pager is in exclusive mode, there is no need
  44952. ** to drop any locks either.
  44953. */
  44954. if( pPager->eState==PAGER_WRITER_LOCKED
  44955. && pPager->exclusiveMode
  44956. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  44957. ){
  44958. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  44959. pPager->eState = PAGER_READER;
  44960. return SQLITE_OK;
  44961. }
  44962. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  44963. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  44964. return pager_error(pPager, rc);
  44965. }
  44966. /*
  44967. ** If a write transaction is open, then all changes made within the
  44968. ** transaction are reverted and the current write-transaction is closed.
  44969. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  44970. ** state if an error occurs.
  44971. **
  44972. ** If the pager is already in PAGER_ERROR state when this function is called,
  44973. ** it returns Pager.errCode immediately. No work is performed in this case.
  44974. **
  44975. ** Otherwise, in rollback mode, this function performs two functions:
  44976. **
  44977. ** 1) It rolls back the journal file, restoring all database file and
  44978. ** in-memory cache pages to the state they were in when the transaction
  44979. ** was opened, and
  44980. **
  44981. ** 2) It finalizes the journal file, so that it is not used for hot
  44982. ** rollback at any point in the future.
  44983. **
  44984. ** Finalization of the journal file (task 2) is only performed if the
  44985. ** rollback is successful.
  44986. **
  44987. ** In WAL mode, all cache-entries containing data modified within the
  44988. ** current transaction are either expelled from the cache or reverted to
  44989. ** their pre-transaction state by re-reading data from the database or
  44990. ** WAL files. The WAL transaction is then closed.
  44991. */
  44992. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  44993. int rc = SQLITE_OK; /* Return code */
  44994. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  44995. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  44996. ** the pager is already in the ERROR state, the rollback is not
  44997. ** attempted here. Instead, the error code is returned to the caller.
  44998. */
  44999. assert( assert_pager_state(pPager) );
  45000. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  45001. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  45002. if( pagerUseWal(pPager) ){
  45003. int rc2;
  45004. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  45005. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  45006. if( rc==SQLITE_OK ) rc = rc2;
  45007. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  45008. int eState = pPager->eState;
  45009. rc = pager_end_transaction(pPager, 0, 0);
  45010. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  45011. /* This can happen using journal_mode=off. Move the pager to the error
  45012. ** state to indicate that the contents of the cache may not be trusted.
  45013. ** Any active readers will get SQLITE_ABORT.
  45014. */
  45015. pPager->errCode = SQLITE_ABORT;
  45016. pPager->eState = PAGER_ERROR;
  45017. return rc;
  45018. }
  45019. }else{
  45020. rc = pager_playback(pPager, 0);
  45021. }
  45022. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  45023. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  45024. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  45025. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  45026. ** cache. So call pager_error() on the way out to make any error persistent.
  45027. */
  45028. return pager_error(pPager, rc);
  45029. }
  45030. /*
  45031. ** Return TRUE if the database file is opened read-only. Return FALSE
  45032. ** if the database is (in theory) writable.
  45033. */
  45034. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  45035. return pPager->readOnly;
  45036. }
  45037. /*
  45038. ** Return the number of references to the pager.
  45039. */
  45040. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  45041. return sqlite3PcacheRefCount(pPager->pPCache);
  45042. }
  45043. /*
  45044. ** Return the approximate number of bytes of memory currently
  45045. ** used by the pager and its associated cache.
  45046. */
  45047. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  45048. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  45049. + 5*sizeof(void*);
  45050. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  45051. + sqlite3MallocSize(pPager)
  45052. + pPager->pageSize;
  45053. }
  45054. /*
  45055. ** Return the number of references to the specified page.
  45056. */
  45057. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  45058. return sqlite3PcachePageRefcount(pPage);
  45059. }
  45060. #ifdef SQLITE_TEST
  45061. /*
  45062. ** This routine is used for testing and analysis only.
  45063. */
  45064. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  45065. static int a[11];
  45066. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  45067. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  45068. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  45069. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  45070. a[4] = pPager->eState;
  45071. a[5] = pPager->errCode;
  45072. a[6] = pPager->aStat[PAGER_STAT_HIT];
  45073. a[7] = pPager->aStat[PAGER_STAT_MISS];
  45074. a[8] = 0; /* Used to be pPager->nOvfl */
  45075. a[9] = pPager->nRead;
  45076. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  45077. return a;
  45078. }
  45079. #endif
  45080. /*
  45081. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  45082. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  45083. ** current cache hit or miss count, according to the value of eStat. If the
  45084. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  45085. ** returning.
  45086. */
  45087. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  45088. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  45089. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  45090. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  45091. );
  45092. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  45093. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  45094. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  45095. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  45096. if( reset ){
  45097. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  45098. }
  45099. }
  45100. /*
  45101. ** Return true if this is an in-memory pager.
  45102. */
  45103. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  45104. return MEMDB;
  45105. }
  45106. /*
  45107. ** Check that there are at least nSavepoint savepoints open. If there are
  45108. ** currently less than nSavepoints open, then open one or more savepoints
  45109. ** to make up the difference. If the number of savepoints is already
  45110. ** equal to nSavepoint, then this function is a no-op.
  45111. **
  45112. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  45113. ** occurs while opening the sub-journal file, then an IO error code is
  45114. ** returned. Otherwise, SQLITE_OK.
  45115. */
  45116. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  45117. int rc = SQLITE_OK; /* Return code */
  45118. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  45119. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45120. assert( assert_pager_state(pPager) );
  45121. if( nSavepoint>nCurrent && pPager->useJournal ){
  45122. int ii; /* Iterator variable */
  45123. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  45124. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  45125. ** if the allocation fails. Otherwise, zero the new portion in case a
  45126. ** malloc failure occurs while populating it in the for(...) loop below.
  45127. */
  45128. aNew = (PagerSavepoint *)sqlite3Realloc(
  45129. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  45130. );
  45131. if( !aNew ){
  45132. return SQLITE_NOMEM;
  45133. }
  45134. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  45135. pPager->aSavepoint = aNew;
  45136. /* Populate the PagerSavepoint structures just allocated. */
  45137. for(ii=nCurrent; ii<nSavepoint; ii++){
  45138. aNew[ii].nOrig = pPager->dbSize;
  45139. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  45140. aNew[ii].iOffset = pPager->journalOff;
  45141. }else{
  45142. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  45143. }
  45144. aNew[ii].iSubRec = pPager->nSubRec;
  45145. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  45146. if( !aNew[ii].pInSavepoint ){
  45147. return SQLITE_NOMEM;
  45148. }
  45149. if( pagerUseWal(pPager) ){
  45150. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  45151. }
  45152. pPager->nSavepoint = ii+1;
  45153. }
  45154. assert( pPager->nSavepoint==nSavepoint );
  45155. assertTruncateConstraint(pPager);
  45156. }
  45157. return rc;
  45158. }
  45159. /*
  45160. ** This function is called to rollback or release (commit) a savepoint.
  45161. ** The savepoint to release or rollback need not be the most recently
  45162. ** created savepoint.
  45163. **
  45164. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  45165. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  45166. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  45167. ** that have occurred since the specified savepoint was created.
  45168. **
  45169. ** The savepoint to rollback or release is identified by parameter
  45170. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  45171. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  45172. ** on the most recently created savepoint. If iSavepoint is greater than
  45173. ** (Pager.nSavepoint-1), then this function is a no-op.
  45174. **
  45175. ** If a negative value is passed to this function, then the current
  45176. ** transaction is rolled back. This is different to calling
  45177. ** sqlite3PagerRollback() because this function does not terminate
  45178. ** the transaction or unlock the database, it just restores the
  45179. ** contents of the database to its original state.
  45180. **
  45181. ** In any case, all savepoints with an index greater than iSavepoint
  45182. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  45183. ** then savepoint iSavepoint is also destroyed.
  45184. **
  45185. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  45186. ** or an IO error code if an IO error occurs while rolling back a
  45187. ** savepoint. If no errors occur, SQLITE_OK is returned.
  45188. */
  45189. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  45190. int rc = pPager->errCode; /* Return code */
  45191. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  45192. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  45193. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  45194. int ii; /* Iterator variable */
  45195. int nNew; /* Number of remaining savepoints after this op. */
  45196. /* Figure out how many savepoints will still be active after this
  45197. ** operation. Store this value in nNew. Then free resources associated
  45198. ** with any savepoints that are destroyed by this operation.
  45199. */
  45200. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  45201. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  45202. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45203. }
  45204. pPager->nSavepoint = nNew;
  45205. /* If this is a release of the outermost savepoint, truncate
  45206. ** the sub-journal to zero bytes in size. */
  45207. if( op==SAVEPOINT_RELEASE ){
  45208. if( nNew==0 && isOpen(pPager->sjfd) ){
  45209. /* Only truncate if it is an in-memory sub-journal. */
  45210. if( sqlite3IsMemJournal(pPager->sjfd) ){
  45211. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  45212. assert( rc==SQLITE_OK );
  45213. }
  45214. pPager->nSubRec = 0;
  45215. }
  45216. }
  45217. /* Else this is a rollback operation, playback the specified savepoint.
  45218. ** If this is a temp-file, it is possible that the journal file has
  45219. ** not yet been opened. In this case there have been no changes to
  45220. ** the database file, so the playback operation can be skipped.
  45221. */
  45222. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  45223. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  45224. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  45225. assert(rc!=SQLITE_DONE);
  45226. }
  45227. }
  45228. return rc;
  45229. }
  45230. /*
  45231. ** Return the full pathname of the database file.
  45232. **
  45233. ** Except, if the pager is in-memory only, then return an empty string if
  45234. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  45235. ** used to report the filename to the user, for compatibility with legacy
  45236. ** behavior. But when the Btree needs to know the filename for matching to
  45237. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  45238. ** participate in shared-cache.
  45239. */
  45240. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  45241. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  45242. }
  45243. /*
  45244. ** Return the VFS structure for the pager.
  45245. */
  45246. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  45247. return pPager->pVfs;
  45248. }
  45249. /*
  45250. ** Return the file handle for the database file associated
  45251. ** with the pager. This might return NULL if the file has
  45252. ** not yet been opened.
  45253. */
  45254. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  45255. return pPager->fd;
  45256. }
  45257. /*
  45258. ** Return the full pathname of the journal file.
  45259. */
  45260. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  45261. return pPager->zJournal;
  45262. }
  45263. /*
  45264. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  45265. ** if fsync()s are executed normally.
  45266. */
  45267. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  45268. return pPager->noSync;
  45269. }
  45270. #ifdef SQLITE_HAS_CODEC
  45271. /*
  45272. ** Set or retrieve the codec for this pager
  45273. */
  45274. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  45275. Pager *pPager,
  45276. void *(*xCodec)(void*,void*,Pgno,int),
  45277. void (*xCodecSizeChng)(void*,int,int),
  45278. void (*xCodecFree)(void*),
  45279. void *pCodec
  45280. ){
  45281. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  45282. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  45283. pPager->xCodecSizeChng = xCodecSizeChng;
  45284. pPager->xCodecFree = xCodecFree;
  45285. pPager->pCodec = pCodec;
  45286. pagerReportSize(pPager);
  45287. }
  45288. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  45289. return pPager->pCodec;
  45290. }
  45291. /*
  45292. ** This function is called by the wal module when writing page content
  45293. ** into the log file.
  45294. **
  45295. ** This function returns a pointer to a buffer containing the encrypted
  45296. ** page content. If a malloc fails, this function may return NULL.
  45297. */
  45298. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  45299. void *aData = 0;
  45300. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  45301. return aData;
  45302. }
  45303. /*
  45304. ** Return the current pager state
  45305. */
  45306. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  45307. return pPager->eState;
  45308. }
  45309. #endif /* SQLITE_HAS_CODEC */
  45310. #ifndef SQLITE_OMIT_AUTOVACUUM
  45311. /*
  45312. ** Move the page pPg to location pgno in the file.
  45313. **
  45314. ** There must be no references to the page previously located at
  45315. ** pgno (which we call pPgOld) though that page is allowed to be
  45316. ** in cache. If the page previously located at pgno is not already
  45317. ** in the rollback journal, it is not put there by by this routine.
  45318. **
  45319. ** References to the page pPg remain valid. Updating any
  45320. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  45321. ** allocated along with the page) is the responsibility of the caller.
  45322. **
  45323. ** A transaction must be active when this routine is called. It used to be
  45324. ** required that a statement transaction was not active, but this restriction
  45325. ** has been removed (CREATE INDEX needs to move a page when a statement
  45326. ** transaction is active).
  45327. **
  45328. ** If the fourth argument, isCommit, is non-zero, then this page is being
  45329. ** moved as part of a database reorganization just before the transaction
  45330. ** is being committed. In this case, it is guaranteed that the database page
  45331. ** pPg refers to will not be written to again within this transaction.
  45332. **
  45333. ** This function may return SQLITE_NOMEM or an IO error code if an error
  45334. ** occurs. Otherwise, it returns SQLITE_OK.
  45335. */
  45336. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  45337. PgHdr *pPgOld; /* The page being overwritten. */
  45338. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  45339. int rc; /* Return code */
  45340. Pgno origPgno; /* The original page number */
  45341. assert( pPg->nRef>0 );
  45342. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45343. || pPager->eState==PAGER_WRITER_DBMOD
  45344. );
  45345. assert( assert_pager_state(pPager) );
  45346. /* In order to be able to rollback, an in-memory database must journal
  45347. ** the page we are moving from.
  45348. */
  45349. if( MEMDB ){
  45350. rc = sqlite3PagerWrite(pPg);
  45351. if( rc ) return rc;
  45352. }
  45353. /* If the page being moved is dirty and has not been saved by the latest
  45354. ** savepoint, then save the current contents of the page into the
  45355. ** sub-journal now. This is required to handle the following scenario:
  45356. **
  45357. ** BEGIN;
  45358. ** <journal page X, then modify it in memory>
  45359. ** SAVEPOINT one;
  45360. ** <Move page X to location Y>
  45361. ** ROLLBACK TO one;
  45362. **
  45363. ** If page X were not written to the sub-journal here, it would not
  45364. ** be possible to restore its contents when the "ROLLBACK TO one"
  45365. ** statement were is processed.
  45366. **
  45367. ** subjournalPage() may need to allocate space to store pPg->pgno into
  45368. ** one or more savepoint bitvecs. This is the reason this function
  45369. ** may return SQLITE_NOMEM.
  45370. */
  45371. if( pPg->flags&PGHDR_DIRTY
  45372. && subjRequiresPage(pPg)
  45373. && SQLITE_OK!=(rc = subjournalPage(pPg))
  45374. ){
  45375. return rc;
  45376. }
  45377. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  45378. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  45379. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  45380. /* If the journal needs to be sync()ed before page pPg->pgno can
  45381. ** be written to, store pPg->pgno in local variable needSyncPgno.
  45382. **
  45383. ** If the isCommit flag is set, there is no need to remember that
  45384. ** the journal needs to be sync()ed before database page pPg->pgno
  45385. ** can be written to. The caller has already promised not to write to it.
  45386. */
  45387. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  45388. needSyncPgno = pPg->pgno;
  45389. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  45390. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  45391. assert( pPg->flags&PGHDR_DIRTY );
  45392. }
  45393. /* If the cache contains a page with page-number pgno, remove it
  45394. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  45395. ** page pgno before the 'move' operation, it needs to be retained
  45396. ** for the page moved there.
  45397. */
  45398. pPg->flags &= ~PGHDR_NEED_SYNC;
  45399. pPgOld = pager_lookup(pPager, pgno);
  45400. assert( !pPgOld || pPgOld->nRef==1 );
  45401. if( pPgOld ){
  45402. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  45403. if( MEMDB ){
  45404. /* Do not discard pages from an in-memory database since we might
  45405. ** need to rollback later. Just move the page out of the way. */
  45406. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  45407. }else{
  45408. sqlite3PcacheDrop(pPgOld);
  45409. }
  45410. }
  45411. origPgno = pPg->pgno;
  45412. sqlite3PcacheMove(pPg, pgno);
  45413. sqlite3PcacheMakeDirty(pPg);
  45414. /* For an in-memory database, make sure the original page continues
  45415. ** to exist, in case the transaction needs to roll back. Use pPgOld
  45416. ** as the original page since it has already been allocated.
  45417. */
  45418. if( MEMDB ){
  45419. assert( pPgOld );
  45420. sqlite3PcacheMove(pPgOld, origPgno);
  45421. sqlite3PagerUnref(pPgOld);
  45422. }
  45423. if( needSyncPgno ){
  45424. /* If needSyncPgno is non-zero, then the journal file needs to be
  45425. ** sync()ed before any data is written to database file page needSyncPgno.
  45426. ** Currently, no such page exists in the page-cache and the
  45427. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  45428. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  45429. ** flag.
  45430. **
  45431. ** If the attempt to load the page into the page-cache fails, (due
  45432. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  45433. ** array. Otherwise, if the page is loaded and written again in
  45434. ** this transaction, it may be written to the database file before
  45435. ** it is synced into the journal file. This way, it may end up in
  45436. ** the journal file twice, but that is not a problem.
  45437. */
  45438. PgHdr *pPgHdr;
  45439. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  45440. if( rc!=SQLITE_OK ){
  45441. if( needSyncPgno<=pPager->dbOrigSize ){
  45442. assert( pPager->pTmpSpace!=0 );
  45443. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  45444. }
  45445. return rc;
  45446. }
  45447. pPgHdr->flags |= PGHDR_NEED_SYNC;
  45448. sqlite3PcacheMakeDirty(pPgHdr);
  45449. sqlite3PagerUnref(pPgHdr);
  45450. }
  45451. return SQLITE_OK;
  45452. }
  45453. #endif
  45454. /*
  45455. ** Return a pointer to the data for the specified page.
  45456. */
  45457. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  45458. assert( pPg->nRef>0 || pPg->pPager->memDb );
  45459. return pPg->pData;
  45460. }
  45461. /*
  45462. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  45463. ** allocated along with the specified page.
  45464. */
  45465. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  45466. return pPg->pExtra;
  45467. }
  45468. /*
  45469. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  45470. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  45471. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  45472. ** the locking-mode is set to the value specified.
  45473. **
  45474. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  45475. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  45476. ** locking-mode.
  45477. */
  45478. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  45479. assert( eMode==PAGER_LOCKINGMODE_QUERY
  45480. || eMode==PAGER_LOCKINGMODE_NORMAL
  45481. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  45482. assert( PAGER_LOCKINGMODE_QUERY<0 );
  45483. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  45484. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  45485. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  45486. pPager->exclusiveMode = (u8)eMode;
  45487. }
  45488. return (int)pPager->exclusiveMode;
  45489. }
  45490. /*
  45491. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  45492. **
  45493. ** PAGER_JOURNALMODE_DELETE
  45494. ** PAGER_JOURNALMODE_TRUNCATE
  45495. ** PAGER_JOURNALMODE_PERSIST
  45496. ** PAGER_JOURNALMODE_OFF
  45497. ** PAGER_JOURNALMODE_MEMORY
  45498. ** PAGER_JOURNALMODE_WAL
  45499. **
  45500. ** The journalmode is set to the value specified if the change is allowed.
  45501. ** The change may be disallowed for the following reasons:
  45502. **
  45503. ** * An in-memory database can only have its journal_mode set to _OFF
  45504. ** or _MEMORY.
  45505. **
  45506. ** * Temporary databases cannot have _WAL journalmode.
  45507. **
  45508. ** The returned indicate the current (possibly updated) journal-mode.
  45509. */
  45510. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  45511. u8 eOld = pPager->journalMode; /* Prior journalmode */
  45512. #ifdef SQLITE_DEBUG
  45513. /* The print_pager_state() routine is intended to be used by the debugger
  45514. ** only. We invoke it once here to suppress a compiler warning. */
  45515. print_pager_state(pPager);
  45516. #endif
  45517. /* The eMode parameter is always valid */
  45518. assert( eMode==PAGER_JOURNALMODE_DELETE
  45519. || eMode==PAGER_JOURNALMODE_TRUNCATE
  45520. || eMode==PAGER_JOURNALMODE_PERSIST
  45521. || eMode==PAGER_JOURNALMODE_OFF
  45522. || eMode==PAGER_JOURNALMODE_WAL
  45523. || eMode==PAGER_JOURNALMODE_MEMORY );
  45524. /* This routine is only called from the OP_JournalMode opcode, and
  45525. ** the logic there will never allow a temporary file to be changed
  45526. ** to WAL mode.
  45527. */
  45528. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  45529. /* Do allow the journalmode of an in-memory database to be set to
  45530. ** anything other than MEMORY or OFF
  45531. */
  45532. if( MEMDB ){
  45533. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  45534. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  45535. eMode = eOld;
  45536. }
  45537. }
  45538. if( eMode!=eOld ){
  45539. /* Change the journal mode. */
  45540. assert( pPager->eState!=PAGER_ERROR );
  45541. pPager->journalMode = (u8)eMode;
  45542. /* When transistioning from TRUNCATE or PERSIST to any other journal
  45543. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  45544. ** delete the journal file.
  45545. */
  45546. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  45547. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  45548. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  45549. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  45550. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  45551. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  45552. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  45553. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  45554. /* In this case we would like to delete the journal file. If it is
  45555. ** not possible, then that is not a problem. Deleting the journal file
  45556. ** here is an optimization only.
  45557. **
  45558. ** Before deleting the journal file, obtain a RESERVED lock on the
  45559. ** database file. This ensures that the journal file is not deleted
  45560. ** while it is in use by some other client.
  45561. */
  45562. sqlite3OsClose(pPager->jfd);
  45563. if( pPager->eLock>=RESERVED_LOCK ){
  45564. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45565. }else{
  45566. int rc = SQLITE_OK;
  45567. int state = pPager->eState;
  45568. assert( state==PAGER_OPEN || state==PAGER_READER );
  45569. if( state==PAGER_OPEN ){
  45570. rc = sqlite3PagerSharedLock(pPager);
  45571. }
  45572. if( pPager->eState==PAGER_READER ){
  45573. assert( rc==SQLITE_OK );
  45574. rc = pagerLockDb(pPager, RESERVED_LOCK);
  45575. }
  45576. if( rc==SQLITE_OK ){
  45577. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45578. }
  45579. if( rc==SQLITE_OK && state==PAGER_READER ){
  45580. pagerUnlockDb(pPager, SHARED_LOCK);
  45581. }else if( state==PAGER_OPEN ){
  45582. pager_unlock(pPager);
  45583. }
  45584. assert( state==pPager->eState );
  45585. }
  45586. }
  45587. }
  45588. /* Return the new journal mode */
  45589. return (int)pPager->journalMode;
  45590. }
  45591. /*
  45592. ** Return the current journal mode.
  45593. */
  45594. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  45595. return (int)pPager->journalMode;
  45596. }
  45597. /*
  45598. ** Return TRUE if the pager is in a state where it is OK to change the
  45599. ** journalmode. Journalmode changes can only happen when the database
  45600. ** is unmodified.
  45601. */
  45602. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  45603. assert( assert_pager_state(pPager) );
  45604. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  45605. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  45606. return 1;
  45607. }
  45608. /*
  45609. ** Get/set the size-limit used for persistent journal files.
  45610. **
  45611. ** Setting the size limit to -1 means no limit is enforced.
  45612. ** An attempt to set a limit smaller than -1 is a no-op.
  45613. */
  45614. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  45615. if( iLimit>=-1 ){
  45616. pPager->journalSizeLimit = iLimit;
  45617. sqlite3WalLimit(pPager->pWal, iLimit);
  45618. }
  45619. return pPager->journalSizeLimit;
  45620. }
  45621. /*
  45622. ** Return a pointer to the pPager->pBackup variable. The backup module
  45623. ** in backup.c maintains the content of this variable. This module
  45624. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  45625. ** sqlite3BackupUpdate() only.
  45626. */
  45627. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  45628. return &pPager->pBackup;
  45629. }
  45630. #ifndef SQLITE_OMIT_VACUUM
  45631. /*
  45632. ** Unless this is an in-memory or temporary database, clear the pager cache.
  45633. */
  45634. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  45635. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  45636. }
  45637. #endif
  45638. #ifndef SQLITE_OMIT_WAL
  45639. /*
  45640. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  45641. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  45642. ** or wal_blocking_checkpoint() API functions.
  45643. **
  45644. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  45645. */
  45646. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  45647. int rc = SQLITE_OK;
  45648. if( pPager->pWal ){
  45649. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  45650. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  45651. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  45652. pnLog, pnCkpt
  45653. );
  45654. }
  45655. return rc;
  45656. }
  45657. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  45658. return sqlite3WalCallback(pPager->pWal);
  45659. }
  45660. /*
  45661. ** Return true if the underlying VFS for the given pager supports the
  45662. ** primitives necessary for write-ahead logging.
  45663. */
  45664. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  45665. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  45666. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  45667. }
  45668. /*
  45669. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  45670. ** is obtained instead, immediately release it.
  45671. */
  45672. static int pagerExclusiveLock(Pager *pPager){
  45673. int rc; /* Return code */
  45674. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45675. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45676. if( rc!=SQLITE_OK ){
  45677. /* If the attempt to grab the exclusive lock failed, release the
  45678. ** pending lock that may have been obtained instead. */
  45679. pagerUnlockDb(pPager, SHARED_LOCK);
  45680. }
  45681. return rc;
  45682. }
  45683. /*
  45684. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  45685. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  45686. ** lock on the database file and use heap-memory to store the wal-index
  45687. ** in. Otherwise, use the normal shared-memory.
  45688. */
  45689. static int pagerOpenWal(Pager *pPager){
  45690. int rc = SQLITE_OK;
  45691. assert( pPager->pWal==0 && pPager->tempFile==0 );
  45692. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45693. /* If the pager is already in exclusive-mode, the WAL module will use
  45694. ** heap-memory for the wal-index instead of the VFS shared-memory
  45695. ** implementation. Take the exclusive lock now, before opening the WAL
  45696. ** file, to make sure this is safe.
  45697. */
  45698. if( pPager->exclusiveMode ){
  45699. rc = pagerExclusiveLock(pPager);
  45700. }
  45701. /* Open the connection to the log file. If this operation fails,
  45702. ** (e.g. due to malloc() failure), return an error code.
  45703. */
  45704. if( rc==SQLITE_OK ){
  45705. rc = sqlite3WalOpen(pPager->pVfs,
  45706. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  45707. pPager->journalSizeLimit, &pPager->pWal
  45708. );
  45709. }
  45710. pagerFixMaplimit(pPager);
  45711. return rc;
  45712. }
  45713. /*
  45714. ** The caller must be holding a SHARED lock on the database file to call
  45715. ** this function.
  45716. **
  45717. ** If the pager passed as the first argument is open on a real database
  45718. ** file (not a temp file or an in-memory database), and the WAL file
  45719. ** is not already open, make an attempt to open it now. If successful,
  45720. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  45721. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  45722. ** not modified in either case.
  45723. **
  45724. ** If the pager is open on a temp-file (or in-memory database), or if
  45725. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  45726. ** without doing anything.
  45727. */
  45728. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  45729. Pager *pPager, /* Pager object */
  45730. int *pbOpen /* OUT: Set to true if call is a no-op */
  45731. ){
  45732. int rc = SQLITE_OK; /* Return code */
  45733. assert( assert_pager_state(pPager) );
  45734. assert( pPager->eState==PAGER_OPEN || pbOpen );
  45735. assert( pPager->eState==PAGER_READER || !pbOpen );
  45736. assert( pbOpen==0 || *pbOpen==0 );
  45737. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  45738. if( !pPager->tempFile && !pPager->pWal ){
  45739. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  45740. /* Close any rollback journal previously open */
  45741. sqlite3OsClose(pPager->jfd);
  45742. rc = pagerOpenWal(pPager);
  45743. if( rc==SQLITE_OK ){
  45744. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  45745. pPager->eState = PAGER_OPEN;
  45746. }
  45747. }else{
  45748. *pbOpen = 1;
  45749. }
  45750. return rc;
  45751. }
  45752. /*
  45753. ** This function is called to close the connection to the log file prior
  45754. ** to switching from WAL to rollback mode.
  45755. **
  45756. ** Before closing the log file, this function attempts to take an
  45757. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  45758. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  45759. ** If successful, the EXCLUSIVE lock is not released before returning.
  45760. */
  45761. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  45762. int rc = SQLITE_OK;
  45763. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  45764. /* If the log file is not already open, but does exist in the file-system,
  45765. ** it may need to be checkpointed before the connection can switch to
  45766. ** rollback mode. Open it now so this can happen.
  45767. */
  45768. if( !pPager->pWal ){
  45769. int logexists = 0;
  45770. rc = pagerLockDb(pPager, SHARED_LOCK);
  45771. if( rc==SQLITE_OK ){
  45772. rc = sqlite3OsAccess(
  45773. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  45774. );
  45775. }
  45776. if( rc==SQLITE_OK && logexists ){
  45777. rc = pagerOpenWal(pPager);
  45778. }
  45779. }
  45780. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  45781. ** the database file, the log and log-summary files will be deleted.
  45782. */
  45783. if( rc==SQLITE_OK && pPager->pWal ){
  45784. rc = pagerExclusiveLock(pPager);
  45785. if( rc==SQLITE_OK ){
  45786. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  45787. pPager->pageSize, (u8*)pPager->pTmpSpace);
  45788. pPager->pWal = 0;
  45789. pagerFixMaplimit(pPager);
  45790. }
  45791. }
  45792. return rc;
  45793. }
  45794. #endif /* !SQLITE_OMIT_WAL */
  45795. #ifdef SQLITE_ENABLE_ZIPVFS
  45796. /*
  45797. ** A read-lock must be held on the pager when this function is called. If
  45798. ** the pager is in WAL mode and the WAL file currently contains one or more
  45799. ** frames, return the size in bytes of the page images stored within the
  45800. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  45801. ** is empty, return 0.
  45802. */
  45803. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  45804. assert( pPager->eState==PAGER_READER );
  45805. return sqlite3WalFramesize(pPager->pWal);
  45806. }
  45807. #endif
  45808. #endif /* SQLITE_OMIT_DISKIO */
  45809. /************** End of pager.c ***********************************************/
  45810. /************** Begin file wal.c *********************************************/
  45811. /*
  45812. ** 2010 February 1
  45813. **
  45814. ** The author disclaims copyright to this source code. In place of
  45815. ** a legal notice, here is a blessing:
  45816. **
  45817. ** May you do good and not evil.
  45818. ** May you find forgiveness for yourself and forgive others.
  45819. ** May you share freely, never taking more than you give.
  45820. **
  45821. *************************************************************************
  45822. **
  45823. ** This file contains the implementation of a write-ahead log (WAL) used in
  45824. ** "journal_mode=WAL" mode.
  45825. **
  45826. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  45827. **
  45828. ** A WAL file consists of a header followed by zero or more "frames".
  45829. ** Each frame records the revised content of a single page from the
  45830. ** database file. All changes to the database are recorded by writing
  45831. ** frames into the WAL. Transactions commit when a frame is written that
  45832. ** contains a commit marker. A single WAL can and usually does record
  45833. ** multiple transactions. Periodically, the content of the WAL is
  45834. ** transferred back into the database file in an operation called a
  45835. ** "checkpoint".
  45836. **
  45837. ** A single WAL file can be used multiple times. In other words, the
  45838. ** WAL can fill up with frames and then be checkpointed and then new
  45839. ** frames can overwrite the old ones. A WAL always grows from beginning
  45840. ** toward the end. Checksums and counters attached to each frame are
  45841. ** used to determine which frames within the WAL are valid and which
  45842. ** are leftovers from prior checkpoints.
  45843. **
  45844. ** The WAL header is 32 bytes in size and consists of the following eight
  45845. ** big-endian 32-bit unsigned integer values:
  45846. **
  45847. ** 0: Magic number. 0x377f0682 or 0x377f0683
  45848. ** 4: File format version. Currently 3007000
  45849. ** 8: Database page size. Example: 1024
  45850. ** 12: Checkpoint sequence number
  45851. ** 16: Salt-1, random integer incremented with each checkpoint
  45852. ** 20: Salt-2, a different random integer changing with each ckpt
  45853. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  45854. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  45855. **
  45856. ** Immediately following the wal-header are zero or more frames. Each
  45857. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  45858. ** of page data. The frame-header is six big-endian 32-bit unsigned
  45859. ** integer values, as follows:
  45860. **
  45861. ** 0: Page number.
  45862. ** 4: For commit records, the size of the database image in pages
  45863. ** after the commit. For all other records, zero.
  45864. ** 8: Salt-1 (copied from the header)
  45865. ** 12: Salt-2 (copied from the header)
  45866. ** 16: Checksum-1.
  45867. ** 20: Checksum-2.
  45868. **
  45869. ** A frame is considered valid if and only if the following conditions are
  45870. ** true:
  45871. **
  45872. ** (1) The salt-1 and salt-2 values in the frame-header match
  45873. ** salt values in the wal-header
  45874. **
  45875. ** (2) The checksum values in the final 8 bytes of the frame-header
  45876. ** exactly match the checksum computed consecutively on the
  45877. ** WAL header and the first 8 bytes and the content of all frames
  45878. ** up to and including the current frame.
  45879. **
  45880. ** The checksum is computed using 32-bit big-endian integers if the
  45881. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  45882. ** is computed using little-endian if the magic number is 0x377f0682.
  45883. ** The checksum values are always stored in the frame header in a
  45884. ** big-endian format regardless of which byte order is used to compute
  45885. ** the checksum. The checksum is computed by interpreting the input as
  45886. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  45887. ** algorithm used for the checksum is as follows:
  45888. **
  45889. ** for i from 0 to n-1 step 2:
  45890. ** s0 += x[i] + s1;
  45891. ** s1 += x[i+1] + s0;
  45892. ** endfor
  45893. **
  45894. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  45895. ** in reverse order (the largest fibonacci weight occurs on the first element
  45896. ** of the sequence being summed.) The s1 value spans all 32-bit
  45897. ** terms of the sequence whereas s0 omits the final term.
  45898. **
  45899. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  45900. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  45901. ** The VFS.xSync operations serve as write barriers - all writes launched
  45902. ** before the xSync must complete before any write that launches after the
  45903. ** xSync begins.
  45904. **
  45905. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  45906. ** value is randomized. This prevents old and new frames in the WAL from
  45907. ** being considered valid at the same time and being checkpointing together
  45908. ** following a crash.
  45909. **
  45910. ** READER ALGORITHM
  45911. **
  45912. ** To read a page from the database (call it page number P), a reader
  45913. ** first checks the WAL to see if it contains page P. If so, then the
  45914. ** last valid instance of page P that is a followed by a commit frame
  45915. ** or is a commit frame itself becomes the value read. If the WAL
  45916. ** contains no copies of page P that are valid and which are a commit
  45917. ** frame or are followed by a commit frame, then page P is read from
  45918. ** the database file.
  45919. **
  45920. ** To start a read transaction, the reader records the index of the last
  45921. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  45922. ** for all subsequent read operations. New transactions can be appended
  45923. ** to the WAL, but as long as the reader uses its original mxFrame value
  45924. ** and ignores the newly appended content, it will see a consistent snapshot
  45925. ** of the database from a single point in time. This technique allows
  45926. ** multiple concurrent readers to view different versions of the database
  45927. ** content simultaneously.
  45928. **
  45929. ** The reader algorithm in the previous paragraphs works correctly, but
  45930. ** because frames for page P can appear anywhere within the WAL, the
  45931. ** reader has to scan the entire WAL looking for page P frames. If the
  45932. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  45933. ** and read performance suffers. To overcome this problem, a separate
  45934. ** data structure called the wal-index is maintained to expedite the
  45935. ** search for frames of a particular page.
  45936. **
  45937. ** WAL-INDEX FORMAT
  45938. **
  45939. ** Conceptually, the wal-index is shared memory, though VFS implementations
  45940. ** might choose to implement the wal-index using a mmapped file. Because
  45941. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  45942. ** on a network filesystem. All users of the database must be able to
  45943. ** share memory.
  45944. **
  45945. ** The wal-index is transient. After a crash, the wal-index can (and should
  45946. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  45947. ** to either truncate or zero the header of the wal-index when the last
  45948. ** connection to it closes. Because the wal-index is transient, it can
  45949. ** use an architecture-specific format; it does not have to be cross-platform.
  45950. ** Hence, unlike the database and WAL file formats which store all values
  45951. ** as big endian, the wal-index can store multi-byte values in the native
  45952. ** byte order of the host computer.
  45953. **
  45954. ** The purpose of the wal-index is to answer this question quickly: Given
  45955. ** a page number P and a maximum frame index M, return the index of the
  45956. ** last frame in the wal before frame M for page P in the WAL, or return
  45957. ** NULL if there are no frames for page P in the WAL prior to M.
  45958. **
  45959. ** The wal-index consists of a header region, followed by an one or
  45960. ** more index blocks.
  45961. **
  45962. ** The wal-index header contains the total number of frames within the WAL
  45963. ** in the mxFrame field.
  45964. **
  45965. ** Each index block except for the first contains information on
  45966. ** HASHTABLE_NPAGE frames. The first index block contains information on
  45967. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  45968. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  45969. ** first index block are the same size as all other index blocks in the
  45970. ** wal-index.
  45971. **
  45972. ** Each index block contains two sections, a page-mapping that contains the
  45973. ** database page number associated with each wal frame, and a hash-table
  45974. ** that allows readers to query an index block for a specific page number.
  45975. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  45976. ** for the first index block) 32-bit page numbers. The first entry in the
  45977. ** first index-block contains the database page number corresponding to the
  45978. ** first frame in the WAL file. The first entry in the second index block
  45979. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  45980. ** the log, and so on.
  45981. **
  45982. ** The last index block in a wal-index usually contains less than the full
  45983. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  45984. ** depending on the contents of the WAL file. This does not change the
  45985. ** allocated size of the page-mapping array - the page-mapping array merely
  45986. ** contains unused entries.
  45987. **
  45988. ** Even without using the hash table, the last frame for page P
  45989. ** can be found by scanning the page-mapping sections of each index block
  45990. ** starting with the last index block and moving toward the first, and
  45991. ** within each index block, starting at the end and moving toward the
  45992. ** beginning. The first entry that equals P corresponds to the frame
  45993. ** holding the content for that page.
  45994. **
  45995. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  45996. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  45997. ** hash table for each page number in the mapping section, so the hash
  45998. ** table is never more than half full. The expected number of collisions
  45999. ** prior to finding a match is 1. Each entry of the hash table is an
  46000. ** 1-based index of an entry in the mapping section of the same
  46001. ** index block. Let K be the 1-based index of the largest entry in
  46002. ** the mapping section. (For index blocks other than the last, K will
  46003. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  46004. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  46005. ** contain a value of 0.
  46006. **
  46007. ** To look for page P in the hash table, first compute a hash iKey on
  46008. ** P as follows:
  46009. **
  46010. ** iKey = (P * 383) % HASHTABLE_NSLOT
  46011. **
  46012. ** Then start scanning entries of the hash table, starting with iKey
  46013. ** (wrapping around to the beginning when the end of the hash table is
  46014. ** reached) until an unused hash slot is found. Let the first unused slot
  46015. ** be at index iUnused. (iUnused might be less than iKey if there was
  46016. ** wrap-around.) Because the hash table is never more than half full,
  46017. ** the search is guaranteed to eventually hit an unused entry. Let
  46018. ** iMax be the value between iKey and iUnused, closest to iUnused,
  46019. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  46020. ** no hash slot such that aHash[i]==p) then page P is not in the
  46021. ** current index block. Otherwise the iMax-th mapping entry of the
  46022. ** current index block corresponds to the last entry that references
  46023. ** page P.
  46024. **
  46025. ** A hash search begins with the last index block and moves toward the
  46026. ** first index block, looking for entries corresponding to page P. On
  46027. ** average, only two or three slots in each index block need to be
  46028. ** examined in order to either find the last entry for page P, or to
  46029. ** establish that no such entry exists in the block. Each index block
  46030. ** holds over 4000 entries. So two or three index blocks are sufficient
  46031. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  46032. ** comparisons (on average) suffice to either locate a frame in the
  46033. ** WAL or to establish that the frame does not exist in the WAL. This
  46034. ** is much faster than scanning the entire 10MB WAL.
  46035. **
  46036. ** Note that entries are added in order of increasing K. Hence, one
  46037. ** reader might be using some value K0 and a second reader that started
  46038. ** at a later time (after additional transactions were added to the WAL
  46039. ** and to the wal-index) might be using a different value K1, where K1>K0.
  46040. ** Both readers can use the same hash table and mapping section to get
  46041. ** the correct result. There may be entries in the hash table with
  46042. ** K>K0 but to the first reader, those entries will appear to be unused
  46043. ** slots in the hash table and so the first reader will get an answer as
  46044. ** if no values greater than K0 had ever been inserted into the hash table
  46045. ** in the first place - which is what reader one wants. Meanwhile, the
  46046. ** second reader using K1 will see additional values that were inserted
  46047. ** later, which is exactly what reader two wants.
  46048. **
  46049. ** When a rollback occurs, the value of K is decreased. Hash table entries
  46050. ** that correspond to frames greater than the new K value are removed
  46051. ** from the hash table at this point.
  46052. */
  46053. #ifndef SQLITE_OMIT_WAL
  46054. /*
  46055. ** Trace output macros
  46056. */
  46057. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46058. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  46059. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  46060. #else
  46061. # define WALTRACE(X)
  46062. #endif
  46063. /*
  46064. ** The maximum (and only) versions of the wal and wal-index formats
  46065. ** that may be interpreted by this version of SQLite.
  46066. **
  46067. ** If a client begins recovering a WAL file and finds that (a) the checksum
  46068. ** values in the wal-header are correct and (b) the version field is not
  46069. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  46070. **
  46071. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  46072. ** checksum test is successful) and finds that the version field is not
  46073. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  46074. ** returns SQLITE_CANTOPEN.
  46075. */
  46076. #define WAL_MAX_VERSION 3007000
  46077. #define WALINDEX_MAX_VERSION 3007000
  46078. /*
  46079. ** Indices of various locking bytes. WAL_NREADER is the number
  46080. ** of available reader locks and should be at least 3.
  46081. */
  46082. #define WAL_WRITE_LOCK 0
  46083. #define WAL_ALL_BUT_WRITE 1
  46084. #define WAL_CKPT_LOCK 1
  46085. #define WAL_RECOVER_LOCK 2
  46086. #define WAL_READ_LOCK(I) (3+(I))
  46087. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  46088. /* Object declarations */
  46089. typedef struct WalIndexHdr WalIndexHdr;
  46090. typedef struct WalIterator WalIterator;
  46091. typedef struct WalCkptInfo WalCkptInfo;
  46092. /*
  46093. ** The following object holds a copy of the wal-index header content.
  46094. **
  46095. ** The actual header in the wal-index consists of two copies of this
  46096. ** object.
  46097. **
  46098. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  46099. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  46100. ** added in 3.7.1 when support for 64K pages was added.
  46101. */
  46102. struct WalIndexHdr {
  46103. u32 iVersion; /* Wal-index version */
  46104. u32 unused; /* Unused (padding) field */
  46105. u32 iChange; /* Counter incremented each transaction */
  46106. u8 isInit; /* 1 when initialized */
  46107. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  46108. u16 szPage; /* Database page size in bytes. 1==64K */
  46109. u32 mxFrame; /* Index of last valid frame in the WAL */
  46110. u32 nPage; /* Size of database in pages */
  46111. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  46112. u32 aSalt[2]; /* Two salt values copied from WAL header */
  46113. u32 aCksum[2]; /* Checksum over all prior fields */
  46114. };
  46115. /*
  46116. ** A copy of the following object occurs in the wal-index immediately
  46117. ** following the second copy of the WalIndexHdr. This object stores
  46118. ** information used by checkpoint.
  46119. **
  46120. ** nBackfill is the number of frames in the WAL that have been written
  46121. ** back into the database. (We call the act of moving content from WAL to
  46122. ** database "backfilling".) The nBackfill number is never greater than
  46123. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  46124. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  46125. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  46126. ** mxFrame back to zero when the WAL is reset.
  46127. **
  46128. ** There is one entry in aReadMark[] for each reader lock. If a reader
  46129. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  46130. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  46131. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  46132. ** a special case; its value is never used and it exists as a place-holder
  46133. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  46134. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  46135. ** directly from the database.
  46136. **
  46137. ** The value of aReadMark[K] may only be changed by a thread that
  46138. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  46139. ** aReadMark[K] cannot changed while there is a reader is using that mark
  46140. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  46141. **
  46142. ** The checkpointer may only transfer frames from WAL to database where
  46143. ** the frame numbers are less than or equal to every aReadMark[] that is
  46144. ** in use (that is, every aReadMark[j] for which there is a corresponding
  46145. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  46146. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  46147. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  46148. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  46149. ** in the WAL has been backfilled into the database) then new readers
  46150. ** will choose aReadMark[0] which has value 0 and hence such reader will
  46151. ** get all their all content directly from the database file and ignore
  46152. ** the WAL.
  46153. **
  46154. ** Writers normally append new frames to the end of the WAL. However,
  46155. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  46156. ** written back into the database) and if no readers are using the WAL
  46157. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  46158. ** the writer will first "reset" the WAL back to the beginning and start
  46159. ** writing new content beginning at frame 1.
  46160. **
  46161. ** We assume that 32-bit loads are atomic and so no locks are needed in
  46162. ** order to read from any aReadMark[] entries.
  46163. */
  46164. struct WalCkptInfo {
  46165. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  46166. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  46167. };
  46168. #define READMARK_NOT_USED 0xffffffff
  46169. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  46170. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  46171. ** only support mandatory file-locks, we do not read or write data
  46172. ** from the region of the file on which locks are applied.
  46173. */
  46174. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  46175. #define WALINDEX_LOCK_RESERVED 16
  46176. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  46177. /* Size of header before each frame in wal */
  46178. #define WAL_FRAME_HDRSIZE 24
  46179. /* Size of write ahead log header, including checksum. */
  46180. /* #define WAL_HDRSIZE 24 */
  46181. #define WAL_HDRSIZE 32
  46182. /* WAL magic value. Either this value, or the same value with the least
  46183. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  46184. ** big-endian format in the first 4 bytes of a WAL file.
  46185. **
  46186. ** If the LSB is set, then the checksums for each frame within the WAL
  46187. ** file are calculated by treating all data as an array of 32-bit
  46188. ** big-endian words. Otherwise, they are calculated by interpreting
  46189. ** all data as 32-bit little-endian words.
  46190. */
  46191. #define WAL_MAGIC 0x377f0682
  46192. /*
  46193. ** Return the offset of frame iFrame in the write-ahead log file,
  46194. ** assuming a database page size of szPage bytes. The offset returned
  46195. ** is to the start of the write-ahead log frame-header.
  46196. */
  46197. #define walFrameOffset(iFrame, szPage) ( \
  46198. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  46199. )
  46200. /*
  46201. ** An open write-ahead log file is represented by an instance of the
  46202. ** following object.
  46203. */
  46204. struct Wal {
  46205. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  46206. sqlite3_file *pDbFd; /* File handle for the database file */
  46207. sqlite3_file *pWalFd; /* File handle for WAL file */
  46208. u32 iCallback; /* Value to pass to log callback (or 0) */
  46209. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  46210. int nWiData; /* Size of array apWiData */
  46211. int szFirstBlock; /* Size of first block written to WAL file */
  46212. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  46213. u32 szPage; /* Database page size */
  46214. i16 readLock; /* Which read lock is being held. -1 for none */
  46215. u8 syncFlags; /* Flags to use to sync header writes */
  46216. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  46217. u8 writeLock; /* True if in a write transaction */
  46218. u8 ckptLock; /* True if holding a checkpoint lock */
  46219. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  46220. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  46221. u8 syncHeader; /* Fsync the WAL header if true */
  46222. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  46223. WalIndexHdr hdr; /* Wal-index header for current transaction */
  46224. const char *zWalName; /* Name of WAL file */
  46225. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  46226. #ifdef SQLITE_DEBUG
  46227. u8 lockError; /* True if a locking error has occurred */
  46228. #endif
  46229. };
  46230. /*
  46231. ** Candidate values for Wal.exclusiveMode.
  46232. */
  46233. #define WAL_NORMAL_MODE 0
  46234. #define WAL_EXCLUSIVE_MODE 1
  46235. #define WAL_HEAPMEMORY_MODE 2
  46236. /*
  46237. ** Possible values for WAL.readOnly
  46238. */
  46239. #define WAL_RDWR 0 /* Normal read/write connection */
  46240. #define WAL_RDONLY 1 /* The WAL file is readonly */
  46241. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  46242. /*
  46243. ** Each page of the wal-index mapping contains a hash-table made up of
  46244. ** an array of HASHTABLE_NSLOT elements of the following type.
  46245. */
  46246. typedef u16 ht_slot;
  46247. /*
  46248. ** This structure is used to implement an iterator that loops through
  46249. ** all frames in the WAL in database page order. Where two or more frames
  46250. ** correspond to the same database page, the iterator visits only the
  46251. ** frame most recently written to the WAL (in other words, the frame with
  46252. ** the largest index).
  46253. **
  46254. ** The internals of this structure are only accessed by:
  46255. **
  46256. ** walIteratorInit() - Create a new iterator,
  46257. ** walIteratorNext() - Step an iterator,
  46258. ** walIteratorFree() - Free an iterator.
  46259. **
  46260. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  46261. */
  46262. struct WalIterator {
  46263. int iPrior; /* Last result returned from the iterator */
  46264. int nSegment; /* Number of entries in aSegment[] */
  46265. struct WalSegment {
  46266. int iNext; /* Next slot in aIndex[] not yet returned */
  46267. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  46268. u32 *aPgno; /* Array of page numbers. */
  46269. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  46270. int iZero; /* Frame number associated with aPgno[0] */
  46271. } aSegment[1]; /* One for every 32KB page in the wal-index */
  46272. };
  46273. /*
  46274. ** Define the parameters of the hash tables in the wal-index file. There
  46275. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  46276. ** wal-index.
  46277. **
  46278. ** Changing any of these constants will alter the wal-index format and
  46279. ** create incompatibilities.
  46280. */
  46281. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  46282. #define HASHTABLE_HASH_1 383 /* Should be prime */
  46283. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  46284. /*
  46285. ** The block of page numbers associated with the first hash-table in a
  46286. ** wal-index is smaller than usual. This is so that there is a complete
  46287. ** hash-table on each aligned 32KB page of the wal-index.
  46288. */
  46289. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  46290. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  46291. #define WALINDEX_PGSZ ( \
  46292. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  46293. )
  46294. /*
  46295. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  46296. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  46297. ** numbered from zero.
  46298. **
  46299. ** If this call is successful, *ppPage is set to point to the wal-index
  46300. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  46301. ** then an SQLite error code is returned and *ppPage is set to 0.
  46302. */
  46303. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  46304. int rc = SQLITE_OK;
  46305. /* Enlarge the pWal->apWiData[] array if required */
  46306. if( pWal->nWiData<=iPage ){
  46307. int nByte = sizeof(u32*)*(iPage+1);
  46308. volatile u32 **apNew;
  46309. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  46310. if( !apNew ){
  46311. *ppPage = 0;
  46312. return SQLITE_NOMEM;
  46313. }
  46314. memset((void*)&apNew[pWal->nWiData], 0,
  46315. sizeof(u32*)*(iPage+1-pWal->nWiData));
  46316. pWal->apWiData = apNew;
  46317. pWal->nWiData = iPage+1;
  46318. }
  46319. /* Request a pointer to the required page from the VFS */
  46320. if( pWal->apWiData[iPage]==0 ){
  46321. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46322. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  46323. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  46324. }else{
  46325. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  46326. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  46327. );
  46328. if( rc==SQLITE_READONLY ){
  46329. pWal->readOnly |= WAL_SHM_RDONLY;
  46330. rc = SQLITE_OK;
  46331. }
  46332. }
  46333. }
  46334. *ppPage = pWal->apWiData[iPage];
  46335. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  46336. return rc;
  46337. }
  46338. /*
  46339. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  46340. */
  46341. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  46342. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46343. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  46344. }
  46345. /*
  46346. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  46347. */
  46348. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  46349. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46350. return (volatile WalIndexHdr*)pWal->apWiData[0];
  46351. }
  46352. /*
  46353. ** The argument to this macro must be of type u32. On a little-endian
  46354. ** architecture, it returns the u32 value that results from interpreting
  46355. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  46356. ** returns the value that would be produced by intepreting the 4 bytes
  46357. ** of the input value as a little-endian integer.
  46358. */
  46359. #define BYTESWAP32(x) ( \
  46360. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  46361. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  46362. )
  46363. /*
  46364. ** Generate or extend an 8 byte checksum based on the data in
  46365. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  46366. ** initial values of 0 and 0 if aIn==NULL).
  46367. **
  46368. ** The checksum is written back into aOut[] before returning.
  46369. **
  46370. ** nByte must be a positive multiple of 8.
  46371. */
  46372. static void walChecksumBytes(
  46373. int nativeCksum, /* True for native byte-order, false for non-native */
  46374. u8 *a, /* Content to be checksummed */
  46375. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  46376. const u32 *aIn, /* Initial checksum value input */
  46377. u32 *aOut /* OUT: Final checksum value output */
  46378. ){
  46379. u32 s1, s2;
  46380. u32 *aData = (u32 *)a;
  46381. u32 *aEnd = (u32 *)&a[nByte];
  46382. if( aIn ){
  46383. s1 = aIn[0];
  46384. s2 = aIn[1];
  46385. }else{
  46386. s1 = s2 = 0;
  46387. }
  46388. assert( nByte>=8 );
  46389. assert( (nByte&0x00000007)==0 );
  46390. if( nativeCksum ){
  46391. do {
  46392. s1 += *aData++ + s2;
  46393. s2 += *aData++ + s1;
  46394. }while( aData<aEnd );
  46395. }else{
  46396. do {
  46397. s1 += BYTESWAP32(aData[0]) + s2;
  46398. s2 += BYTESWAP32(aData[1]) + s1;
  46399. aData += 2;
  46400. }while( aData<aEnd );
  46401. }
  46402. aOut[0] = s1;
  46403. aOut[1] = s2;
  46404. }
  46405. static void walShmBarrier(Wal *pWal){
  46406. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  46407. sqlite3OsShmBarrier(pWal->pDbFd);
  46408. }
  46409. }
  46410. /*
  46411. ** Write the header information in pWal->hdr into the wal-index.
  46412. **
  46413. ** The checksum on pWal->hdr is updated before it is written.
  46414. */
  46415. static void walIndexWriteHdr(Wal *pWal){
  46416. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  46417. const int nCksum = offsetof(WalIndexHdr, aCksum);
  46418. assert( pWal->writeLock );
  46419. pWal->hdr.isInit = 1;
  46420. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  46421. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  46422. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46423. walShmBarrier(pWal);
  46424. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46425. }
  46426. /*
  46427. ** This function encodes a single frame header and writes it to a buffer
  46428. ** supplied by the caller. A frame-header is made up of a series of
  46429. ** 4-byte big-endian integers, as follows:
  46430. **
  46431. ** 0: Page number.
  46432. ** 4: For commit records, the size of the database image in pages
  46433. ** after the commit. For all other records, zero.
  46434. ** 8: Salt-1 (copied from the wal-header)
  46435. ** 12: Salt-2 (copied from the wal-header)
  46436. ** 16: Checksum-1.
  46437. ** 20: Checksum-2.
  46438. */
  46439. static void walEncodeFrame(
  46440. Wal *pWal, /* The write-ahead log */
  46441. u32 iPage, /* Database page number for frame */
  46442. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  46443. u8 *aData, /* Pointer to page data */
  46444. u8 *aFrame /* OUT: Write encoded frame here */
  46445. ){
  46446. int nativeCksum; /* True for native byte-order checksums */
  46447. u32 *aCksum = pWal->hdr.aFrameCksum;
  46448. assert( WAL_FRAME_HDRSIZE==24 );
  46449. sqlite3Put4byte(&aFrame[0], iPage);
  46450. sqlite3Put4byte(&aFrame[4], nTruncate);
  46451. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  46452. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46453. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46454. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46455. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  46456. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  46457. }
  46458. /*
  46459. ** Check to see if the frame with header in aFrame[] and content
  46460. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  46461. ** *pnTruncate and return true. Return if the frame is not valid.
  46462. */
  46463. static int walDecodeFrame(
  46464. Wal *pWal, /* The write-ahead log */
  46465. u32 *piPage, /* OUT: Database page number for frame */
  46466. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  46467. u8 *aData, /* Pointer to page data (for checksum) */
  46468. u8 *aFrame /* Frame data */
  46469. ){
  46470. int nativeCksum; /* True for native byte-order checksums */
  46471. u32 *aCksum = pWal->hdr.aFrameCksum;
  46472. u32 pgno; /* Page number of the frame */
  46473. assert( WAL_FRAME_HDRSIZE==24 );
  46474. /* A frame is only valid if the salt values in the frame-header
  46475. ** match the salt values in the wal-header.
  46476. */
  46477. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  46478. return 0;
  46479. }
  46480. /* A frame is only valid if the page number is creater than zero.
  46481. */
  46482. pgno = sqlite3Get4byte(&aFrame[0]);
  46483. if( pgno==0 ){
  46484. return 0;
  46485. }
  46486. /* A frame is only valid if a checksum of the WAL header,
  46487. ** all prior frams, the first 16 bytes of this frame-header,
  46488. ** and the frame-data matches the checksum in the last 8
  46489. ** bytes of this frame-header.
  46490. */
  46491. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46492. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46493. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46494. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  46495. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  46496. ){
  46497. /* Checksum failed. */
  46498. return 0;
  46499. }
  46500. /* If we reach this point, the frame is valid. Return the page number
  46501. ** and the new database size.
  46502. */
  46503. *piPage = pgno;
  46504. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  46505. return 1;
  46506. }
  46507. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46508. /*
  46509. ** Names of locks. This routine is used to provide debugging output and is not
  46510. ** a part of an ordinary build.
  46511. */
  46512. static const char *walLockName(int lockIdx){
  46513. if( lockIdx==WAL_WRITE_LOCK ){
  46514. return "WRITE-LOCK";
  46515. }else if( lockIdx==WAL_CKPT_LOCK ){
  46516. return "CKPT-LOCK";
  46517. }else if( lockIdx==WAL_RECOVER_LOCK ){
  46518. return "RECOVER-LOCK";
  46519. }else{
  46520. static char zName[15];
  46521. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  46522. lockIdx-WAL_READ_LOCK(0));
  46523. return zName;
  46524. }
  46525. }
  46526. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  46527. /*
  46528. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  46529. ** A lock cannot be moved directly between shared and exclusive - it must go
  46530. ** through the unlocked state first.
  46531. **
  46532. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  46533. */
  46534. static int walLockShared(Wal *pWal, int lockIdx){
  46535. int rc;
  46536. if( pWal->exclusiveMode ) return SQLITE_OK;
  46537. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46538. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  46539. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  46540. walLockName(lockIdx), rc ? "failed" : "ok"));
  46541. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46542. return rc;
  46543. }
  46544. static void walUnlockShared(Wal *pWal, int lockIdx){
  46545. if( pWal->exclusiveMode ) return;
  46546. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46547. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  46548. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  46549. }
  46550. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  46551. int rc;
  46552. if( pWal->exclusiveMode ) return SQLITE_OK;
  46553. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46554. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  46555. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  46556. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  46557. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46558. return rc;
  46559. }
  46560. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  46561. if( pWal->exclusiveMode ) return;
  46562. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46563. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  46564. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  46565. walLockName(lockIdx), n));
  46566. }
  46567. /*
  46568. ** Compute a hash on a page number. The resulting hash value must land
  46569. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  46570. ** the hash to the next value in the event of a collision.
  46571. */
  46572. static int walHash(u32 iPage){
  46573. assert( iPage>0 );
  46574. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  46575. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  46576. }
  46577. static int walNextHash(int iPriorHash){
  46578. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  46579. }
  46580. /*
  46581. ** Return pointers to the hash table and page number array stored on
  46582. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  46583. ** numbered starting from 0.
  46584. **
  46585. ** Set output variable *paHash to point to the start of the hash table
  46586. ** in the wal-index file. Set *piZero to one less than the frame
  46587. ** number of the first frame indexed by this hash table. If a
  46588. ** slot in the hash table is set to N, it refers to frame number
  46589. ** (*piZero+N) in the log.
  46590. **
  46591. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  46592. ** first frame indexed by the hash table, frame (*piZero+1).
  46593. */
  46594. static int walHashGet(
  46595. Wal *pWal, /* WAL handle */
  46596. int iHash, /* Find the iHash'th table */
  46597. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  46598. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  46599. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  46600. ){
  46601. int rc; /* Return code */
  46602. volatile u32 *aPgno;
  46603. rc = walIndexPage(pWal, iHash, &aPgno);
  46604. assert( rc==SQLITE_OK || iHash>0 );
  46605. if( rc==SQLITE_OK ){
  46606. u32 iZero;
  46607. volatile ht_slot *aHash;
  46608. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  46609. if( iHash==0 ){
  46610. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  46611. iZero = 0;
  46612. }else{
  46613. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  46614. }
  46615. *paPgno = &aPgno[-1];
  46616. *paHash = aHash;
  46617. *piZero = iZero;
  46618. }
  46619. return rc;
  46620. }
  46621. /*
  46622. ** Return the number of the wal-index page that contains the hash-table
  46623. ** and page-number array that contain entries corresponding to WAL frame
  46624. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  46625. ** are numbered starting from 0.
  46626. */
  46627. static int walFramePage(u32 iFrame){
  46628. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  46629. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  46630. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  46631. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  46632. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  46633. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  46634. );
  46635. return iHash;
  46636. }
  46637. /*
  46638. ** Return the page number associated with frame iFrame in this WAL.
  46639. */
  46640. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  46641. int iHash = walFramePage(iFrame);
  46642. if( iHash==0 ){
  46643. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  46644. }
  46645. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  46646. }
  46647. /*
  46648. ** Remove entries from the hash table that point to WAL slots greater
  46649. ** than pWal->hdr.mxFrame.
  46650. **
  46651. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  46652. ** to a rollback or savepoint.
  46653. **
  46654. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  46655. ** updated. Any later hash tables will be automatically cleared when
  46656. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  46657. ** actually needed.
  46658. */
  46659. static void walCleanupHash(Wal *pWal){
  46660. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  46661. volatile u32 *aPgno = 0; /* Page number array for hash table */
  46662. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  46663. int iLimit = 0; /* Zero values greater than this */
  46664. int nByte; /* Number of bytes to zero in aPgno[] */
  46665. int i; /* Used to iterate through aHash[] */
  46666. assert( pWal->writeLock );
  46667. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  46668. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  46669. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  46670. if( pWal->hdr.mxFrame==0 ) return;
  46671. /* Obtain pointers to the hash-table and page-number array containing
  46672. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  46673. ** that the page said hash-table and array reside on is already mapped.
  46674. */
  46675. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  46676. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  46677. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  46678. /* Zero all hash-table entries that correspond to frame numbers greater
  46679. ** than pWal->hdr.mxFrame.
  46680. */
  46681. iLimit = pWal->hdr.mxFrame - iZero;
  46682. assert( iLimit>0 );
  46683. for(i=0; i<HASHTABLE_NSLOT; i++){
  46684. if( aHash[i]>iLimit ){
  46685. aHash[i] = 0;
  46686. }
  46687. }
  46688. /* Zero the entries in the aPgno array that correspond to frames with
  46689. ** frame numbers greater than pWal->hdr.mxFrame.
  46690. */
  46691. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  46692. memset((void *)&aPgno[iLimit+1], 0, nByte);
  46693. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46694. /* Verify that the every entry in the mapping region is still reachable
  46695. ** via the hash table even after the cleanup.
  46696. */
  46697. if( iLimit ){
  46698. int i; /* Loop counter */
  46699. int iKey; /* Hash key */
  46700. for(i=1; i<=iLimit; i++){
  46701. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46702. if( aHash[iKey]==i ) break;
  46703. }
  46704. assert( aHash[iKey]==i );
  46705. }
  46706. }
  46707. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46708. }
  46709. /*
  46710. ** Set an entry in the wal-index that will map database page number
  46711. ** pPage into WAL frame iFrame.
  46712. */
  46713. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  46714. int rc; /* Return code */
  46715. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  46716. volatile u32 *aPgno = 0; /* Page number array */
  46717. volatile ht_slot *aHash = 0; /* Hash table */
  46718. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  46719. /* Assuming the wal-index file was successfully mapped, populate the
  46720. ** page number array and hash table entry.
  46721. */
  46722. if( rc==SQLITE_OK ){
  46723. int iKey; /* Hash table key */
  46724. int idx; /* Value to write to hash-table slot */
  46725. int nCollide; /* Number of hash collisions */
  46726. idx = iFrame - iZero;
  46727. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  46728. /* If this is the first entry to be added to this hash-table, zero the
  46729. ** entire hash table and aPgno[] array before proceding.
  46730. */
  46731. if( idx==1 ){
  46732. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  46733. memset((void*)&aPgno[1], 0, nByte);
  46734. }
  46735. /* If the entry in aPgno[] is already set, then the previous writer
  46736. ** must have exited unexpectedly in the middle of a transaction (after
  46737. ** writing one or more dirty pages to the WAL to free up memory).
  46738. ** Remove the remnants of that writers uncommitted transaction from
  46739. ** the hash-table before writing any new entries.
  46740. */
  46741. if( aPgno[idx] ){
  46742. walCleanupHash(pWal);
  46743. assert( !aPgno[idx] );
  46744. }
  46745. /* Write the aPgno[] array entry and the hash-table slot. */
  46746. nCollide = idx;
  46747. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  46748. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  46749. }
  46750. aPgno[idx] = iPage;
  46751. aHash[iKey] = (ht_slot)idx;
  46752. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46753. /* Verify that the number of entries in the hash table exactly equals
  46754. ** the number of entries in the mapping region.
  46755. */
  46756. {
  46757. int i; /* Loop counter */
  46758. int nEntry = 0; /* Number of entries in the hash table */
  46759. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  46760. assert( nEntry==idx );
  46761. }
  46762. /* Verify that the every entry in the mapping region is reachable
  46763. ** via the hash table. This turns out to be a really, really expensive
  46764. ** thing to check, so only do this occasionally - not on every
  46765. ** iteration.
  46766. */
  46767. if( (idx&0x3ff)==0 ){
  46768. int i; /* Loop counter */
  46769. for(i=1; i<=idx; i++){
  46770. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46771. if( aHash[iKey]==i ) break;
  46772. }
  46773. assert( aHash[iKey]==i );
  46774. }
  46775. }
  46776. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46777. }
  46778. return rc;
  46779. }
  46780. /*
  46781. ** Recover the wal-index by reading the write-ahead log file.
  46782. **
  46783. ** This routine first tries to establish an exclusive lock on the
  46784. ** wal-index to prevent other threads/processes from doing anything
  46785. ** with the WAL or wal-index while recovery is running. The
  46786. ** WAL_RECOVER_LOCK is also held so that other threads will know
  46787. ** that this thread is running recovery. If unable to establish
  46788. ** the necessary locks, this routine returns SQLITE_BUSY.
  46789. */
  46790. static int walIndexRecover(Wal *pWal){
  46791. int rc; /* Return Code */
  46792. i64 nSize; /* Size of log file */
  46793. u32 aFrameCksum[2] = {0, 0};
  46794. int iLock; /* Lock offset to lock for checkpoint */
  46795. int nLock; /* Number of locks to hold */
  46796. /* Obtain an exclusive lock on all byte in the locking range not already
  46797. ** locked by the caller. The caller is guaranteed to have locked the
  46798. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  46799. ** If successful, the same bytes that are locked here are unlocked before
  46800. ** this function returns.
  46801. */
  46802. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  46803. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  46804. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  46805. assert( pWal->writeLock );
  46806. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  46807. nLock = SQLITE_SHM_NLOCK - iLock;
  46808. rc = walLockExclusive(pWal, iLock, nLock);
  46809. if( rc ){
  46810. return rc;
  46811. }
  46812. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  46813. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  46814. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  46815. if( rc!=SQLITE_OK ){
  46816. goto recovery_error;
  46817. }
  46818. if( nSize>WAL_HDRSIZE ){
  46819. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  46820. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  46821. int szFrame; /* Number of bytes in buffer aFrame[] */
  46822. u8 *aData; /* Pointer to data part of aFrame buffer */
  46823. int iFrame; /* Index of last frame read */
  46824. i64 iOffset; /* Next offset to read from log file */
  46825. int szPage; /* Page size according to the log */
  46826. u32 magic; /* Magic value read from WAL header */
  46827. u32 version; /* Magic value read from WAL header */
  46828. int isValid; /* True if this frame is valid */
  46829. /* Read in the WAL header. */
  46830. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  46831. if( rc!=SQLITE_OK ){
  46832. goto recovery_error;
  46833. }
  46834. /* If the database page size is not a power of two, or is greater than
  46835. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  46836. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  46837. ** WAL file.
  46838. */
  46839. magic = sqlite3Get4byte(&aBuf[0]);
  46840. szPage = sqlite3Get4byte(&aBuf[8]);
  46841. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  46842. || szPage&(szPage-1)
  46843. || szPage>SQLITE_MAX_PAGE_SIZE
  46844. || szPage<512
  46845. ){
  46846. goto finished;
  46847. }
  46848. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  46849. pWal->szPage = szPage;
  46850. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  46851. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  46852. /* Verify that the WAL header checksum is correct */
  46853. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  46854. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  46855. );
  46856. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  46857. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  46858. ){
  46859. goto finished;
  46860. }
  46861. /* Verify that the version number on the WAL format is one that
  46862. ** are able to understand */
  46863. version = sqlite3Get4byte(&aBuf[4]);
  46864. if( version!=WAL_MAX_VERSION ){
  46865. rc = SQLITE_CANTOPEN_BKPT;
  46866. goto finished;
  46867. }
  46868. /* Malloc a buffer to read frames into. */
  46869. szFrame = szPage + WAL_FRAME_HDRSIZE;
  46870. aFrame = (u8 *)sqlite3_malloc(szFrame);
  46871. if( !aFrame ){
  46872. rc = SQLITE_NOMEM;
  46873. goto recovery_error;
  46874. }
  46875. aData = &aFrame[WAL_FRAME_HDRSIZE];
  46876. /* Read all frames from the log file. */
  46877. iFrame = 0;
  46878. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  46879. u32 pgno; /* Database page number for frame */
  46880. u32 nTruncate; /* dbsize field from frame header */
  46881. /* Read and decode the next log frame. */
  46882. iFrame++;
  46883. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  46884. if( rc!=SQLITE_OK ) break;
  46885. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  46886. if( !isValid ) break;
  46887. rc = walIndexAppend(pWal, iFrame, pgno);
  46888. if( rc!=SQLITE_OK ) break;
  46889. /* If nTruncate is non-zero, this is a commit record. */
  46890. if( nTruncate ){
  46891. pWal->hdr.mxFrame = iFrame;
  46892. pWal->hdr.nPage = nTruncate;
  46893. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  46894. testcase( szPage<=32768 );
  46895. testcase( szPage>=65536 );
  46896. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  46897. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  46898. }
  46899. }
  46900. sqlite3_free(aFrame);
  46901. }
  46902. finished:
  46903. if( rc==SQLITE_OK ){
  46904. volatile WalCkptInfo *pInfo;
  46905. int i;
  46906. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  46907. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  46908. walIndexWriteHdr(pWal);
  46909. /* Reset the checkpoint-header. This is safe because this thread is
  46910. ** currently holding locks that exclude all other readers, writers and
  46911. ** checkpointers.
  46912. */
  46913. pInfo = walCkptInfo(pWal);
  46914. pInfo->nBackfill = 0;
  46915. pInfo->aReadMark[0] = 0;
  46916. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  46917. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  46918. /* If more than one frame was recovered from the log file, report an
  46919. ** event via sqlite3_log(). This is to help with identifying performance
  46920. ** problems caused by applications routinely shutting down without
  46921. ** checkpointing the log file.
  46922. */
  46923. if( pWal->hdr.nPage ){
  46924. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  46925. "recovered %d frames from WAL file %s",
  46926. pWal->hdr.mxFrame, pWal->zWalName
  46927. );
  46928. }
  46929. }
  46930. recovery_error:
  46931. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  46932. walUnlockExclusive(pWal, iLock, nLock);
  46933. return rc;
  46934. }
  46935. /*
  46936. ** Close an open wal-index.
  46937. */
  46938. static void walIndexClose(Wal *pWal, int isDelete){
  46939. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46940. int i;
  46941. for(i=0; i<pWal->nWiData; i++){
  46942. sqlite3_free((void *)pWal->apWiData[i]);
  46943. pWal->apWiData[i] = 0;
  46944. }
  46945. }else{
  46946. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  46947. }
  46948. }
  46949. /*
  46950. ** Open a connection to the WAL file zWalName. The database file must
  46951. ** already be opened on connection pDbFd. The buffer that zWalName points
  46952. ** to must remain valid for the lifetime of the returned Wal* handle.
  46953. **
  46954. ** A SHARED lock should be held on the database file when this function
  46955. ** is called. The purpose of this SHARED lock is to prevent any other
  46956. ** client from unlinking the WAL or wal-index file. If another process
  46957. ** were to do this just after this client opened one of these files, the
  46958. ** system would be badly broken.
  46959. **
  46960. ** If the log file is successfully opened, SQLITE_OK is returned and
  46961. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  46962. ** an SQLite error code is returned and *ppWal is left unmodified.
  46963. */
  46964. SQLITE_PRIVATE int sqlite3WalOpen(
  46965. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  46966. sqlite3_file *pDbFd, /* The open database file */
  46967. const char *zWalName, /* Name of the WAL file */
  46968. int bNoShm, /* True to run in heap-memory mode */
  46969. i64 mxWalSize, /* Truncate WAL to this size on reset */
  46970. Wal **ppWal /* OUT: Allocated Wal handle */
  46971. ){
  46972. int rc; /* Return Code */
  46973. Wal *pRet; /* Object to allocate and return */
  46974. int flags; /* Flags passed to OsOpen() */
  46975. assert( zWalName && zWalName[0] );
  46976. assert( pDbFd );
  46977. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  46978. ** this source file. Verify that the #defines of the locking byte offsets
  46979. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  46980. */
  46981. #ifdef WIN_SHM_BASE
  46982. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46983. #endif
  46984. #ifdef UNIX_SHM_BASE
  46985. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46986. #endif
  46987. /* Allocate an instance of struct Wal to return. */
  46988. *ppWal = 0;
  46989. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  46990. if( !pRet ){
  46991. return SQLITE_NOMEM;
  46992. }
  46993. pRet->pVfs = pVfs;
  46994. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  46995. pRet->pDbFd = pDbFd;
  46996. pRet->readLock = -1;
  46997. pRet->mxWalSize = mxWalSize;
  46998. pRet->zWalName = zWalName;
  46999. pRet->syncHeader = 1;
  47000. pRet->padToSectorBoundary = 1;
  47001. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  47002. /* Open file handle on the write-ahead log file. */
  47003. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  47004. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  47005. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  47006. pRet->readOnly = WAL_RDONLY;
  47007. }
  47008. if( rc!=SQLITE_OK ){
  47009. walIndexClose(pRet, 0);
  47010. sqlite3OsClose(pRet->pWalFd);
  47011. sqlite3_free(pRet);
  47012. }else{
  47013. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  47014. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  47015. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  47016. pRet->padToSectorBoundary = 0;
  47017. }
  47018. *ppWal = pRet;
  47019. WALTRACE(("WAL%d: opened\n", pRet));
  47020. }
  47021. return rc;
  47022. }
  47023. /*
  47024. ** Change the size to which the WAL file is trucated on each reset.
  47025. */
  47026. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  47027. if( pWal ) pWal->mxWalSize = iLimit;
  47028. }
  47029. /*
  47030. ** Find the smallest page number out of all pages held in the WAL that
  47031. ** has not been returned by any prior invocation of this method on the
  47032. ** same WalIterator object. Write into *piFrame the frame index where
  47033. ** that page was last written into the WAL. Write into *piPage the page
  47034. ** number.
  47035. **
  47036. ** Return 0 on success. If there are no pages in the WAL with a page
  47037. ** number larger than *piPage, then return 1.
  47038. */
  47039. static int walIteratorNext(
  47040. WalIterator *p, /* Iterator */
  47041. u32 *piPage, /* OUT: The page number of the next page */
  47042. u32 *piFrame /* OUT: Wal frame index of next page */
  47043. ){
  47044. u32 iMin; /* Result pgno must be greater than iMin */
  47045. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  47046. int i; /* For looping through segments */
  47047. iMin = p->iPrior;
  47048. assert( iMin<0xffffffff );
  47049. for(i=p->nSegment-1; i>=0; i--){
  47050. struct WalSegment *pSegment = &p->aSegment[i];
  47051. while( pSegment->iNext<pSegment->nEntry ){
  47052. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  47053. if( iPg>iMin ){
  47054. if( iPg<iRet ){
  47055. iRet = iPg;
  47056. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  47057. }
  47058. break;
  47059. }
  47060. pSegment->iNext++;
  47061. }
  47062. }
  47063. *piPage = p->iPrior = iRet;
  47064. return (iRet==0xFFFFFFFF);
  47065. }
  47066. /*
  47067. ** This function merges two sorted lists into a single sorted list.
  47068. **
  47069. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  47070. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  47071. ** is guaranteed for all J<K:
  47072. **
  47073. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  47074. ** aContent[aRight[J]] < aContent[aRight[K]]
  47075. **
  47076. ** This routine overwrites aRight[] with a new (probably longer) sequence
  47077. ** of indices such that the aRight[] contains every index that appears in
  47078. ** either aLeft[] or the old aRight[] and such that the second condition
  47079. ** above is still met.
  47080. **
  47081. ** The aContent[aLeft[X]] values will be unique for all X. And the
  47082. ** aContent[aRight[X]] values will be unique too. But there might be
  47083. ** one or more combinations of X and Y such that
  47084. **
  47085. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  47086. **
  47087. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  47088. */
  47089. static void walMerge(
  47090. const u32 *aContent, /* Pages in wal - keys for the sort */
  47091. ht_slot *aLeft, /* IN: Left hand input list */
  47092. int nLeft, /* IN: Elements in array *paLeft */
  47093. ht_slot **paRight, /* IN/OUT: Right hand input list */
  47094. int *pnRight, /* IN/OUT: Elements in *paRight */
  47095. ht_slot *aTmp /* Temporary buffer */
  47096. ){
  47097. int iLeft = 0; /* Current index in aLeft */
  47098. int iRight = 0; /* Current index in aRight */
  47099. int iOut = 0; /* Current index in output buffer */
  47100. int nRight = *pnRight;
  47101. ht_slot *aRight = *paRight;
  47102. assert( nLeft>0 && nRight>0 );
  47103. while( iRight<nRight || iLeft<nLeft ){
  47104. ht_slot logpage;
  47105. Pgno dbpage;
  47106. if( (iLeft<nLeft)
  47107. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  47108. ){
  47109. logpage = aLeft[iLeft++];
  47110. }else{
  47111. logpage = aRight[iRight++];
  47112. }
  47113. dbpage = aContent[logpage];
  47114. aTmp[iOut++] = logpage;
  47115. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  47116. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  47117. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  47118. }
  47119. *paRight = aLeft;
  47120. *pnRight = iOut;
  47121. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  47122. }
  47123. /*
  47124. ** Sort the elements in list aList using aContent[] as the sort key.
  47125. ** Remove elements with duplicate keys, preferring to keep the
  47126. ** larger aList[] values.
  47127. **
  47128. ** The aList[] entries are indices into aContent[]. The values in
  47129. ** aList[] are to be sorted so that for all J<K:
  47130. **
  47131. ** aContent[aList[J]] < aContent[aList[K]]
  47132. **
  47133. ** For any X and Y such that
  47134. **
  47135. ** aContent[aList[X]] == aContent[aList[Y]]
  47136. **
  47137. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  47138. ** the smaller.
  47139. */
  47140. static void walMergesort(
  47141. const u32 *aContent, /* Pages in wal */
  47142. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  47143. ht_slot *aList, /* IN/OUT: List to sort */
  47144. int *pnList /* IN/OUT: Number of elements in aList[] */
  47145. ){
  47146. struct Sublist {
  47147. int nList; /* Number of elements in aList */
  47148. ht_slot *aList; /* Pointer to sub-list content */
  47149. };
  47150. const int nList = *pnList; /* Size of input list */
  47151. int nMerge = 0; /* Number of elements in list aMerge */
  47152. ht_slot *aMerge = 0; /* List to be merged */
  47153. int iList; /* Index into input list */
  47154. int iSub = 0; /* Index into aSub array */
  47155. struct Sublist aSub[13]; /* Array of sub-lists */
  47156. memset(aSub, 0, sizeof(aSub));
  47157. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  47158. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  47159. for(iList=0; iList<nList; iList++){
  47160. nMerge = 1;
  47161. aMerge = &aList[iList];
  47162. for(iSub=0; iList & (1<<iSub); iSub++){
  47163. struct Sublist *p = &aSub[iSub];
  47164. assert( p->aList && p->nList<=(1<<iSub) );
  47165. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  47166. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47167. }
  47168. aSub[iSub].aList = aMerge;
  47169. aSub[iSub].nList = nMerge;
  47170. }
  47171. for(iSub++; iSub<ArraySize(aSub); iSub++){
  47172. if( nList & (1<<iSub) ){
  47173. struct Sublist *p = &aSub[iSub];
  47174. assert( p->nList<=(1<<iSub) );
  47175. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  47176. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47177. }
  47178. }
  47179. assert( aMerge==aList );
  47180. *pnList = nMerge;
  47181. #ifdef SQLITE_DEBUG
  47182. {
  47183. int i;
  47184. for(i=1; i<*pnList; i++){
  47185. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  47186. }
  47187. }
  47188. #endif
  47189. }
  47190. /*
  47191. ** Free an iterator allocated by walIteratorInit().
  47192. */
  47193. static void walIteratorFree(WalIterator *p){
  47194. sqlite3ScratchFree(p);
  47195. }
  47196. /*
  47197. ** Construct a WalInterator object that can be used to loop over all
  47198. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  47199. ** lock.
  47200. **
  47201. ** On success, make *pp point to the newly allocated WalInterator object
  47202. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  47203. ** returns an error, the value of *pp is undefined.
  47204. **
  47205. ** The calling routine should invoke walIteratorFree() to destroy the
  47206. ** WalIterator object when it has finished with it.
  47207. */
  47208. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  47209. WalIterator *p; /* Return value */
  47210. int nSegment; /* Number of segments to merge */
  47211. u32 iLast; /* Last frame in log */
  47212. int nByte; /* Number of bytes to allocate */
  47213. int i; /* Iterator variable */
  47214. ht_slot *aTmp; /* Temp space used by merge-sort */
  47215. int rc = SQLITE_OK; /* Return Code */
  47216. /* This routine only runs while holding the checkpoint lock. And
  47217. ** it only runs if there is actually content in the log (mxFrame>0).
  47218. */
  47219. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  47220. iLast = pWal->hdr.mxFrame;
  47221. /* Allocate space for the WalIterator object. */
  47222. nSegment = walFramePage(iLast) + 1;
  47223. nByte = sizeof(WalIterator)
  47224. + (nSegment-1)*sizeof(struct WalSegment)
  47225. + iLast*sizeof(ht_slot);
  47226. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  47227. if( !p ){
  47228. return SQLITE_NOMEM;
  47229. }
  47230. memset(p, 0, nByte);
  47231. p->nSegment = nSegment;
  47232. /* Allocate temporary space used by the merge-sort routine. This block
  47233. ** of memory will be freed before this function returns.
  47234. */
  47235. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  47236. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  47237. );
  47238. if( !aTmp ){
  47239. rc = SQLITE_NOMEM;
  47240. }
  47241. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  47242. volatile ht_slot *aHash;
  47243. u32 iZero;
  47244. volatile u32 *aPgno;
  47245. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  47246. if( rc==SQLITE_OK ){
  47247. int j; /* Counter variable */
  47248. int nEntry; /* Number of entries in this segment */
  47249. ht_slot *aIndex; /* Sorted index for this segment */
  47250. aPgno++;
  47251. if( (i+1)==nSegment ){
  47252. nEntry = (int)(iLast - iZero);
  47253. }else{
  47254. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  47255. }
  47256. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  47257. iZero++;
  47258. for(j=0; j<nEntry; j++){
  47259. aIndex[j] = (ht_slot)j;
  47260. }
  47261. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  47262. p->aSegment[i].iZero = iZero;
  47263. p->aSegment[i].nEntry = nEntry;
  47264. p->aSegment[i].aIndex = aIndex;
  47265. p->aSegment[i].aPgno = (u32 *)aPgno;
  47266. }
  47267. }
  47268. sqlite3ScratchFree(aTmp);
  47269. if( rc!=SQLITE_OK ){
  47270. walIteratorFree(p);
  47271. }
  47272. *pp = p;
  47273. return rc;
  47274. }
  47275. /*
  47276. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  47277. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  47278. ** busy-handler function. Invoke it and retry the lock until either the
  47279. ** lock is successfully obtained or the busy-handler returns 0.
  47280. */
  47281. static int walBusyLock(
  47282. Wal *pWal, /* WAL connection */
  47283. int (*xBusy)(void*), /* Function to call when busy */
  47284. void *pBusyArg, /* Context argument for xBusyHandler */
  47285. int lockIdx, /* Offset of first byte to lock */
  47286. int n /* Number of bytes to lock */
  47287. ){
  47288. int rc;
  47289. do {
  47290. rc = walLockExclusive(pWal, lockIdx, n);
  47291. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  47292. return rc;
  47293. }
  47294. /*
  47295. ** The cache of the wal-index header must be valid to call this function.
  47296. ** Return the page-size in bytes used by the database.
  47297. */
  47298. static int walPagesize(Wal *pWal){
  47299. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47300. }
  47301. /*
  47302. ** Copy as much content as we can from the WAL back into the database file
  47303. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  47304. **
  47305. ** The amount of information copies from WAL to database might be limited
  47306. ** by active readers. This routine will never overwrite a database page
  47307. ** that a concurrent reader might be using.
  47308. **
  47309. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  47310. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  47311. ** checkpoints are always run by a background thread or background
  47312. ** process, foreground threads will never block on a lengthy fsync call.
  47313. **
  47314. ** Fsync is called on the WAL before writing content out of the WAL and
  47315. ** into the database. This ensures that if the new content is persistent
  47316. ** in the WAL and can be recovered following a power-loss or hard reset.
  47317. **
  47318. ** Fsync is also called on the database file if (and only if) the entire
  47319. ** WAL content is copied into the database file. This second fsync makes
  47320. ** it safe to delete the WAL since the new content will persist in the
  47321. ** database file.
  47322. **
  47323. ** This routine uses and updates the nBackfill field of the wal-index header.
  47324. ** This is the only routine tha will increase the value of nBackfill.
  47325. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  47326. ** its value.)
  47327. **
  47328. ** The caller must be holding sufficient locks to ensure that no other
  47329. ** checkpoint is running (in any other thread or process) at the same
  47330. ** time.
  47331. */
  47332. static int walCheckpoint(
  47333. Wal *pWal, /* Wal connection */
  47334. int eMode, /* One of PASSIVE, FULL or RESTART */
  47335. int (*xBusyCall)(void*), /* Function to call when busy */
  47336. void *pBusyArg, /* Context argument for xBusyHandler */
  47337. int sync_flags, /* Flags for OsSync() (or 0) */
  47338. u8 *zBuf /* Temporary buffer to use */
  47339. ){
  47340. int rc; /* Return code */
  47341. int szPage; /* Database page-size */
  47342. WalIterator *pIter = 0; /* Wal iterator context */
  47343. u32 iDbpage = 0; /* Next database page to write */
  47344. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  47345. u32 mxSafeFrame; /* Max frame that can be backfilled */
  47346. u32 mxPage; /* Max database page to write */
  47347. int i; /* Loop counter */
  47348. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  47349. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  47350. szPage = walPagesize(pWal);
  47351. testcase( szPage<=32768 );
  47352. testcase( szPage>=65536 );
  47353. pInfo = walCkptInfo(pWal);
  47354. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  47355. /* Allocate the iterator */
  47356. rc = walIteratorInit(pWal, &pIter);
  47357. if( rc!=SQLITE_OK ){
  47358. return rc;
  47359. }
  47360. assert( pIter );
  47361. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  47362. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  47363. ** safe to write into the database. Frames beyond mxSafeFrame might
  47364. ** overwrite database pages that are in use by active readers and thus
  47365. ** cannot be backfilled from the WAL.
  47366. */
  47367. mxSafeFrame = pWal->hdr.mxFrame;
  47368. mxPage = pWal->hdr.nPage;
  47369. for(i=1; i<WAL_NREADER; i++){
  47370. u32 y = pInfo->aReadMark[i];
  47371. if( mxSafeFrame>y ){
  47372. assert( y<=pWal->hdr.mxFrame );
  47373. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  47374. if( rc==SQLITE_OK ){
  47375. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  47376. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47377. }else if( rc==SQLITE_BUSY ){
  47378. mxSafeFrame = y;
  47379. xBusy = 0;
  47380. }else{
  47381. goto walcheckpoint_out;
  47382. }
  47383. }
  47384. }
  47385. if( pInfo->nBackfill<mxSafeFrame
  47386. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  47387. ){
  47388. i64 nSize; /* Current size of database file */
  47389. u32 nBackfill = pInfo->nBackfill;
  47390. /* Sync the WAL to disk */
  47391. if( sync_flags ){
  47392. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  47393. }
  47394. /* If the database may grow as a result of this checkpoint, hint
  47395. ** about the eventual size of the db file to the VFS layer.
  47396. */
  47397. if( rc==SQLITE_OK ){
  47398. i64 nReq = ((i64)mxPage * szPage);
  47399. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  47400. if( rc==SQLITE_OK && nSize<nReq ){
  47401. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  47402. }
  47403. }
  47404. /* Iterate through the contents of the WAL, copying data to the db file. */
  47405. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  47406. i64 iOffset;
  47407. assert( walFramePgno(pWal, iFrame)==iDbpage );
  47408. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  47409. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  47410. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  47411. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  47412. if( rc!=SQLITE_OK ) break;
  47413. iOffset = (iDbpage-1)*(i64)szPage;
  47414. testcase( IS_BIG_INT(iOffset) );
  47415. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  47416. if( rc!=SQLITE_OK ) break;
  47417. }
  47418. /* If work was actually accomplished... */
  47419. if( rc==SQLITE_OK ){
  47420. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  47421. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  47422. testcase( IS_BIG_INT(szDb) );
  47423. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  47424. if( rc==SQLITE_OK && sync_flags ){
  47425. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  47426. }
  47427. }
  47428. if( rc==SQLITE_OK ){
  47429. pInfo->nBackfill = mxSafeFrame;
  47430. }
  47431. }
  47432. /* Release the reader lock held while backfilling */
  47433. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  47434. }
  47435. if( rc==SQLITE_BUSY ){
  47436. /* Reset the return code so as not to report a checkpoint failure
  47437. ** just because there are active readers. */
  47438. rc = SQLITE_OK;
  47439. }
  47440. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  47441. ** file has been copied into the database file, then block until all
  47442. ** readers have finished using the wal file. This ensures that the next
  47443. ** process to write to the database restarts the wal file.
  47444. */
  47445. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  47446. assert( pWal->writeLock );
  47447. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  47448. rc = SQLITE_BUSY;
  47449. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  47450. assert( mxSafeFrame==pWal->hdr.mxFrame );
  47451. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  47452. if( rc==SQLITE_OK ){
  47453. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47454. }
  47455. }
  47456. }
  47457. walcheckpoint_out:
  47458. walIteratorFree(pIter);
  47459. return rc;
  47460. }
  47461. /*
  47462. ** If the WAL file is currently larger than nMax bytes in size, truncate
  47463. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  47464. */
  47465. static void walLimitSize(Wal *pWal, i64 nMax){
  47466. i64 sz;
  47467. int rx;
  47468. sqlite3BeginBenignMalloc();
  47469. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  47470. if( rx==SQLITE_OK && (sz > nMax ) ){
  47471. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  47472. }
  47473. sqlite3EndBenignMalloc();
  47474. if( rx ){
  47475. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  47476. }
  47477. }
  47478. /*
  47479. ** Close a connection to a log file.
  47480. */
  47481. SQLITE_PRIVATE int sqlite3WalClose(
  47482. Wal *pWal, /* Wal to close */
  47483. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  47484. int nBuf,
  47485. u8 *zBuf /* Buffer of at least nBuf bytes */
  47486. ){
  47487. int rc = SQLITE_OK;
  47488. if( pWal ){
  47489. int isDelete = 0; /* True to unlink wal and wal-index files */
  47490. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  47491. ** ordinary, rollback-mode locking methods, this guarantees that the
  47492. ** connection associated with this log file is the only connection to
  47493. ** the database. In this case checkpoint the database and unlink both
  47494. ** the wal and wal-index files.
  47495. **
  47496. ** The EXCLUSIVE lock is not released before returning.
  47497. */
  47498. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  47499. if( rc==SQLITE_OK ){
  47500. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  47501. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  47502. }
  47503. rc = sqlite3WalCheckpoint(
  47504. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  47505. );
  47506. if( rc==SQLITE_OK ){
  47507. int bPersist = -1;
  47508. sqlite3OsFileControlHint(
  47509. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  47510. );
  47511. if( bPersist!=1 ){
  47512. /* Try to delete the WAL file if the checkpoint completed and
  47513. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  47514. ** mode (!bPersist) */
  47515. isDelete = 1;
  47516. }else if( pWal->mxWalSize>=0 ){
  47517. /* Try to truncate the WAL file to zero bytes if the checkpoint
  47518. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  47519. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  47520. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  47521. ** to zero bytes as truncating to the journal_size_limit might
  47522. ** leave a corrupt WAL file on disk. */
  47523. walLimitSize(pWal, 0);
  47524. }
  47525. }
  47526. }
  47527. walIndexClose(pWal, isDelete);
  47528. sqlite3OsClose(pWal->pWalFd);
  47529. if( isDelete ){
  47530. sqlite3BeginBenignMalloc();
  47531. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  47532. sqlite3EndBenignMalloc();
  47533. }
  47534. WALTRACE(("WAL%p: closed\n", pWal));
  47535. sqlite3_free((void *)pWal->apWiData);
  47536. sqlite3_free(pWal);
  47537. }
  47538. return rc;
  47539. }
  47540. /*
  47541. ** Try to read the wal-index header. Return 0 on success and 1 if
  47542. ** there is a problem.
  47543. **
  47544. ** The wal-index is in shared memory. Another thread or process might
  47545. ** be writing the header at the same time this procedure is trying to
  47546. ** read it, which might result in inconsistency. A dirty read is detected
  47547. ** by verifying that both copies of the header are the same and also by
  47548. ** a checksum on the header.
  47549. **
  47550. ** If and only if the read is consistent and the header is different from
  47551. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  47552. ** and *pChanged is set to 1.
  47553. **
  47554. ** If the checksum cannot be verified return non-zero. If the header
  47555. ** is read successfully and the checksum verified, return zero.
  47556. */
  47557. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  47558. u32 aCksum[2]; /* Checksum on the header content */
  47559. WalIndexHdr h1, h2; /* Two copies of the header content */
  47560. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  47561. /* The first page of the wal-index must be mapped at this point. */
  47562. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  47563. /* Read the header. This might happen concurrently with a write to the
  47564. ** same area of shared memory on a different CPU in a SMP,
  47565. ** meaning it is possible that an inconsistent snapshot is read
  47566. ** from the file. If this happens, return non-zero.
  47567. **
  47568. ** There are two copies of the header at the beginning of the wal-index.
  47569. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  47570. ** Memory barriers are used to prevent the compiler or the hardware from
  47571. ** reordering the reads and writes.
  47572. */
  47573. aHdr = walIndexHdr(pWal);
  47574. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  47575. walShmBarrier(pWal);
  47576. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  47577. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  47578. return 1; /* Dirty read */
  47579. }
  47580. if( h1.isInit==0 ){
  47581. return 1; /* Malformed header - probably all zeros */
  47582. }
  47583. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  47584. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  47585. return 1; /* Checksum does not match */
  47586. }
  47587. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  47588. *pChanged = 1;
  47589. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  47590. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47591. testcase( pWal->szPage<=32768 );
  47592. testcase( pWal->szPage>=65536 );
  47593. }
  47594. /* The header was successfully read. Return zero. */
  47595. return 0;
  47596. }
  47597. /*
  47598. ** Read the wal-index header from the wal-index and into pWal->hdr.
  47599. ** If the wal-header appears to be corrupt, try to reconstruct the
  47600. ** wal-index from the WAL before returning.
  47601. **
  47602. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  47603. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  47604. ** to 0.
  47605. **
  47606. ** If the wal-index header is successfully read, return SQLITE_OK.
  47607. ** Otherwise an SQLite error code.
  47608. */
  47609. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  47610. int rc; /* Return code */
  47611. int badHdr; /* True if a header read failed */
  47612. volatile u32 *page0; /* Chunk of wal-index containing header */
  47613. /* Ensure that page 0 of the wal-index (the page that contains the
  47614. ** wal-index header) is mapped. Return early if an error occurs here.
  47615. */
  47616. assert( pChanged );
  47617. rc = walIndexPage(pWal, 0, &page0);
  47618. if( rc!=SQLITE_OK ){
  47619. return rc;
  47620. };
  47621. assert( page0 || pWal->writeLock==0 );
  47622. /* If the first page of the wal-index has been mapped, try to read the
  47623. ** wal-index header immediately, without holding any lock. This usually
  47624. ** works, but may fail if the wal-index header is corrupt or currently
  47625. ** being modified by another thread or process.
  47626. */
  47627. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  47628. /* If the first attempt failed, it might have been due to a race
  47629. ** with a writer. So get a WRITE lock and try again.
  47630. */
  47631. assert( badHdr==0 || pWal->writeLock==0 );
  47632. if( badHdr ){
  47633. if( pWal->readOnly & WAL_SHM_RDONLY ){
  47634. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  47635. walUnlockShared(pWal, WAL_WRITE_LOCK);
  47636. rc = SQLITE_READONLY_RECOVERY;
  47637. }
  47638. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  47639. pWal->writeLock = 1;
  47640. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  47641. badHdr = walIndexTryHdr(pWal, pChanged);
  47642. if( badHdr ){
  47643. /* If the wal-index header is still malformed even while holding
  47644. ** a WRITE lock, it can only mean that the header is corrupted and
  47645. ** needs to be reconstructed. So run recovery to do exactly that.
  47646. */
  47647. rc = walIndexRecover(pWal);
  47648. *pChanged = 1;
  47649. }
  47650. }
  47651. pWal->writeLock = 0;
  47652. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47653. }
  47654. }
  47655. /* If the header is read successfully, check the version number to make
  47656. ** sure the wal-index was not constructed with some future format that
  47657. ** this version of SQLite cannot understand.
  47658. */
  47659. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  47660. rc = SQLITE_CANTOPEN_BKPT;
  47661. }
  47662. return rc;
  47663. }
  47664. /*
  47665. ** This is the value that walTryBeginRead returns when it needs to
  47666. ** be retried.
  47667. */
  47668. #define WAL_RETRY (-1)
  47669. /*
  47670. ** Attempt to start a read transaction. This might fail due to a race or
  47671. ** other transient condition. When that happens, it returns WAL_RETRY to
  47672. ** indicate to the caller that it is safe to retry immediately.
  47673. **
  47674. ** On success return SQLITE_OK. On a permanent failure (such an
  47675. ** I/O error or an SQLITE_BUSY because another process is running
  47676. ** recovery) return a positive error code.
  47677. **
  47678. ** The useWal parameter is true to force the use of the WAL and disable
  47679. ** the case where the WAL is bypassed because it has been completely
  47680. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  47681. ** to make a copy of the wal-index header into pWal->hdr. If the
  47682. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  47683. ** to the caller that the local paget cache is obsolete and needs to be
  47684. ** flushed.) When useWal==1, the wal-index header is assumed to already
  47685. ** be loaded and the pChanged parameter is unused.
  47686. **
  47687. ** The caller must set the cnt parameter to the number of prior calls to
  47688. ** this routine during the current read attempt that returned WAL_RETRY.
  47689. ** This routine will start taking more aggressive measures to clear the
  47690. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  47691. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  47692. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  47693. ** and is not honoring the locking protocol. There is a vanishingly small
  47694. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  47695. ** bad luck when there is lots of contention for the wal-index, but that
  47696. ** possibility is so small that it can be safely neglected, we believe.
  47697. **
  47698. ** On success, this routine obtains a read lock on
  47699. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  47700. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  47701. ** that means the Wal does not hold any read lock. The reader must not
  47702. ** access any database page that is modified by a WAL frame up to and
  47703. ** including frame number aReadMark[pWal->readLock]. The reader will
  47704. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  47705. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  47706. ** completely and get all content directly from the database file.
  47707. ** If the useWal parameter is 1 then the WAL will never be ignored and
  47708. ** this routine will always set pWal->readLock>0 on success.
  47709. ** When the read transaction is completed, the caller must release the
  47710. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  47711. **
  47712. ** This routine uses the nBackfill and aReadMark[] fields of the header
  47713. ** to select a particular WAL_READ_LOCK() that strives to let the
  47714. ** checkpoint process do as much work as possible. This routine might
  47715. ** update values of the aReadMark[] array in the header, but if it does
  47716. ** so it takes care to hold an exclusive lock on the corresponding
  47717. ** WAL_READ_LOCK() while changing values.
  47718. */
  47719. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  47720. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  47721. u32 mxReadMark; /* Largest aReadMark[] value */
  47722. int mxI; /* Index of largest aReadMark[] value */
  47723. int i; /* Loop counter */
  47724. int rc = SQLITE_OK; /* Return code */
  47725. assert( pWal->readLock<0 ); /* Not currently locked */
  47726. /* Take steps to avoid spinning forever if there is a protocol error.
  47727. **
  47728. ** Circumstances that cause a RETRY should only last for the briefest
  47729. ** instances of time. No I/O or other system calls are done while the
  47730. ** locks are held, so the locks should not be held for very long. But
  47731. ** if we are unlucky, another process that is holding a lock might get
  47732. ** paged out or take a page-fault that is time-consuming to resolve,
  47733. ** during the few nanoseconds that it is holding the lock. In that case,
  47734. ** it might take longer than normal for the lock to free.
  47735. **
  47736. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  47737. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  47738. ** is more of a scheduler yield than an actual delay. But on the 10th
  47739. ** an subsequent retries, the delays start becoming longer and longer,
  47740. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  47741. ** The total delay time before giving up is less than 1 second.
  47742. */
  47743. if( cnt>5 ){
  47744. int nDelay = 1; /* Pause time in microseconds */
  47745. if( cnt>100 ){
  47746. VVA_ONLY( pWal->lockError = 1; )
  47747. return SQLITE_PROTOCOL;
  47748. }
  47749. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  47750. sqlite3OsSleep(pWal->pVfs, nDelay);
  47751. }
  47752. if( !useWal ){
  47753. rc = walIndexReadHdr(pWal, pChanged);
  47754. if( rc==SQLITE_BUSY ){
  47755. /* If there is not a recovery running in another thread or process
  47756. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  47757. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  47758. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  47759. ** would be technically correct. But the race is benign since with
  47760. ** WAL_RETRY this routine will be called again and will probably be
  47761. ** right on the second iteration.
  47762. */
  47763. if( pWal->apWiData[0]==0 ){
  47764. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  47765. ** We assume this is a transient condition, so return WAL_RETRY. The
  47766. ** xShmMap() implementation used by the default unix and win32 VFS
  47767. ** modules may return SQLITE_BUSY due to a race condition in the
  47768. ** code that determines whether or not the shared-memory region
  47769. ** must be zeroed before the requested page is returned.
  47770. */
  47771. rc = WAL_RETRY;
  47772. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  47773. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  47774. rc = WAL_RETRY;
  47775. }else if( rc==SQLITE_BUSY ){
  47776. rc = SQLITE_BUSY_RECOVERY;
  47777. }
  47778. }
  47779. if( rc!=SQLITE_OK ){
  47780. return rc;
  47781. }
  47782. }
  47783. pInfo = walCkptInfo(pWal);
  47784. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  47785. /* The WAL has been completely backfilled (or it is empty).
  47786. ** and can be safely ignored.
  47787. */
  47788. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  47789. walShmBarrier(pWal);
  47790. if( rc==SQLITE_OK ){
  47791. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  47792. /* It is not safe to allow the reader to continue here if frames
  47793. ** may have been appended to the log before READ_LOCK(0) was obtained.
  47794. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  47795. ** which implies that the database file contains a trustworthy
  47796. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  47797. ** happening, this is usually correct.
  47798. **
  47799. ** However, if frames have been appended to the log (or if the log
  47800. ** is wrapped and written for that matter) before the READ_LOCK(0)
  47801. ** is obtained, that is not necessarily true. A checkpointer may
  47802. ** have started to backfill the appended frames but crashed before
  47803. ** it finished. Leaving a corrupt image in the database file.
  47804. */
  47805. walUnlockShared(pWal, WAL_READ_LOCK(0));
  47806. return WAL_RETRY;
  47807. }
  47808. pWal->readLock = 0;
  47809. return SQLITE_OK;
  47810. }else if( rc!=SQLITE_BUSY ){
  47811. return rc;
  47812. }
  47813. }
  47814. /* If we get this far, it means that the reader will want to use
  47815. ** the WAL to get at content from recent commits. The job now is
  47816. ** to select one of the aReadMark[] entries that is closest to
  47817. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  47818. */
  47819. mxReadMark = 0;
  47820. mxI = 0;
  47821. for(i=1; i<WAL_NREADER; i++){
  47822. u32 thisMark = pInfo->aReadMark[i];
  47823. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  47824. assert( thisMark!=READMARK_NOT_USED );
  47825. mxReadMark = thisMark;
  47826. mxI = i;
  47827. }
  47828. }
  47829. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  47830. {
  47831. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  47832. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  47833. ){
  47834. for(i=1; i<WAL_NREADER; i++){
  47835. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47836. if( rc==SQLITE_OK ){
  47837. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  47838. mxI = i;
  47839. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47840. break;
  47841. }else if( rc!=SQLITE_BUSY ){
  47842. return rc;
  47843. }
  47844. }
  47845. }
  47846. if( mxI==0 ){
  47847. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  47848. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  47849. }
  47850. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  47851. if( rc ){
  47852. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  47853. }
  47854. /* Now that the read-lock has been obtained, check that neither the
  47855. ** value in the aReadMark[] array or the contents of the wal-index
  47856. ** header have changed.
  47857. **
  47858. ** It is necessary to check that the wal-index header did not change
  47859. ** between the time it was read and when the shared-lock was obtained
  47860. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  47861. ** that the log file may have been wrapped by a writer, or that frames
  47862. ** that occur later in the log than pWal->hdr.mxFrame may have been
  47863. ** copied into the database by a checkpointer. If either of these things
  47864. ** happened, then reading the database with the current value of
  47865. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  47866. ** instead.
  47867. **
  47868. ** This does not guarantee that the copy of the wal-index header is up to
  47869. ** date before proceeding. That would not be possible without somehow
  47870. ** blocking writers. It only guarantees that a dangerous checkpoint or
  47871. ** log-wrap (either of which would require an exclusive lock on
  47872. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  47873. */
  47874. walShmBarrier(pWal);
  47875. if( pInfo->aReadMark[mxI]!=mxReadMark
  47876. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  47877. ){
  47878. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  47879. return WAL_RETRY;
  47880. }else{
  47881. assert( mxReadMark<=pWal->hdr.mxFrame );
  47882. pWal->readLock = (i16)mxI;
  47883. }
  47884. }
  47885. return rc;
  47886. }
  47887. /*
  47888. ** Begin a read transaction on the database.
  47889. **
  47890. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  47891. ** it takes a snapshot of the state of the WAL and wal-index for the current
  47892. ** instant in time. The current thread will continue to use this snapshot.
  47893. ** Other threads might append new content to the WAL and wal-index but
  47894. ** that extra content is ignored by the current thread.
  47895. **
  47896. ** If the database contents have changes since the previous read
  47897. ** transaction, then *pChanged is set to 1 before returning. The
  47898. ** Pager layer will use this to know that is cache is stale and
  47899. ** needs to be flushed.
  47900. */
  47901. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  47902. int rc; /* Return code */
  47903. int cnt = 0; /* Number of TryBeginRead attempts */
  47904. do{
  47905. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  47906. }while( rc==WAL_RETRY );
  47907. testcase( (rc&0xff)==SQLITE_BUSY );
  47908. testcase( (rc&0xff)==SQLITE_IOERR );
  47909. testcase( rc==SQLITE_PROTOCOL );
  47910. testcase( rc==SQLITE_OK );
  47911. return rc;
  47912. }
  47913. /*
  47914. ** Finish with a read transaction. All this does is release the
  47915. ** read-lock.
  47916. */
  47917. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  47918. sqlite3WalEndWriteTransaction(pWal);
  47919. if( pWal->readLock>=0 ){
  47920. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47921. pWal->readLock = -1;
  47922. }
  47923. }
  47924. /*
  47925. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  47926. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  47927. ** to zero.
  47928. **
  47929. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  47930. ** error does occur, the final value of *piRead is undefined.
  47931. */
  47932. SQLITE_PRIVATE int sqlite3WalFindFrame(
  47933. Wal *pWal, /* WAL handle */
  47934. Pgno pgno, /* Database page number to read data for */
  47935. u32 *piRead /* OUT: Frame number (or zero) */
  47936. ){
  47937. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  47938. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  47939. int iHash; /* Used to loop through N hash tables */
  47940. /* This routine is only be called from within a read transaction. */
  47941. assert( pWal->readLock>=0 || pWal->lockError );
  47942. /* If the "last page" field of the wal-index header snapshot is 0, then
  47943. ** no data will be read from the wal under any circumstances. Return early
  47944. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  47945. ** then the WAL is ignored by the reader so return early, as if the
  47946. ** WAL were empty.
  47947. */
  47948. if( iLast==0 || pWal->readLock==0 ){
  47949. *piRead = 0;
  47950. return SQLITE_OK;
  47951. }
  47952. /* Search the hash table or tables for an entry matching page number
  47953. ** pgno. Each iteration of the following for() loop searches one
  47954. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  47955. **
  47956. ** This code might run concurrently to the code in walIndexAppend()
  47957. ** that adds entries to the wal-index (and possibly to this hash
  47958. ** table). This means the value just read from the hash
  47959. ** slot (aHash[iKey]) may have been added before or after the
  47960. ** current read transaction was opened. Values added after the
  47961. ** read transaction was opened may have been written incorrectly -
  47962. ** i.e. these slots may contain garbage data. However, we assume
  47963. ** that any slots written before the current read transaction was
  47964. ** opened remain unmodified.
  47965. **
  47966. ** For the reasons above, the if(...) condition featured in the inner
  47967. ** loop of the following block is more stringent that would be required
  47968. ** if we had exclusive access to the hash-table:
  47969. **
  47970. ** (aPgno[iFrame]==pgno):
  47971. ** This condition filters out normal hash-table collisions.
  47972. **
  47973. ** (iFrame<=iLast):
  47974. ** This condition filters out entries that were added to the hash
  47975. ** table after the current read-transaction had started.
  47976. */
  47977. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  47978. volatile ht_slot *aHash; /* Pointer to hash table */
  47979. volatile u32 *aPgno; /* Pointer to array of page numbers */
  47980. u32 iZero; /* Frame number corresponding to aPgno[0] */
  47981. int iKey; /* Hash slot index */
  47982. int nCollide; /* Number of hash collisions remaining */
  47983. int rc; /* Error code */
  47984. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  47985. if( rc!=SQLITE_OK ){
  47986. return rc;
  47987. }
  47988. nCollide = HASHTABLE_NSLOT;
  47989. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  47990. u32 iFrame = aHash[iKey] + iZero;
  47991. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  47992. /* assert( iFrame>iRead ); -- not true if there is corruption */
  47993. iRead = iFrame;
  47994. }
  47995. if( (nCollide--)==0 ){
  47996. return SQLITE_CORRUPT_BKPT;
  47997. }
  47998. }
  47999. }
  48000. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48001. /* If expensive assert() statements are available, do a linear search
  48002. ** of the wal-index file content. Make sure the results agree with the
  48003. ** result obtained using the hash indexes above. */
  48004. {
  48005. u32 iRead2 = 0;
  48006. u32 iTest;
  48007. for(iTest=iLast; iTest>0; iTest--){
  48008. if( walFramePgno(pWal, iTest)==pgno ){
  48009. iRead2 = iTest;
  48010. break;
  48011. }
  48012. }
  48013. assert( iRead==iRead2 );
  48014. }
  48015. #endif
  48016. *piRead = iRead;
  48017. return SQLITE_OK;
  48018. }
  48019. /*
  48020. ** Read the contents of frame iRead from the wal file into buffer pOut
  48021. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  48022. ** error code otherwise.
  48023. */
  48024. SQLITE_PRIVATE int sqlite3WalReadFrame(
  48025. Wal *pWal, /* WAL handle */
  48026. u32 iRead, /* Frame to read */
  48027. int nOut, /* Size of buffer pOut in bytes */
  48028. u8 *pOut /* Buffer to write page data to */
  48029. ){
  48030. int sz;
  48031. i64 iOffset;
  48032. sz = pWal->hdr.szPage;
  48033. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  48034. testcase( sz<=32768 );
  48035. testcase( sz>=65536 );
  48036. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  48037. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  48038. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  48039. }
  48040. /*
  48041. ** Return the size of the database in pages (or zero, if unknown).
  48042. */
  48043. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  48044. if( pWal && ALWAYS(pWal->readLock>=0) ){
  48045. return pWal->hdr.nPage;
  48046. }
  48047. return 0;
  48048. }
  48049. /*
  48050. ** This function starts a write transaction on the WAL.
  48051. **
  48052. ** A read transaction must have already been started by a prior call
  48053. ** to sqlite3WalBeginReadTransaction().
  48054. **
  48055. ** If another thread or process has written into the database since
  48056. ** the read transaction was started, then it is not possible for this
  48057. ** thread to write as doing so would cause a fork. So this routine
  48058. ** returns SQLITE_BUSY in that case and no write transaction is started.
  48059. **
  48060. ** There can only be a single writer active at a time.
  48061. */
  48062. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  48063. int rc;
  48064. /* Cannot start a write transaction without first holding a read
  48065. ** transaction. */
  48066. assert( pWal->readLock>=0 );
  48067. if( pWal->readOnly ){
  48068. return SQLITE_READONLY;
  48069. }
  48070. /* Only one writer allowed at a time. Get the write lock. Return
  48071. ** SQLITE_BUSY if unable.
  48072. */
  48073. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48074. if( rc ){
  48075. return rc;
  48076. }
  48077. pWal->writeLock = 1;
  48078. /* If another connection has written to the database file since the
  48079. ** time the read transaction on this connection was started, then
  48080. ** the write is disallowed.
  48081. */
  48082. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  48083. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48084. pWal->writeLock = 0;
  48085. rc = SQLITE_BUSY_SNAPSHOT;
  48086. }
  48087. return rc;
  48088. }
  48089. /*
  48090. ** End a write transaction. The commit has already been done. This
  48091. ** routine merely releases the lock.
  48092. */
  48093. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  48094. if( pWal->writeLock ){
  48095. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48096. pWal->writeLock = 0;
  48097. pWal->truncateOnCommit = 0;
  48098. }
  48099. return SQLITE_OK;
  48100. }
  48101. /*
  48102. ** If any data has been written (but not committed) to the log file, this
  48103. ** function moves the write-pointer back to the start of the transaction.
  48104. **
  48105. ** Additionally, the callback function is invoked for each frame written
  48106. ** to the WAL since the start of the transaction. If the callback returns
  48107. ** other than SQLITE_OK, it is not invoked again and the error code is
  48108. ** returned to the caller.
  48109. **
  48110. ** Otherwise, if the callback function does not return an error, this
  48111. ** function returns SQLITE_OK.
  48112. */
  48113. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  48114. int rc = SQLITE_OK;
  48115. if( ALWAYS(pWal->writeLock) ){
  48116. Pgno iMax = pWal->hdr.mxFrame;
  48117. Pgno iFrame;
  48118. /* Restore the clients cache of the wal-index header to the state it
  48119. ** was in before the client began writing to the database.
  48120. */
  48121. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  48122. for(iFrame=pWal->hdr.mxFrame+1;
  48123. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  48124. iFrame++
  48125. ){
  48126. /* This call cannot fail. Unless the page for which the page number
  48127. ** is passed as the second argument is (a) in the cache and
  48128. ** (b) has an outstanding reference, then xUndo is either a no-op
  48129. ** (if (a) is false) or simply expels the page from the cache (if (b)
  48130. ** is false).
  48131. **
  48132. ** If the upper layer is doing a rollback, it is guaranteed that there
  48133. ** are no outstanding references to any page other than page 1. And
  48134. ** page 1 is never written to the log until the transaction is
  48135. ** committed. As a result, the call to xUndo may not fail.
  48136. */
  48137. assert( walFramePgno(pWal, iFrame)!=1 );
  48138. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  48139. }
  48140. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  48141. }
  48142. assert( rc==SQLITE_OK );
  48143. return rc;
  48144. }
  48145. /*
  48146. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  48147. ** values. This function populates the array with values required to
  48148. ** "rollback" the write position of the WAL handle back to the current
  48149. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  48150. */
  48151. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  48152. assert( pWal->writeLock );
  48153. aWalData[0] = pWal->hdr.mxFrame;
  48154. aWalData[1] = pWal->hdr.aFrameCksum[0];
  48155. aWalData[2] = pWal->hdr.aFrameCksum[1];
  48156. aWalData[3] = pWal->nCkpt;
  48157. }
  48158. /*
  48159. ** Move the write position of the WAL back to the point identified by
  48160. ** the values in the aWalData[] array. aWalData must point to an array
  48161. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  48162. ** by a call to WalSavepoint().
  48163. */
  48164. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  48165. int rc = SQLITE_OK;
  48166. assert( pWal->writeLock );
  48167. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  48168. if( aWalData[3]!=pWal->nCkpt ){
  48169. /* This savepoint was opened immediately after the write-transaction
  48170. ** was started. Right after that, the writer decided to wrap around
  48171. ** to the start of the log. Update the savepoint values to match.
  48172. */
  48173. aWalData[0] = 0;
  48174. aWalData[3] = pWal->nCkpt;
  48175. }
  48176. if( aWalData[0]<pWal->hdr.mxFrame ){
  48177. pWal->hdr.mxFrame = aWalData[0];
  48178. pWal->hdr.aFrameCksum[0] = aWalData[1];
  48179. pWal->hdr.aFrameCksum[1] = aWalData[2];
  48180. walCleanupHash(pWal);
  48181. }
  48182. return rc;
  48183. }
  48184. /*
  48185. ** This function is called just before writing a set of frames to the log
  48186. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  48187. ** to the current log file, it is possible to overwrite the start of the
  48188. ** existing log file with the new frames (i.e. "reset" the log). If so,
  48189. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  48190. ** unchanged.
  48191. **
  48192. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  48193. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  48194. ** if an error occurs.
  48195. */
  48196. static int walRestartLog(Wal *pWal){
  48197. int rc = SQLITE_OK;
  48198. int cnt;
  48199. if( pWal->readLock==0 ){
  48200. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  48201. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48202. if( pInfo->nBackfill>0 ){
  48203. u32 salt1;
  48204. sqlite3_randomness(4, &salt1);
  48205. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48206. if( rc==SQLITE_OK ){
  48207. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  48208. ** readers are currently using the WAL), then the transactions
  48209. ** frames will overwrite the start of the existing log. Update the
  48210. ** wal-index header to reflect this.
  48211. **
  48212. ** In theory it would be Ok to update the cache of the header only
  48213. ** at this point. But updating the actual wal-index header is also
  48214. ** safe and means there is no special case for sqlite3WalUndo()
  48215. ** to handle if this transaction is rolled back.
  48216. */
  48217. int i; /* Loop counter */
  48218. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  48219. pWal->nCkpt++;
  48220. pWal->hdr.mxFrame = 0;
  48221. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  48222. aSalt[1] = salt1;
  48223. walIndexWriteHdr(pWal);
  48224. pInfo->nBackfill = 0;
  48225. pInfo->aReadMark[1] = 0;
  48226. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  48227. assert( pInfo->aReadMark[0]==0 );
  48228. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48229. }else if( rc!=SQLITE_BUSY ){
  48230. return rc;
  48231. }
  48232. }
  48233. walUnlockShared(pWal, WAL_READ_LOCK(0));
  48234. pWal->readLock = -1;
  48235. cnt = 0;
  48236. do{
  48237. int notUsed;
  48238. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  48239. }while( rc==WAL_RETRY );
  48240. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  48241. testcase( (rc&0xff)==SQLITE_IOERR );
  48242. testcase( rc==SQLITE_PROTOCOL );
  48243. testcase( rc==SQLITE_OK );
  48244. }
  48245. return rc;
  48246. }
  48247. /*
  48248. ** Information about the current state of the WAL file and where
  48249. ** the next fsync should occur - passed from sqlite3WalFrames() into
  48250. ** walWriteToLog().
  48251. */
  48252. typedef struct WalWriter {
  48253. Wal *pWal; /* The complete WAL information */
  48254. sqlite3_file *pFd; /* The WAL file to which we write */
  48255. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  48256. int syncFlags; /* Flags for the fsync */
  48257. int szPage; /* Size of one page */
  48258. } WalWriter;
  48259. /*
  48260. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  48261. ** Do a sync when crossing the p->iSyncPoint boundary.
  48262. **
  48263. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  48264. ** first write the part before iSyncPoint, then sync, then write the
  48265. ** rest.
  48266. */
  48267. static int walWriteToLog(
  48268. WalWriter *p, /* WAL to write to */
  48269. void *pContent, /* Content to be written */
  48270. int iAmt, /* Number of bytes to write */
  48271. sqlite3_int64 iOffset /* Start writing at this offset */
  48272. ){
  48273. int rc;
  48274. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  48275. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  48276. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  48277. if( rc ) return rc;
  48278. iOffset += iFirstAmt;
  48279. iAmt -= iFirstAmt;
  48280. pContent = (void*)(iFirstAmt + (char*)pContent);
  48281. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  48282. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  48283. if( iAmt==0 || rc ) return rc;
  48284. }
  48285. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  48286. return rc;
  48287. }
  48288. /*
  48289. ** Write out a single frame of the WAL
  48290. */
  48291. static int walWriteOneFrame(
  48292. WalWriter *p, /* Where to write the frame */
  48293. PgHdr *pPage, /* The page of the frame to be written */
  48294. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  48295. sqlite3_int64 iOffset /* Byte offset at which to write */
  48296. ){
  48297. int rc; /* Result code from subfunctions */
  48298. void *pData; /* Data actually written */
  48299. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  48300. #if defined(SQLITE_HAS_CODEC)
  48301. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  48302. #else
  48303. pData = pPage->pData;
  48304. #endif
  48305. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  48306. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  48307. if( rc ) return rc;
  48308. /* Write the page data */
  48309. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  48310. return rc;
  48311. }
  48312. /*
  48313. ** Write a set of frames to the log. The caller must hold the write-lock
  48314. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  48315. */
  48316. SQLITE_PRIVATE int sqlite3WalFrames(
  48317. Wal *pWal, /* Wal handle to write to */
  48318. int szPage, /* Database page-size in bytes */
  48319. PgHdr *pList, /* List of dirty pages to write */
  48320. Pgno nTruncate, /* Database size after this commit */
  48321. int isCommit, /* True if this is a commit */
  48322. int sync_flags /* Flags to pass to OsSync() (or 0) */
  48323. ){
  48324. int rc; /* Used to catch return codes */
  48325. u32 iFrame; /* Next frame address */
  48326. PgHdr *p; /* Iterator to run through pList with. */
  48327. PgHdr *pLast = 0; /* Last frame in list */
  48328. int nExtra = 0; /* Number of extra copies of last page */
  48329. int szFrame; /* The size of a single frame */
  48330. i64 iOffset; /* Next byte to write in WAL file */
  48331. WalWriter w; /* The writer */
  48332. assert( pList );
  48333. assert( pWal->writeLock );
  48334. /* If this frame set completes a transaction, then nTruncate>0. If
  48335. ** nTruncate==0 then this frame set does not complete the transaction. */
  48336. assert( (isCommit!=0)==(nTruncate!=0) );
  48337. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48338. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  48339. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  48340. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  48341. }
  48342. #endif
  48343. /* See if it is possible to write these frames into the start of the
  48344. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  48345. */
  48346. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  48347. return rc;
  48348. }
  48349. /* If this is the first frame written into the log, write the WAL
  48350. ** header to the start of the WAL file. See comments at the top of
  48351. ** this source file for a description of the WAL header format.
  48352. */
  48353. iFrame = pWal->hdr.mxFrame;
  48354. if( iFrame==0 ){
  48355. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  48356. u32 aCksum[2]; /* Checksum for wal-header */
  48357. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  48358. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  48359. sqlite3Put4byte(&aWalHdr[8], szPage);
  48360. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  48361. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  48362. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  48363. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  48364. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  48365. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  48366. pWal->szPage = szPage;
  48367. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  48368. pWal->hdr.aFrameCksum[0] = aCksum[0];
  48369. pWal->hdr.aFrameCksum[1] = aCksum[1];
  48370. pWal->truncateOnCommit = 1;
  48371. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  48372. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  48373. if( rc!=SQLITE_OK ){
  48374. return rc;
  48375. }
  48376. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  48377. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  48378. ** an out-of-order write following a WAL restart could result in
  48379. ** database corruption. See the ticket:
  48380. **
  48381. ** http://localhost:591/sqlite/info/ff5be73dee
  48382. */
  48383. if( pWal->syncHeader && sync_flags ){
  48384. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  48385. if( rc ) return rc;
  48386. }
  48387. }
  48388. assert( (int)pWal->szPage==szPage );
  48389. /* Setup information needed to write frames into the WAL */
  48390. w.pWal = pWal;
  48391. w.pFd = pWal->pWalFd;
  48392. w.iSyncPoint = 0;
  48393. w.syncFlags = sync_flags;
  48394. w.szPage = szPage;
  48395. iOffset = walFrameOffset(iFrame+1, szPage);
  48396. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48397. /* Write all frames into the log file exactly once */
  48398. for(p=pList; p; p=p->pDirty){
  48399. int nDbSize; /* 0 normally. Positive == commit flag */
  48400. iFrame++;
  48401. assert( iOffset==walFrameOffset(iFrame, szPage) );
  48402. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  48403. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  48404. if( rc ) return rc;
  48405. pLast = p;
  48406. iOffset += szFrame;
  48407. }
  48408. /* If this is the end of a transaction, then we might need to pad
  48409. ** the transaction and/or sync the WAL file.
  48410. **
  48411. ** Padding and syncing only occur if this set of frames complete a
  48412. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  48413. ** or synchonous==OFF, then no padding or syncing are needed.
  48414. **
  48415. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  48416. ** needed and only the sync is done. If padding is needed, then the
  48417. ** final frame is repeated (with its commit mark) until the next sector
  48418. ** boundary is crossed. Only the part of the WAL prior to the last
  48419. ** sector boundary is synced; the part of the last frame that extends
  48420. ** past the sector boundary is written after the sync.
  48421. */
  48422. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  48423. if( pWal->padToSectorBoundary ){
  48424. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  48425. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  48426. while( iOffset<w.iSyncPoint ){
  48427. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  48428. if( rc ) return rc;
  48429. iOffset += szFrame;
  48430. nExtra++;
  48431. }
  48432. }else{
  48433. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  48434. }
  48435. }
  48436. /* If this frame set completes the first transaction in the WAL and
  48437. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  48438. ** journal size limit, if possible.
  48439. */
  48440. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  48441. i64 sz = pWal->mxWalSize;
  48442. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  48443. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  48444. }
  48445. walLimitSize(pWal, sz);
  48446. pWal->truncateOnCommit = 0;
  48447. }
  48448. /* Append data to the wal-index. It is not necessary to lock the
  48449. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  48450. ** guarantees that there are no other writers, and no data that may
  48451. ** be in use by existing readers is being overwritten.
  48452. */
  48453. iFrame = pWal->hdr.mxFrame;
  48454. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  48455. iFrame++;
  48456. rc = walIndexAppend(pWal, iFrame, p->pgno);
  48457. }
  48458. while( rc==SQLITE_OK && nExtra>0 ){
  48459. iFrame++;
  48460. nExtra--;
  48461. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  48462. }
  48463. if( rc==SQLITE_OK ){
  48464. /* Update the private copy of the header. */
  48465. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  48466. testcase( szPage<=32768 );
  48467. testcase( szPage>=65536 );
  48468. pWal->hdr.mxFrame = iFrame;
  48469. if( isCommit ){
  48470. pWal->hdr.iChange++;
  48471. pWal->hdr.nPage = nTruncate;
  48472. }
  48473. /* If this is a commit, update the wal-index header too. */
  48474. if( isCommit ){
  48475. walIndexWriteHdr(pWal);
  48476. pWal->iCallback = iFrame;
  48477. }
  48478. }
  48479. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  48480. return rc;
  48481. }
  48482. /*
  48483. ** This routine is called to implement sqlite3_wal_checkpoint() and
  48484. ** related interfaces.
  48485. **
  48486. ** Obtain a CHECKPOINT lock and then backfill as much information as
  48487. ** we can from WAL into the database.
  48488. **
  48489. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  48490. ** callback. In this case this function runs a blocking checkpoint.
  48491. */
  48492. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  48493. Wal *pWal, /* Wal connection */
  48494. int eMode, /* PASSIVE, FULL or RESTART */
  48495. int (*xBusy)(void*), /* Function to call when busy */
  48496. void *pBusyArg, /* Context argument for xBusyHandler */
  48497. int sync_flags, /* Flags to sync db file with (or 0) */
  48498. int nBuf, /* Size of temporary buffer */
  48499. u8 *zBuf, /* Temporary buffer to use */
  48500. int *pnLog, /* OUT: Number of frames in WAL */
  48501. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  48502. ){
  48503. int rc; /* Return code */
  48504. int isChanged = 0; /* True if a new wal-index header is loaded */
  48505. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  48506. assert( pWal->ckptLock==0 );
  48507. assert( pWal->writeLock==0 );
  48508. if( pWal->readOnly ) return SQLITE_READONLY;
  48509. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  48510. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  48511. if( rc ){
  48512. /* Usually this is SQLITE_BUSY meaning that another thread or process
  48513. ** is already running a checkpoint, or maybe a recovery. But it might
  48514. ** also be SQLITE_IOERR. */
  48515. return rc;
  48516. }
  48517. pWal->ckptLock = 1;
  48518. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  48519. ** to prevent any writers from running while the checkpoint is underway.
  48520. ** This has to be done before the call to walIndexReadHdr() below.
  48521. **
  48522. ** If the writer lock cannot be obtained, then a passive checkpoint is
  48523. ** run instead. Since the checkpointer is not holding the writer lock,
  48524. ** there is no point in blocking waiting for any readers. Assuming no
  48525. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  48526. */
  48527. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  48528. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  48529. if( rc==SQLITE_OK ){
  48530. pWal->writeLock = 1;
  48531. }else if( rc==SQLITE_BUSY ){
  48532. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  48533. rc = SQLITE_OK;
  48534. }
  48535. }
  48536. /* Read the wal-index header. */
  48537. if( rc==SQLITE_OK ){
  48538. rc = walIndexReadHdr(pWal, &isChanged);
  48539. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  48540. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  48541. }
  48542. }
  48543. /* Copy data from the log to the database file. */
  48544. if( rc==SQLITE_OK ){
  48545. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  48546. rc = SQLITE_CORRUPT_BKPT;
  48547. }else{
  48548. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  48549. }
  48550. /* If no error occurred, set the output variables. */
  48551. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  48552. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  48553. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  48554. }
  48555. }
  48556. if( isChanged ){
  48557. /* If a new wal-index header was loaded before the checkpoint was
  48558. ** performed, then the pager-cache associated with pWal is now
  48559. ** out of date. So zero the cached wal-index header to ensure that
  48560. ** next time the pager opens a snapshot on this database it knows that
  48561. ** the cache needs to be reset.
  48562. */
  48563. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  48564. }
  48565. /* Release the locks. */
  48566. sqlite3WalEndWriteTransaction(pWal);
  48567. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  48568. pWal->ckptLock = 0;
  48569. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  48570. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  48571. }
  48572. /* Return the value to pass to a sqlite3_wal_hook callback, the
  48573. ** number of frames in the WAL at the point of the last commit since
  48574. ** sqlite3WalCallback() was called. If no commits have occurred since
  48575. ** the last call, then return 0.
  48576. */
  48577. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  48578. u32 ret = 0;
  48579. if( pWal ){
  48580. ret = pWal->iCallback;
  48581. pWal->iCallback = 0;
  48582. }
  48583. return (int)ret;
  48584. }
  48585. /*
  48586. ** This function is called to change the WAL subsystem into or out
  48587. ** of locking_mode=EXCLUSIVE.
  48588. **
  48589. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  48590. ** into locking_mode=NORMAL. This means that we must acquire a lock
  48591. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  48592. ** or if the acquisition of the lock fails, then return 0. If the
  48593. ** transition out of exclusive-mode is successful, return 1. This
  48594. ** operation must occur while the pager is still holding the exclusive
  48595. ** lock on the main database file.
  48596. **
  48597. ** If op is one, then change from locking_mode=NORMAL into
  48598. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  48599. ** be released. Return 1 if the transition is made and 0 if the
  48600. ** WAL is already in exclusive-locking mode - meaning that this
  48601. ** routine is a no-op. The pager must already hold the exclusive lock
  48602. ** on the main database file before invoking this operation.
  48603. **
  48604. ** If op is negative, then do a dry-run of the op==1 case but do
  48605. ** not actually change anything. The pager uses this to see if it
  48606. ** should acquire the database exclusive lock prior to invoking
  48607. ** the op==1 case.
  48608. */
  48609. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  48610. int rc;
  48611. assert( pWal->writeLock==0 );
  48612. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  48613. /* pWal->readLock is usually set, but might be -1 if there was a
  48614. ** prior error while attempting to acquire are read-lock. This cannot
  48615. ** happen if the connection is actually in exclusive mode (as no xShmLock
  48616. ** locks are taken in this case). Nor should the pager attempt to
  48617. ** upgrade to exclusive-mode following such an error.
  48618. */
  48619. assert( pWal->readLock>=0 || pWal->lockError );
  48620. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  48621. if( op==0 ){
  48622. if( pWal->exclusiveMode ){
  48623. pWal->exclusiveMode = 0;
  48624. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  48625. pWal->exclusiveMode = 1;
  48626. }
  48627. rc = pWal->exclusiveMode==0;
  48628. }else{
  48629. /* Already in locking_mode=NORMAL */
  48630. rc = 0;
  48631. }
  48632. }else if( op>0 ){
  48633. assert( pWal->exclusiveMode==0 );
  48634. assert( pWal->readLock>=0 );
  48635. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  48636. pWal->exclusiveMode = 1;
  48637. rc = 1;
  48638. }else{
  48639. rc = pWal->exclusiveMode==0;
  48640. }
  48641. return rc;
  48642. }
  48643. /*
  48644. ** Return true if the argument is non-NULL and the WAL module is using
  48645. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  48646. ** WAL module is using shared-memory, return false.
  48647. */
  48648. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  48649. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  48650. }
  48651. #ifdef SQLITE_ENABLE_ZIPVFS
  48652. /*
  48653. ** If the argument is not NULL, it points to a Wal object that holds a
  48654. ** read-lock. This function returns the database page-size if it is known,
  48655. ** or zero if it is not (or if pWal is NULL).
  48656. */
  48657. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  48658. assert( pWal==0 || pWal->readLock>=0 );
  48659. return (pWal ? pWal->szPage : 0);
  48660. }
  48661. #endif
  48662. #endif /* #ifndef SQLITE_OMIT_WAL */
  48663. /************** End of wal.c *************************************************/
  48664. /************** Begin file btmutex.c *****************************************/
  48665. /*
  48666. ** 2007 August 27
  48667. **
  48668. ** The author disclaims copyright to this source code. In place of
  48669. ** a legal notice, here is a blessing:
  48670. **
  48671. ** May you do good and not evil.
  48672. ** May you find forgiveness for yourself and forgive others.
  48673. ** May you share freely, never taking more than you give.
  48674. **
  48675. *************************************************************************
  48676. **
  48677. ** This file contains code used to implement mutexes on Btree objects.
  48678. ** This code really belongs in btree.c. But btree.c is getting too
  48679. ** big and we want to break it down some. This packaged seemed like
  48680. ** a good breakout.
  48681. */
  48682. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  48683. /************** Begin file btreeInt.h ****************************************/
  48684. /*
  48685. ** 2004 April 6
  48686. **
  48687. ** The author disclaims copyright to this source code. In place of
  48688. ** a legal notice, here is a blessing:
  48689. **
  48690. ** May you do good and not evil.
  48691. ** May you find forgiveness for yourself and forgive others.
  48692. ** May you share freely, never taking more than you give.
  48693. **
  48694. *************************************************************************
  48695. ** This file implements a external (disk-based) database using BTrees.
  48696. ** For a detailed discussion of BTrees, refer to
  48697. **
  48698. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  48699. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  48700. ** Publishing Company, Reading, Massachusetts.
  48701. **
  48702. ** The basic idea is that each page of the file contains N database
  48703. ** entries and N+1 pointers to subpages.
  48704. **
  48705. ** ----------------------------------------------------------------
  48706. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  48707. ** ----------------------------------------------------------------
  48708. **
  48709. ** All of the keys on the page that Ptr(0) points to have values less
  48710. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  48711. ** values greater than Key(0) and less than Key(1). All of the keys
  48712. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  48713. ** so forth.
  48714. **
  48715. ** Finding a particular key requires reading O(log(M)) pages from the
  48716. ** disk where M is the number of entries in the tree.
  48717. **
  48718. ** In this implementation, a single file can hold one or more separate
  48719. ** BTrees. Each BTree is identified by the index of its root page. The
  48720. ** key and data for any entry are combined to form the "payload". A
  48721. ** fixed amount of payload can be carried directly on the database
  48722. ** page. If the payload is larger than the preset amount then surplus
  48723. ** bytes are stored on overflow pages. The payload for an entry
  48724. ** and the preceding pointer are combined to form a "Cell". Each
  48725. ** page has a small header which contains the Ptr(N) pointer and other
  48726. ** information such as the size of key and data.
  48727. **
  48728. ** FORMAT DETAILS
  48729. **
  48730. ** The file is divided into pages. The first page is called page 1,
  48731. ** the second is page 2, and so forth. A page number of zero indicates
  48732. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  48733. ** Each page can be either a btree page, a freelist page, an overflow
  48734. ** page, or a pointer-map page.
  48735. **
  48736. ** The first page is always a btree page. The first 100 bytes of the first
  48737. ** page contain a special header (the "file header") that describes the file.
  48738. ** The format of the file header is as follows:
  48739. **
  48740. ** OFFSET SIZE DESCRIPTION
  48741. ** 0 16 Header string: "SQLite format 3\000"
  48742. ** 16 2 Page size in bytes. (1 means 65536)
  48743. ** 18 1 File format write version
  48744. ** 19 1 File format read version
  48745. ** 20 1 Bytes of unused space at the end of each page
  48746. ** 21 1 Max embedded payload fraction (must be 64)
  48747. ** 22 1 Min embedded payload fraction (must be 32)
  48748. ** 23 1 Min leaf payload fraction (must be 32)
  48749. ** 24 4 File change counter
  48750. ** 28 4 Reserved for future use
  48751. ** 32 4 First freelist page
  48752. ** 36 4 Number of freelist pages in the file
  48753. ** 40 60 15 4-byte meta values passed to higher layers
  48754. **
  48755. ** 40 4 Schema cookie
  48756. ** 44 4 File format of schema layer
  48757. ** 48 4 Size of page cache
  48758. ** 52 4 Largest root-page (auto/incr_vacuum)
  48759. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  48760. ** 60 4 User version
  48761. ** 64 4 Incremental vacuum mode
  48762. ** 68 4 Application-ID
  48763. ** 72 20 unused
  48764. ** 92 4 The version-valid-for number
  48765. ** 96 4 SQLITE_VERSION_NUMBER
  48766. **
  48767. ** All of the integer values are big-endian (most significant byte first).
  48768. **
  48769. ** The file change counter is incremented when the database is changed
  48770. ** This counter allows other processes to know when the file has changed
  48771. ** and thus when they need to flush their cache.
  48772. **
  48773. ** The max embedded payload fraction is the amount of the total usable
  48774. ** space in a page that can be consumed by a single cell for standard
  48775. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  48776. ** is to limit the maximum cell size so that at least 4 cells will fit
  48777. ** on one page. Thus the default max embedded payload fraction is 64.
  48778. **
  48779. ** If the payload for a cell is larger than the max payload, then extra
  48780. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  48781. ** as many bytes as possible are moved into the overflow pages without letting
  48782. ** the cell size drop below the min embedded payload fraction.
  48783. **
  48784. ** The min leaf payload fraction is like the min embedded payload fraction
  48785. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  48786. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  48787. ** not specified in the header.
  48788. **
  48789. ** Each btree pages is divided into three sections: The header, the
  48790. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  48791. ** file header that occurs before the page header.
  48792. **
  48793. ** |----------------|
  48794. ** | file header | 100 bytes. Page 1 only.
  48795. ** |----------------|
  48796. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  48797. ** |----------------|
  48798. ** | cell pointer | | 2 bytes per cell. Sorted order.
  48799. ** | array | | Grows downward
  48800. ** | | v
  48801. ** |----------------|
  48802. ** | unallocated |
  48803. ** | space |
  48804. ** |----------------| ^ Grows upwards
  48805. ** | cell content | | Arbitrary order interspersed with freeblocks.
  48806. ** | area | | and free space fragments.
  48807. ** |----------------|
  48808. **
  48809. ** The page headers looks like this:
  48810. **
  48811. ** OFFSET SIZE DESCRIPTION
  48812. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  48813. ** 1 2 byte offset to the first freeblock
  48814. ** 3 2 number of cells on this page
  48815. ** 5 2 first byte of the cell content area
  48816. ** 7 1 number of fragmented free bytes
  48817. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  48818. **
  48819. ** The flags define the format of this btree page. The leaf flag means that
  48820. ** this page has no children. The zerodata flag means that this page carries
  48821. ** only keys and no data. The intkey flag means that the key is a integer
  48822. ** which is stored in the key size entry of the cell header rather than in
  48823. ** the payload area.
  48824. **
  48825. ** The cell pointer array begins on the first byte after the page header.
  48826. ** The cell pointer array contains zero or more 2-byte numbers which are
  48827. ** offsets from the beginning of the page to the cell content in the cell
  48828. ** content area. The cell pointers occur in sorted order. The system strives
  48829. ** to keep free space after the last cell pointer so that new cells can
  48830. ** be easily added without having to defragment the page.
  48831. **
  48832. ** Cell content is stored at the very end of the page and grows toward the
  48833. ** beginning of the page.
  48834. **
  48835. ** Unused space within the cell content area is collected into a linked list of
  48836. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  48837. ** to the first freeblock is given in the header. Freeblocks occur in
  48838. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  48839. ** any group of 3 or fewer unused bytes in the cell content area cannot
  48840. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  48841. ** a fragment. The total number of bytes in all fragments is recorded.
  48842. ** in the page header at offset 7.
  48843. **
  48844. ** SIZE DESCRIPTION
  48845. ** 2 Byte offset of the next freeblock
  48846. ** 2 Bytes in this freeblock
  48847. **
  48848. ** Cells are of variable length. Cells are stored in the cell content area at
  48849. ** the end of the page. Pointers to the cells are in the cell pointer array
  48850. ** that immediately follows the page header. Cells is not necessarily
  48851. ** contiguous or in order, but cell pointers are contiguous and in order.
  48852. **
  48853. ** Cell content makes use of variable length integers. A variable
  48854. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  48855. ** byte are used. The integer consists of all bytes that have bit 8 set and
  48856. ** the first byte with bit 8 clear. The most significant byte of the integer
  48857. ** appears first. A variable-length integer may not be more than 9 bytes long.
  48858. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  48859. ** allows a 64-bit integer to be encoded in 9 bytes.
  48860. **
  48861. ** 0x00 becomes 0x00000000
  48862. ** 0x7f becomes 0x0000007f
  48863. ** 0x81 0x00 becomes 0x00000080
  48864. ** 0x82 0x00 becomes 0x00000100
  48865. ** 0x80 0x7f becomes 0x0000007f
  48866. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  48867. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  48868. **
  48869. ** Variable length integers are used for rowids and to hold the number of
  48870. ** bytes of key and data in a btree cell.
  48871. **
  48872. ** The content of a cell looks like this:
  48873. **
  48874. ** SIZE DESCRIPTION
  48875. ** 4 Page number of the left child. Omitted if leaf flag is set.
  48876. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  48877. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  48878. ** * Payload
  48879. ** 4 First page of the overflow chain. Omitted if no overflow
  48880. **
  48881. ** Overflow pages form a linked list. Each page except the last is completely
  48882. ** filled with data (pagesize - 4 bytes). The last page can have as little
  48883. ** as 1 byte of data.
  48884. **
  48885. ** SIZE DESCRIPTION
  48886. ** 4 Page number of next overflow page
  48887. ** * Data
  48888. **
  48889. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  48890. ** file header points to the first in a linked list of trunk page. Each trunk
  48891. ** page points to multiple leaf pages. The content of a leaf page is
  48892. ** unspecified. A trunk page looks like this:
  48893. **
  48894. ** SIZE DESCRIPTION
  48895. ** 4 Page number of next trunk page
  48896. ** 4 Number of leaf pointers on this page
  48897. ** * zero or more pages numbers of leaves
  48898. */
  48899. /* The following value is the maximum cell size assuming a maximum page
  48900. ** size give above.
  48901. */
  48902. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  48903. /* The maximum number of cells on a single page of the database. This
  48904. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  48905. ** plus 2 bytes for the index to the cell in the page header). Such
  48906. ** small cells will be rare, but they are possible.
  48907. */
  48908. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  48909. /* Forward declarations */
  48910. typedef struct MemPage MemPage;
  48911. typedef struct BtLock BtLock;
  48912. /*
  48913. ** This is a magic string that appears at the beginning of every
  48914. ** SQLite database in order to identify the file as a real database.
  48915. **
  48916. ** You can change this value at compile-time by specifying a
  48917. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  48918. ** header must be exactly 16 bytes including the zero-terminator so
  48919. ** the string itself should be 15 characters long. If you change
  48920. ** the header, then your custom library will not be able to read
  48921. ** databases generated by the standard tools and the standard tools
  48922. ** will not be able to read databases created by your custom library.
  48923. */
  48924. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  48925. # define SQLITE_FILE_HEADER "SQLite format 3"
  48926. #endif
  48927. /*
  48928. ** Page type flags. An ORed combination of these flags appear as the
  48929. ** first byte of on-disk image of every BTree page.
  48930. */
  48931. #define PTF_INTKEY 0x01
  48932. #define PTF_ZERODATA 0x02
  48933. #define PTF_LEAFDATA 0x04
  48934. #define PTF_LEAF 0x08
  48935. /*
  48936. ** As each page of the file is loaded into memory, an instance of the following
  48937. ** structure is appended and initialized to zero. This structure stores
  48938. ** information about the page that is decoded from the raw file page.
  48939. **
  48940. ** The pParent field points back to the parent page. This allows us to
  48941. ** walk up the BTree from any leaf to the root. Care must be taken to
  48942. ** unref() the parent page pointer when this page is no longer referenced.
  48943. ** The pageDestructor() routine handles that chore.
  48944. **
  48945. ** Access to all fields of this structure is controlled by the mutex
  48946. ** stored in MemPage.pBt->mutex.
  48947. */
  48948. struct MemPage {
  48949. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  48950. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  48951. u8 intKey; /* True if intkey flag is set */
  48952. u8 leaf; /* True if leaf flag is set */
  48953. u8 hasData; /* True if this page stores data */
  48954. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  48955. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  48956. u8 max1bytePayload; /* min(maxLocal,127) */
  48957. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  48958. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  48959. u16 cellOffset; /* Index in aData of first cell pointer */
  48960. u16 nFree; /* Number of free bytes on the page */
  48961. u16 nCell; /* Number of cells on this page, local and ovfl */
  48962. u16 maskPage; /* Mask for page offset */
  48963. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  48964. ** non-overflow cell */
  48965. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  48966. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  48967. u8 *aData; /* Pointer to disk image of the page data */
  48968. u8 *aDataEnd; /* One byte past the end of usable data */
  48969. u8 *aCellIdx; /* The cell index area */
  48970. DbPage *pDbPage; /* Pager page handle */
  48971. Pgno pgno; /* Page number for this page */
  48972. };
  48973. /*
  48974. ** The in-memory image of a disk page has the auxiliary information appended
  48975. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  48976. ** that extra information.
  48977. */
  48978. #define EXTRA_SIZE sizeof(MemPage)
  48979. /*
  48980. ** A linked list of the following structures is stored at BtShared.pLock.
  48981. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  48982. ** is opened on the table with root page BtShared.iTable. Locks are removed
  48983. ** from this list when a transaction is committed or rolled back, or when
  48984. ** a btree handle is closed.
  48985. */
  48986. struct BtLock {
  48987. Btree *pBtree; /* Btree handle holding this lock */
  48988. Pgno iTable; /* Root page of table */
  48989. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  48990. BtLock *pNext; /* Next in BtShared.pLock list */
  48991. };
  48992. /* Candidate values for BtLock.eLock */
  48993. #define READ_LOCK 1
  48994. #define WRITE_LOCK 2
  48995. /* A Btree handle
  48996. **
  48997. ** A database connection contains a pointer to an instance of
  48998. ** this object for every database file that it has open. This structure
  48999. ** is opaque to the database connection. The database connection cannot
  49000. ** see the internals of this structure and only deals with pointers to
  49001. ** this structure.
  49002. **
  49003. ** For some database files, the same underlying database cache might be
  49004. ** shared between multiple connections. In that case, each connection
  49005. ** has it own instance of this object. But each instance of this object
  49006. ** points to the same BtShared object. The database cache and the
  49007. ** schema associated with the database file are all contained within
  49008. ** the BtShared object.
  49009. **
  49010. ** All fields in this structure are accessed under sqlite3.mutex.
  49011. ** The pBt pointer itself may not be changed while there exists cursors
  49012. ** in the referenced BtShared that point back to this Btree since those
  49013. ** cursors have to go through this Btree to find their BtShared and
  49014. ** they often do so without holding sqlite3.mutex.
  49015. */
  49016. struct Btree {
  49017. sqlite3 *db; /* The database connection holding this btree */
  49018. BtShared *pBt; /* Sharable content of this btree */
  49019. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  49020. u8 sharable; /* True if we can share pBt with another db */
  49021. u8 locked; /* True if db currently has pBt locked */
  49022. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  49023. int nBackup; /* Number of backup operations reading this btree */
  49024. Btree *pNext; /* List of other sharable Btrees from the same db */
  49025. Btree *pPrev; /* Back pointer of the same list */
  49026. #ifndef SQLITE_OMIT_SHARED_CACHE
  49027. BtLock lock; /* Object used to lock page 1 */
  49028. #endif
  49029. };
  49030. /*
  49031. ** Btree.inTrans may take one of the following values.
  49032. **
  49033. ** If the shared-data extension is enabled, there may be multiple users
  49034. ** of the Btree structure. At most one of these may open a write transaction,
  49035. ** but any number may have active read transactions.
  49036. */
  49037. #define TRANS_NONE 0
  49038. #define TRANS_READ 1
  49039. #define TRANS_WRITE 2
  49040. /*
  49041. ** An instance of this object represents a single database file.
  49042. **
  49043. ** A single database file can be in use at the same time by two
  49044. ** or more database connections. When two or more connections are
  49045. ** sharing the same database file, each connection has it own
  49046. ** private Btree object for the file and each of those Btrees points
  49047. ** to this one BtShared object. BtShared.nRef is the number of
  49048. ** connections currently sharing this database file.
  49049. **
  49050. ** Fields in this structure are accessed under the BtShared.mutex
  49051. ** mutex, except for nRef and pNext which are accessed under the
  49052. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  49053. ** may not be modified once it is initially set as long as nRef>0.
  49054. ** The pSchema field may be set once under BtShared.mutex and
  49055. ** thereafter is unchanged as long as nRef>0.
  49056. **
  49057. ** isPending:
  49058. **
  49059. ** If a BtShared client fails to obtain a write-lock on a database
  49060. ** table (because there exists one or more read-locks on the table),
  49061. ** the shared-cache enters 'pending-lock' state and isPending is
  49062. ** set to true.
  49063. **
  49064. ** The shared-cache leaves the 'pending lock' state when either of
  49065. ** the following occur:
  49066. **
  49067. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  49068. ** 2) The number of locks held by other connections drops to zero.
  49069. **
  49070. ** while in the 'pending-lock' state, no connection may start a new
  49071. ** transaction.
  49072. **
  49073. ** This feature is included to help prevent writer-starvation.
  49074. */
  49075. struct BtShared {
  49076. Pager *pPager; /* The page cache */
  49077. sqlite3 *db; /* Database connection currently using this Btree */
  49078. BtCursor *pCursor; /* A list of all open cursors */
  49079. MemPage *pPage1; /* First page of the database */
  49080. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  49081. #ifndef SQLITE_OMIT_AUTOVACUUM
  49082. u8 autoVacuum; /* True if auto-vacuum is enabled */
  49083. u8 incrVacuum; /* True if incr-vacuum is enabled */
  49084. u8 bDoTruncate; /* True to truncate db on commit */
  49085. #endif
  49086. u8 inTransaction; /* Transaction state */
  49087. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  49088. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  49089. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  49090. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  49091. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  49092. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  49093. u32 pageSize; /* Total number of bytes on a page */
  49094. u32 usableSize; /* Number of usable bytes on each page */
  49095. int nTransaction; /* Number of open transactions (read + write) */
  49096. u32 nPage; /* Number of pages in the database */
  49097. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  49098. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  49099. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  49100. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  49101. #ifndef SQLITE_OMIT_SHARED_CACHE
  49102. int nRef; /* Number of references to this structure */
  49103. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  49104. BtLock *pLock; /* List of locks held on this shared-btree struct */
  49105. Btree *pWriter; /* Btree with currently open write transaction */
  49106. #endif
  49107. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  49108. };
  49109. /*
  49110. ** Allowed values for BtShared.btsFlags
  49111. */
  49112. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  49113. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  49114. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  49115. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  49116. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  49117. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  49118. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  49119. /*
  49120. ** An instance of the following structure is used to hold information
  49121. ** about a cell. The parseCellPtr() function fills in this structure
  49122. ** based on information extract from the raw disk page.
  49123. */
  49124. typedef struct CellInfo CellInfo;
  49125. struct CellInfo {
  49126. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  49127. u8 *pCell; /* Pointer to the start of cell content */
  49128. u32 nData; /* Number of bytes of data */
  49129. u32 nPayload; /* Total amount of payload */
  49130. u16 nHeader; /* Size of the cell content header in bytes */
  49131. u16 nLocal; /* Amount of payload held locally */
  49132. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  49133. u16 nSize; /* Size of the cell content on the main b-tree page */
  49134. };
  49135. /*
  49136. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  49137. ** this will be declared corrupt. This value is calculated based on a
  49138. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  49139. ** root-node and 3 for all other internal nodes.
  49140. **
  49141. ** If a tree that appears to be taller than this is encountered, it is
  49142. ** assumed that the database is corrupt.
  49143. */
  49144. #define BTCURSOR_MAX_DEPTH 20
  49145. /*
  49146. ** A cursor is a pointer to a particular entry within a particular
  49147. ** b-tree within a database file.
  49148. **
  49149. ** The entry is identified by its MemPage and the index in
  49150. ** MemPage.aCell[] of the entry.
  49151. **
  49152. ** A single database file can be shared by two more database connections,
  49153. ** but cursors cannot be shared. Each cursor is associated with a
  49154. ** particular database connection identified BtCursor.pBtree.db.
  49155. **
  49156. ** Fields in this structure are accessed under the BtShared.mutex
  49157. ** found at self->pBt->mutex.
  49158. */
  49159. struct BtCursor {
  49160. Btree *pBtree; /* The Btree to which this cursor belongs */
  49161. BtShared *pBt; /* The BtShared this cursor points to */
  49162. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  49163. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  49164. #ifndef SQLITE_OMIT_INCRBLOB
  49165. Pgno *aOverflow; /* Cache of overflow page locations */
  49166. #endif
  49167. Pgno pgnoRoot; /* The root page of this tree */
  49168. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  49169. CellInfo info; /* A parse of the cell we are pointing at */
  49170. i64 nKey; /* Size of pKey, or last integer key */
  49171. void *pKey; /* Saved key that was cursor's last known position */
  49172. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  49173. u8 wrFlag; /* True if writable */
  49174. u8 atLast; /* Cursor pointing to the last entry */
  49175. u8 validNKey; /* True if info.nKey is valid */
  49176. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  49177. #ifndef SQLITE_OMIT_INCRBLOB
  49178. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  49179. #endif
  49180. u8 hints; /* As configured by CursorSetHints() */
  49181. i16 iPage; /* Index of current page in apPage */
  49182. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  49183. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  49184. };
  49185. /*
  49186. ** Potential values for BtCursor.eState.
  49187. **
  49188. ** CURSOR_INVALID:
  49189. ** Cursor does not point to a valid entry. This can happen (for example)
  49190. ** because the table is empty or because BtreeCursorFirst() has not been
  49191. ** called.
  49192. **
  49193. ** CURSOR_VALID:
  49194. ** Cursor points to a valid entry. getPayload() etc. may be called.
  49195. **
  49196. ** CURSOR_SKIPNEXT:
  49197. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  49198. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  49199. ** operation should be a no-op.
  49200. **
  49201. ** CURSOR_REQUIRESEEK:
  49202. ** The table that this cursor was opened on still exists, but has been
  49203. ** modified since the cursor was last used. The cursor position is saved
  49204. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  49205. ** this state, restoreCursorPosition() can be called to attempt to
  49206. ** seek the cursor to the saved position.
  49207. **
  49208. ** CURSOR_FAULT:
  49209. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  49210. ** on a different connection that shares the BtShared cache with this
  49211. ** cursor. The error has left the cache in an inconsistent state.
  49212. ** Do nothing else with this cursor. Any attempt to use the cursor
  49213. ** should return the error code stored in BtCursor.skip
  49214. */
  49215. #define CURSOR_INVALID 0
  49216. #define CURSOR_VALID 1
  49217. #define CURSOR_SKIPNEXT 2
  49218. #define CURSOR_REQUIRESEEK 3
  49219. #define CURSOR_FAULT 4
  49220. /*
  49221. ** The database page the PENDING_BYTE occupies. This page is never used.
  49222. */
  49223. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  49224. /*
  49225. ** These macros define the location of the pointer-map entry for a
  49226. ** database page. The first argument to each is the number of usable
  49227. ** bytes on each page of the database (often 1024). The second is the
  49228. ** page number to look up in the pointer map.
  49229. **
  49230. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  49231. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  49232. ** the offset of the requested map entry.
  49233. **
  49234. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  49235. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  49236. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  49237. ** this test.
  49238. */
  49239. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  49240. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  49241. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  49242. /*
  49243. ** The pointer map is a lookup table that identifies the parent page for
  49244. ** each child page in the database file. The parent page is the page that
  49245. ** contains a pointer to the child. Every page in the database contains
  49246. ** 0 or 1 parent pages. (In this context 'database page' refers
  49247. ** to any page that is not part of the pointer map itself.) Each pointer map
  49248. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  49249. ** The PTRMAP_XXX identifiers below are the valid types.
  49250. **
  49251. ** The purpose of the pointer map is to facility moving pages from one
  49252. ** position in the file to another as part of autovacuum. When a page
  49253. ** is moved, the pointer in its parent must be updated to point to the
  49254. ** new location. The pointer map is used to locate the parent page quickly.
  49255. **
  49256. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  49257. ** used in this case.
  49258. **
  49259. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  49260. ** is not used in this case.
  49261. **
  49262. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  49263. ** overflow pages. The page number identifies the page that
  49264. ** contains the cell with a pointer to this overflow page.
  49265. **
  49266. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  49267. ** overflow pages. The page-number identifies the previous
  49268. ** page in the overflow page list.
  49269. **
  49270. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  49271. ** identifies the parent page in the btree.
  49272. */
  49273. #define PTRMAP_ROOTPAGE 1
  49274. #define PTRMAP_FREEPAGE 2
  49275. #define PTRMAP_OVERFLOW1 3
  49276. #define PTRMAP_OVERFLOW2 4
  49277. #define PTRMAP_BTREE 5
  49278. /* A bunch of assert() statements to check the transaction state variables
  49279. ** of handle p (type Btree*) are internally consistent.
  49280. */
  49281. #define btreeIntegrity(p) \
  49282. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  49283. assert( p->pBt->inTransaction>=p->inTrans );
  49284. /*
  49285. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  49286. ** if the database supports auto-vacuum or not. Because it is used
  49287. ** within an expression that is an argument to another macro
  49288. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  49289. ** So, this macro is defined instead.
  49290. */
  49291. #ifndef SQLITE_OMIT_AUTOVACUUM
  49292. #define ISAUTOVACUUM (pBt->autoVacuum)
  49293. #else
  49294. #define ISAUTOVACUUM 0
  49295. #endif
  49296. /*
  49297. ** This structure is passed around through all the sanity checking routines
  49298. ** in order to keep track of some global state information.
  49299. **
  49300. ** The aRef[] array is allocated so that there is 1 bit for each page in
  49301. ** the database. As the integrity-check proceeds, for each page used in
  49302. ** the database the corresponding bit is set. This allows integrity-check to
  49303. ** detect pages that are used twice and orphaned pages (both of which
  49304. ** indicate corruption).
  49305. */
  49306. typedef struct IntegrityCk IntegrityCk;
  49307. struct IntegrityCk {
  49308. BtShared *pBt; /* The tree being checked out */
  49309. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  49310. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  49311. Pgno nPage; /* Number of pages in the database */
  49312. int mxErr; /* Stop accumulating errors when this reaches zero */
  49313. int nErr; /* Number of messages written to zErrMsg so far */
  49314. int mallocFailed; /* A memory allocation error has occurred */
  49315. StrAccum errMsg; /* Accumulate the error message text here */
  49316. };
  49317. /*
  49318. ** Routines to read or write a two- and four-byte big-endian integer values.
  49319. */
  49320. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  49321. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  49322. #define get4byte sqlite3Get4byte
  49323. #define put4byte sqlite3Put4byte
  49324. /************** End of btreeInt.h ********************************************/
  49325. /************** Continuing where we left off in btmutex.c ********************/
  49326. #ifndef SQLITE_OMIT_SHARED_CACHE
  49327. #if SQLITE_THREADSAFE
  49328. /*
  49329. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  49330. ** set BtShared.db to the database handle associated with p and the
  49331. ** p->locked boolean to true.
  49332. */
  49333. static void lockBtreeMutex(Btree *p){
  49334. assert( p->locked==0 );
  49335. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  49336. assert( sqlite3_mutex_held(p->db->mutex) );
  49337. sqlite3_mutex_enter(p->pBt->mutex);
  49338. p->pBt->db = p->db;
  49339. p->locked = 1;
  49340. }
  49341. /*
  49342. ** Release the BtShared mutex associated with B-Tree handle p and
  49343. ** clear the p->locked boolean.
  49344. */
  49345. static void unlockBtreeMutex(Btree *p){
  49346. BtShared *pBt = p->pBt;
  49347. assert( p->locked==1 );
  49348. assert( sqlite3_mutex_held(pBt->mutex) );
  49349. assert( sqlite3_mutex_held(p->db->mutex) );
  49350. assert( p->db==pBt->db );
  49351. sqlite3_mutex_leave(pBt->mutex);
  49352. p->locked = 0;
  49353. }
  49354. /*
  49355. ** Enter a mutex on the given BTree object.
  49356. **
  49357. ** If the object is not sharable, then no mutex is ever required
  49358. ** and this routine is a no-op. The underlying mutex is non-recursive.
  49359. ** But we keep a reference count in Btree.wantToLock so the behavior
  49360. ** of this interface is recursive.
  49361. **
  49362. ** To avoid deadlocks, multiple Btrees are locked in the same order
  49363. ** by all database connections. The p->pNext is a list of other
  49364. ** Btrees belonging to the same database connection as the p Btree
  49365. ** which need to be locked after p. If we cannot get a lock on
  49366. ** p, then first unlock all of the others on p->pNext, then wait
  49367. ** for the lock to become available on p, then relock all of the
  49368. ** subsequent Btrees that desire a lock.
  49369. */
  49370. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49371. Btree *pLater;
  49372. /* Some basic sanity checking on the Btree. The list of Btrees
  49373. ** connected by pNext and pPrev should be in sorted order by
  49374. ** Btree.pBt value. All elements of the list should belong to
  49375. ** the same connection. Only shared Btrees are on the list. */
  49376. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  49377. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  49378. assert( p->pNext==0 || p->pNext->db==p->db );
  49379. assert( p->pPrev==0 || p->pPrev->db==p->db );
  49380. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  49381. /* Check for locking consistency */
  49382. assert( !p->locked || p->wantToLock>0 );
  49383. assert( p->sharable || p->wantToLock==0 );
  49384. /* We should already hold a lock on the database connection */
  49385. assert( sqlite3_mutex_held(p->db->mutex) );
  49386. /* Unless the database is sharable and unlocked, then BtShared.db
  49387. ** should already be set correctly. */
  49388. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  49389. if( !p->sharable ) return;
  49390. p->wantToLock++;
  49391. if( p->locked ) return;
  49392. /* In most cases, we should be able to acquire the lock we
  49393. ** want without having to go throught the ascending lock
  49394. ** procedure that follows. Just be sure not to block.
  49395. */
  49396. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  49397. p->pBt->db = p->db;
  49398. p->locked = 1;
  49399. return;
  49400. }
  49401. /* To avoid deadlock, first release all locks with a larger
  49402. ** BtShared address. Then acquire our lock. Then reacquire
  49403. ** the other BtShared locks that we used to hold in ascending
  49404. ** order.
  49405. */
  49406. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49407. assert( pLater->sharable );
  49408. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  49409. assert( !pLater->locked || pLater->wantToLock>0 );
  49410. if( pLater->locked ){
  49411. unlockBtreeMutex(pLater);
  49412. }
  49413. }
  49414. lockBtreeMutex(p);
  49415. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49416. if( pLater->wantToLock ){
  49417. lockBtreeMutex(pLater);
  49418. }
  49419. }
  49420. }
  49421. /*
  49422. ** Exit the recursive mutex on a Btree.
  49423. */
  49424. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  49425. if( p->sharable ){
  49426. assert( p->wantToLock>0 );
  49427. p->wantToLock--;
  49428. if( p->wantToLock==0 ){
  49429. unlockBtreeMutex(p);
  49430. }
  49431. }
  49432. }
  49433. #ifndef NDEBUG
  49434. /*
  49435. ** Return true if the BtShared mutex is held on the btree, or if the
  49436. ** B-Tree is not marked as sharable.
  49437. **
  49438. ** This routine is used only from within assert() statements.
  49439. */
  49440. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  49441. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  49442. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  49443. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  49444. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  49445. return (p->sharable==0 || p->locked);
  49446. }
  49447. #endif
  49448. #ifndef SQLITE_OMIT_INCRBLOB
  49449. /*
  49450. ** Enter and leave a mutex on a Btree given a cursor owned by that
  49451. ** Btree. These entry points are used by incremental I/O and can be
  49452. ** omitted if that module is not used.
  49453. */
  49454. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  49455. sqlite3BtreeEnter(pCur->pBtree);
  49456. }
  49457. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  49458. sqlite3BtreeLeave(pCur->pBtree);
  49459. }
  49460. #endif /* SQLITE_OMIT_INCRBLOB */
  49461. /*
  49462. ** Enter the mutex on every Btree associated with a database
  49463. ** connection. This is needed (for example) prior to parsing
  49464. ** a statement since we will be comparing table and column names
  49465. ** against all schemas and we do not want those schemas being
  49466. ** reset out from under us.
  49467. **
  49468. ** There is a corresponding leave-all procedures.
  49469. **
  49470. ** Enter the mutexes in accending order by BtShared pointer address
  49471. ** to avoid the possibility of deadlock when two threads with
  49472. ** two or more btrees in common both try to lock all their btrees
  49473. ** at the same instant.
  49474. */
  49475. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49476. int i;
  49477. Btree *p;
  49478. assert( sqlite3_mutex_held(db->mutex) );
  49479. for(i=0; i<db->nDb; i++){
  49480. p = db->aDb[i].pBt;
  49481. if( p ) sqlite3BtreeEnter(p);
  49482. }
  49483. }
  49484. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  49485. int i;
  49486. Btree *p;
  49487. assert( sqlite3_mutex_held(db->mutex) );
  49488. for(i=0; i<db->nDb; i++){
  49489. p = db->aDb[i].pBt;
  49490. if( p ) sqlite3BtreeLeave(p);
  49491. }
  49492. }
  49493. /*
  49494. ** Return true if a particular Btree requires a lock. Return FALSE if
  49495. ** no lock is ever required since it is not sharable.
  49496. */
  49497. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  49498. return p->sharable;
  49499. }
  49500. #ifndef NDEBUG
  49501. /*
  49502. ** Return true if the current thread holds the database connection
  49503. ** mutex and all required BtShared mutexes.
  49504. **
  49505. ** This routine is used inside assert() statements only.
  49506. */
  49507. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  49508. int i;
  49509. if( !sqlite3_mutex_held(db->mutex) ){
  49510. return 0;
  49511. }
  49512. for(i=0; i<db->nDb; i++){
  49513. Btree *p;
  49514. p = db->aDb[i].pBt;
  49515. if( p && p->sharable &&
  49516. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  49517. return 0;
  49518. }
  49519. }
  49520. return 1;
  49521. }
  49522. #endif /* NDEBUG */
  49523. #ifndef NDEBUG
  49524. /*
  49525. ** Return true if the correct mutexes are held for accessing the
  49526. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  49527. ** access are:
  49528. **
  49529. ** (1) The mutex on db
  49530. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  49531. **
  49532. ** If pSchema is not NULL, then iDb is computed from pSchema and
  49533. ** db using sqlite3SchemaToIndex().
  49534. */
  49535. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  49536. Btree *p;
  49537. assert( db!=0 );
  49538. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  49539. assert( iDb>=0 && iDb<db->nDb );
  49540. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  49541. if( iDb==1 ) return 1;
  49542. p = db->aDb[iDb].pBt;
  49543. assert( p!=0 );
  49544. return p->sharable==0 || p->locked==1;
  49545. }
  49546. #endif /* NDEBUG */
  49547. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  49548. /*
  49549. ** The following are special cases for mutex enter routines for use
  49550. ** in single threaded applications that use shared cache. Except for
  49551. ** these two routines, all mutex operations are no-ops in that case and
  49552. ** are null #defines in btree.h.
  49553. **
  49554. ** If shared cache is disabled, then all btree mutex routines, including
  49555. ** the ones below, are no-ops and are null #defines in btree.h.
  49556. */
  49557. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49558. p->pBt->db = p->db;
  49559. }
  49560. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49561. int i;
  49562. for(i=0; i<db->nDb; i++){
  49563. Btree *p = db->aDb[i].pBt;
  49564. if( p ){
  49565. p->pBt->db = p->db;
  49566. }
  49567. }
  49568. }
  49569. #endif /* if SQLITE_THREADSAFE */
  49570. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  49571. /************** End of btmutex.c *********************************************/
  49572. /************** Begin file btree.c *******************************************/
  49573. /*
  49574. ** 2004 April 6
  49575. **
  49576. ** The author disclaims copyright to this source code. In place of
  49577. ** a legal notice, here is a blessing:
  49578. **
  49579. ** May you do good and not evil.
  49580. ** May you find forgiveness for yourself and forgive others.
  49581. ** May you share freely, never taking more than you give.
  49582. **
  49583. *************************************************************************
  49584. ** This file implements a external (disk-based) database using BTrees.
  49585. ** See the header comment on "btreeInt.h" for additional information.
  49586. ** Including a description of file format and an overview of operation.
  49587. */
  49588. /*
  49589. ** The header string that appears at the beginning of every
  49590. ** SQLite database.
  49591. */
  49592. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  49593. /*
  49594. ** Set this global variable to 1 to enable tracing using the TRACE
  49595. ** macro.
  49596. */
  49597. #if 0
  49598. int sqlite3BtreeTrace=1; /* True to enable tracing */
  49599. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  49600. #else
  49601. # define TRACE(X)
  49602. #endif
  49603. /*
  49604. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  49605. ** But if the value is zero, make it 65536.
  49606. **
  49607. ** This routine is used to extract the "offset to cell content area" value
  49608. ** from the header of a btree page. If the page size is 65536 and the page
  49609. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  49610. ** This routine makes the necessary adjustment to 65536.
  49611. */
  49612. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  49613. /*
  49614. ** Values passed as the 5th argument to allocateBtreePage()
  49615. */
  49616. #define BTALLOC_ANY 0 /* Allocate any page */
  49617. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  49618. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  49619. /*
  49620. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  49621. ** defined, or 0 if it is. For example:
  49622. **
  49623. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  49624. */
  49625. #ifndef SQLITE_OMIT_AUTOVACUUM
  49626. #define IfNotOmitAV(expr) (expr)
  49627. #else
  49628. #define IfNotOmitAV(expr) 0
  49629. #endif
  49630. #ifndef SQLITE_OMIT_SHARED_CACHE
  49631. /*
  49632. ** A list of BtShared objects that are eligible for participation
  49633. ** in shared cache. This variable has file scope during normal builds,
  49634. ** but the test harness needs to access it so we make it global for
  49635. ** test builds.
  49636. **
  49637. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  49638. */
  49639. #ifdef SQLITE_TEST
  49640. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49641. #else
  49642. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49643. #endif
  49644. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49645. #ifndef SQLITE_OMIT_SHARED_CACHE
  49646. /*
  49647. ** Enable or disable the shared pager and schema features.
  49648. **
  49649. ** This routine has no effect on existing database connections.
  49650. ** The shared cache setting effects only future calls to
  49651. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  49652. */
  49653. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  49654. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  49655. return SQLITE_OK;
  49656. }
  49657. #endif
  49658. #ifdef SQLITE_OMIT_SHARED_CACHE
  49659. /*
  49660. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  49661. ** and clearAllSharedCacheTableLocks()
  49662. ** manipulate entries in the BtShared.pLock linked list used to store
  49663. ** shared-cache table level locks. If the library is compiled with the
  49664. ** shared-cache feature disabled, then there is only ever one user
  49665. ** of each BtShared structure and so this locking is not necessary.
  49666. ** So define the lock related functions as no-ops.
  49667. */
  49668. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  49669. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  49670. #define clearAllSharedCacheTableLocks(a)
  49671. #define downgradeAllSharedCacheTableLocks(a)
  49672. #define hasSharedCacheTableLock(a,b,c,d) 1
  49673. #define hasReadConflicts(a, b) 0
  49674. #endif
  49675. #ifndef SQLITE_OMIT_SHARED_CACHE
  49676. #ifdef SQLITE_DEBUG
  49677. /*
  49678. **** This function is only used as part of an assert() statement. ***
  49679. **
  49680. ** Check to see if pBtree holds the required locks to read or write to the
  49681. ** table with root page iRoot. Return 1 if it does and 0 if not.
  49682. **
  49683. ** For example, when writing to a table with root-page iRoot via
  49684. ** Btree connection pBtree:
  49685. **
  49686. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  49687. **
  49688. ** When writing to an index that resides in a sharable database, the
  49689. ** caller should have first obtained a lock specifying the root page of
  49690. ** the corresponding table. This makes things a bit more complicated,
  49691. ** as this module treats each table as a separate structure. To determine
  49692. ** the table corresponding to the index being written, this
  49693. ** function has to search through the database schema.
  49694. **
  49695. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  49696. ** hold a write-lock on the schema table (root page 1). This is also
  49697. ** acceptable.
  49698. */
  49699. static int hasSharedCacheTableLock(
  49700. Btree *pBtree, /* Handle that must hold lock */
  49701. Pgno iRoot, /* Root page of b-tree */
  49702. int isIndex, /* True if iRoot is the root of an index b-tree */
  49703. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  49704. ){
  49705. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  49706. Pgno iTab = 0;
  49707. BtLock *pLock;
  49708. /* If this database is not shareable, or if the client is reading
  49709. ** and has the read-uncommitted flag set, then no lock is required.
  49710. ** Return true immediately.
  49711. */
  49712. if( (pBtree->sharable==0)
  49713. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  49714. ){
  49715. return 1;
  49716. }
  49717. /* If the client is reading or writing an index and the schema is
  49718. ** not loaded, then it is too difficult to actually check to see if
  49719. ** the correct locks are held. So do not bother - just return true.
  49720. ** This case does not come up very often anyhow.
  49721. */
  49722. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  49723. return 1;
  49724. }
  49725. /* Figure out the root-page that the lock should be held on. For table
  49726. ** b-trees, this is just the root page of the b-tree being read or
  49727. ** written. For index b-trees, it is the root page of the associated
  49728. ** table. */
  49729. if( isIndex ){
  49730. HashElem *p;
  49731. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  49732. Index *pIdx = (Index *)sqliteHashData(p);
  49733. if( pIdx->tnum==(int)iRoot ){
  49734. iTab = pIdx->pTable->tnum;
  49735. }
  49736. }
  49737. }else{
  49738. iTab = iRoot;
  49739. }
  49740. /* Search for the required lock. Either a write-lock on root-page iTab, a
  49741. ** write-lock on the schema table, or (if the client is reading) a
  49742. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  49743. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  49744. if( pLock->pBtree==pBtree
  49745. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  49746. && pLock->eLock>=eLockType
  49747. ){
  49748. return 1;
  49749. }
  49750. }
  49751. /* Failed to find the required lock. */
  49752. return 0;
  49753. }
  49754. #endif /* SQLITE_DEBUG */
  49755. #ifdef SQLITE_DEBUG
  49756. /*
  49757. **** This function may be used as part of assert() statements only. ****
  49758. **
  49759. ** Return true if it would be illegal for pBtree to write into the
  49760. ** table or index rooted at iRoot because other shared connections are
  49761. ** simultaneously reading that same table or index.
  49762. **
  49763. ** It is illegal for pBtree to write if some other Btree object that
  49764. ** shares the same BtShared object is currently reading or writing
  49765. ** the iRoot table. Except, if the other Btree object has the
  49766. ** read-uncommitted flag set, then it is OK for the other object to
  49767. ** have a read cursor.
  49768. **
  49769. ** For example, before writing to any part of the table or index
  49770. ** rooted at page iRoot, one should call:
  49771. **
  49772. ** assert( !hasReadConflicts(pBtree, iRoot) );
  49773. */
  49774. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  49775. BtCursor *p;
  49776. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  49777. if( p->pgnoRoot==iRoot
  49778. && p->pBtree!=pBtree
  49779. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  49780. ){
  49781. return 1;
  49782. }
  49783. }
  49784. return 0;
  49785. }
  49786. #endif /* #ifdef SQLITE_DEBUG */
  49787. /*
  49788. ** Query to see if Btree handle p may obtain a lock of type eLock
  49789. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  49790. ** SQLITE_OK if the lock may be obtained (by calling
  49791. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  49792. */
  49793. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  49794. BtShared *pBt = p->pBt;
  49795. BtLock *pIter;
  49796. assert( sqlite3BtreeHoldsMutex(p) );
  49797. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49798. assert( p->db!=0 );
  49799. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  49800. /* If requesting a write-lock, then the Btree must have an open write
  49801. ** transaction on this file. And, obviously, for this to be so there
  49802. ** must be an open write transaction on the file itself.
  49803. */
  49804. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  49805. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  49806. /* This routine is a no-op if the shared-cache is not enabled */
  49807. if( !p->sharable ){
  49808. return SQLITE_OK;
  49809. }
  49810. /* If some other connection is holding an exclusive lock, the
  49811. ** requested lock may not be obtained.
  49812. */
  49813. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  49814. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  49815. return SQLITE_LOCKED_SHAREDCACHE;
  49816. }
  49817. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49818. /* The condition (pIter->eLock!=eLock) in the following if(...)
  49819. ** statement is a simplification of:
  49820. **
  49821. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  49822. **
  49823. ** since we know that if eLock==WRITE_LOCK, then no other connection
  49824. ** may hold a WRITE_LOCK on any table in this file (since there can
  49825. ** only be a single writer).
  49826. */
  49827. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  49828. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  49829. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  49830. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  49831. if( eLock==WRITE_LOCK ){
  49832. assert( p==pBt->pWriter );
  49833. pBt->btsFlags |= BTS_PENDING;
  49834. }
  49835. return SQLITE_LOCKED_SHAREDCACHE;
  49836. }
  49837. }
  49838. return SQLITE_OK;
  49839. }
  49840. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49841. #ifndef SQLITE_OMIT_SHARED_CACHE
  49842. /*
  49843. ** Add a lock on the table with root-page iTable to the shared-btree used
  49844. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  49845. ** WRITE_LOCK.
  49846. **
  49847. ** This function assumes the following:
  49848. **
  49849. ** (a) The specified Btree object p is connected to a sharable
  49850. ** database (one with the BtShared.sharable flag set), and
  49851. **
  49852. ** (b) No other Btree objects hold a lock that conflicts
  49853. ** with the requested lock (i.e. querySharedCacheTableLock() has
  49854. ** already been called and returned SQLITE_OK).
  49855. **
  49856. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  49857. ** is returned if a malloc attempt fails.
  49858. */
  49859. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  49860. BtShared *pBt = p->pBt;
  49861. BtLock *pLock = 0;
  49862. BtLock *pIter;
  49863. assert( sqlite3BtreeHoldsMutex(p) );
  49864. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49865. assert( p->db!=0 );
  49866. /* A connection with the read-uncommitted flag set will never try to
  49867. ** obtain a read-lock using this function. The only read-lock obtained
  49868. ** by a connection in read-uncommitted mode is on the sqlite_master
  49869. ** table, and that lock is obtained in BtreeBeginTrans(). */
  49870. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  49871. /* This function should only be called on a sharable b-tree after it
  49872. ** has been determined that no other b-tree holds a conflicting lock. */
  49873. assert( p->sharable );
  49874. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  49875. /* First search the list for an existing lock on this table. */
  49876. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49877. if( pIter->iTable==iTable && pIter->pBtree==p ){
  49878. pLock = pIter;
  49879. break;
  49880. }
  49881. }
  49882. /* If the above search did not find a BtLock struct associating Btree p
  49883. ** with table iTable, allocate one and link it into the list.
  49884. */
  49885. if( !pLock ){
  49886. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  49887. if( !pLock ){
  49888. return SQLITE_NOMEM;
  49889. }
  49890. pLock->iTable = iTable;
  49891. pLock->pBtree = p;
  49892. pLock->pNext = pBt->pLock;
  49893. pBt->pLock = pLock;
  49894. }
  49895. /* Set the BtLock.eLock variable to the maximum of the current lock
  49896. ** and the requested lock. This means if a write-lock was already held
  49897. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  49898. */
  49899. assert( WRITE_LOCK>READ_LOCK );
  49900. if( eLock>pLock->eLock ){
  49901. pLock->eLock = eLock;
  49902. }
  49903. return SQLITE_OK;
  49904. }
  49905. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49906. #ifndef SQLITE_OMIT_SHARED_CACHE
  49907. /*
  49908. ** Release all the table locks (locks obtained via calls to
  49909. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  49910. **
  49911. ** This function assumes that Btree p has an open read or write
  49912. ** transaction. If it does not, then the BTS_PENDING flag
  49913. ** may be incorrectly cleared.
  49914. */
  49915. static void clearAllSharedCacheTableLocks(Btree *p){
  49916. BtShared *pBt = p->pBt;
  49917. BtLock **ppIter = &pBt->pLock;
  49918. assert( sqlite3BtreeHoldsMutex(p) );
  49919. assert( p->sharable || 0==*ppIter );
  49920. assert( p->inTrans>0 );
  49921. while( *ppIter ){
  49922. BtLock *pLock = *ppIter;
  49923. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  49924. assert( pLock->pBtree->inTrans>=pLock->eLock );
  49925. if( pLock->pBtree==p ){
  49926. *ppIter = pLock->pNext;
  49927. assert( pLock->iTable!=1 || pLock==&p->lock );
  49928. if( pLock->iTable!=1 ){
  49929. sqlite3_free(pLock);
  49930. }
  49931. }else{
  49932. ppIter = &pLock->pNext;
  49933. }
  49934. }
  49935. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  49936. if( pBt->pWriter==p ){
  49937. pBt->pWriter = 0;
  49938. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49939. }else if( pBt->nTransaction==2 ){
  49940. /* This function is called when Btree p is concluding its
  49941. ** transaction. If there currently exists a writer, and p is not
  49942. ** that writer, then the number of locks held by connections other
  49943. ** than the writer must be about to drop to zero. In this case
  49944. ** set the BTS_PENDING flag to 0.
  49945. **
  49946. ** If there is not currently a writer, then BTS_PENDING must
  49947. ** be zero already. So this next line is harmless in that case.
  49948. */
  49949. pBt->btsFlags &= ~BTS_PENDING;
  49950. }
  49951. }
  49952. /*
  49953. ** This function changes all write-locks held by Btree p into read-locks.
  49954. */
  49955. static void downgradeAllSharedCacheTableLocks(Btree *p){
  49956. BtShared *pBt = p->pBt;
  49957. if( pBt->pWriter==p ){
  49958. BtLock *pLock;
  49959. pBt->pWriter = 0;
  49960. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49961. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  49962. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  49963. pLock->eLock = READ_LOCK;
  49964. }
  49965. }
  49966. }
  49967. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49968. static void releasePage(MemPage *pPage); /* Forward reference */
  49969. /*
  49970. ***** This routine is used inside of assert() only ****
  49971. **
  49972. ** Verify that the cursor holds the mutex on its BtShared
  49973. */
  49974. #ifdef SQLITE_DEBUG
  49975. static int cursorHoldsMutex(BtCursor *p){
  49976. return sqlite3_mutex_held(p->pBt->mutex);
  49977. }
  49978. #endif
  49979. #ifndef SQLITE_OMIT_INCRBLOB
  49980. /*
  49981. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  49982. */
  49983. static void invalidateOverflowCache(BtCursor *pCur){
  49984. assert( cursorHoldsMutex(pCur) );
  49985. sqlite3_free(pCur->aOverflow);
  49986. pCur->aOverflow = 0;
  49987. }
  49988. /*
  49989. ** Invalidate the overflow page-list cache for all cursors opened
  49990. ** on the shared btree structure pBt.
  49991. */
  49992. static void invalidateAllOverflowCache(BtShared *pBt){
  49993. BtCursor *p;
  49994. assert( sqlite3_mutex_held(pBt->mutex) );
  49995. for(p=pBt->pCursor; p; p=p->pNext){
  49996. invalidateOverflowCache(p);
  49997. }
  49998. }
  49999. /*
  50000. ** This function is called before modifying the contents of a table
  50001. ** to invalidate any incrblob cursors that are open on the
  50002. ** row or one of the rows being modified.
  50003. **
  50004. ** If argument isClearTable is true, then the entire contents of the
  50005. ** table is about to be deleted. In this case invalidate all incrblob
  50006. ** cursors open on any row within the table with root-page pgnoRoot.
  50007. **
  50008. ** Otherwise, if argument isClearTable is false, then the row with
  50009. ** rowid iRow is being replaced or deleted. In this case invalidate
  50010. ** only those incrblob cursors open on that specific row.
  50011. */
  50012. static void invalidateIncrblobCursors(
  50013. Btree *pBtree, /* The database file to check */
  50014. i64 iRow, /* The rowid that might be changing */
  50015. int isClearTable /* True if all rows are being deleted */
  50016. ){
  50017. BtCursor *p;
  50018. BtShared *pBt = pBtree->pBt;
  50019. assert( sqlite3BtreeHoldsMutex(pBtree) );
  50020. for(p=pBt->pCursor; p; p=p->pNext){
  50021. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  50022. p->eState = CURSOR_INVALID;
  50023. }
  50024. }
  50025. }
  50026. #else
  50027. /* Stub functions when INCRBLOB is omitted */
  50028. #define invalidateOverflowCache(x)
  50029. #define invalidateAllOverflowCache(x)
  50030. #define invalidateIncrblobCursors(x,y,z)
  50031. #endif /* SQLITE_OMIT_INCRBLOB */
  50032. /*
  50033. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  50034. ** when a page that previously contained data becomes a free-list leaf
  50035. ** page.
  50036. **
  50037. ** The BtShared.pHasContent bitvec exists to work around an obscure
  50038. ** bug caused by the interaction of two useful IO optimizations surrounding
  50039. ** free-list leaf pages:
  50040. **
  50041. ** 1) When all data is deleted from a page and the page becomes
  50042. ** a free-list leaf page, the page is not written to the database
  50043. ** (as free-list leaf pages contain no meaningful data). Sometimes
  50044. ** such a page is not even journalled (as it will not be modified,
  50045. ** why bother journalling it?).
  50046. **
  50047. ** 2) When a free-list leaf page is reused, its content is not read
  50048. ** from the database or written to the journal file (why should it
  50049. ** be, if it is not at all meaningful?).
  50050. **
  50051. ** By themselves, these optimizations work fine and provide a handy
  50052. ** performance boost to bulk delete or insert operations. However, if
  50053. ** a page is moved to the free-list and then reused within the same
  50054. ** transaction, a problem comes up. If the page is not journalled when
  50055. ** it is moved to the free-list and it is also not journalled when it
  50056. ** is extracted from the free-list and reused, then the original data
  50057. ** may be lost. In the event of a rollback, it may not be possible
  50058. ** to restore the database to its original configuration.
  50059. **
  50060. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  50061. ** moved to become a free-list leaf page, the corresponding bit is
  50062. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  50063. ** optimization 2 above is omitted if the corresponding bit is already
  50064. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  50065. ** at the end of every transaction.
  50066. */
  50067. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  50068. int rc = SQLITE_OK;
  50069. if( !pBt->pHasContent ){
  50070. assert( pgno<=pBt->nPage );
  50071. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  50072. if( !pBt->pHasContent ){
  50073. rc = SQLITE_NOMEM;
  50074. }
  50075. }
  50076. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  50077. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  50078. }
  50079. return rc;
  50080. }
  50081. /*
  50082. ** Query the BtShared.pHasContent vector.
  50083. **
  50084. ** This function is called when a free-list leaf page is removed from the
  50085. ** free-list for reuse. It returns false if it is safe to retrieve the
  50086. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  50087. */
  50088. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  50089. Bitvec *p = pBt->pHasContent;
  50090. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  50091. }
  50092. /*
  50093. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  50094. ** invoked at the conclusion of each write-transaction.
  50095. */
  50096. static void btreeClearHasContent(BtShared *pBt){
  50097. sqlite3BitvecDestroy(pBt->pHasContent);
  50098. pBt->pHasContent = 0;
  50099. }
  50100. /*
  50101. ** Release all of the apPage[] pages for a cursor.
  50102. */
  50103. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  50104. int i;
  50105. for(i=0; i<=pCur->iPage; i++){
  50106. releasePage(pCur->apPage[i]);
  50107. pCur->apPage[i] = 0;
  50108. }
  50109. pCur->iPage = -1;
  50110. }
  50111. /*
  50112. ** Save the current cursor position in the variables BtCursor.nKey
  50113. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  50114. **
  50115. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  50116. ** prior to calling this routine.
  50117. */
  50118. static int saveCursorPosition(BtCursor *pCur){
  50119. int rc;
  50120. assert( CURSOR_VALID==pCur->eState );
  50121. assert( 0==pCur->pKey );
  50122. assert( cursorHoldsMutex(pCur) );
  50123. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  50124. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  50125. /* If this is an intKey table, then the above call to BtreeKeySize()
  50126. ** stores the integer key in pCur->nKey. In this case this value is
  50127. ** all that is required. Otherwise, if pCur is not open on an intKey
  50128. ** table, then malloc space for and store the pCur->nKey bytes of key
  50129. ** data.
  50130. */
  50131. if( 0==pCur->apPage[0]->intKey ){
  50132. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  50133. if( pKey ){
  50134. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  50135. if( rc==SQLITE_OK ){
  50136. pCur->pKey = pKey;
  50137. }else{
  50138. sqlite3_free(pKey);
  50139. }
  50140. }else{
  50141. rc = SQLITE_NOMEM;
  50142. }
  50143. }
  50144. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  50145. if( rc==SQLITE_OK ){
  50146. btreeReleaseAllCursorPages(pCur);
  50147. pCur->eState = CURSOR_REQUIRESEEK;
  50148. }
  50149. invalidateOverflowCache(pCur);
  50150. return rc;
  50151. }
  50152. /*
  50153. ** Save the positions of all cursors (except pExcept) that are open on
  50154. ** the table with root-page iRoot. Usually, this is called just before cursor
  50155. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  50156. */
  50157. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  50158. BtCursor *p;
  50159. assert( sqlite3_mutex_held(pBt->mutex) );
  50160. assert( pExcept==0 || pExcept->pBt==pBt );
  50161. for(p=pBt->pCursor; p; p=p->pNext){
  50162. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  50163. if( p->eState==CURSOR_VALID ){
  50164. int rc = saveCursorPosition(p);
  50165. if( SQLITE_OK!=rc ){
  50166. return rc;
  50167. }
  50168. }else{
  50169. testcase( p->iPage>0 );
  50170. btreeReleaseAllCursorPages(p);
  50171. }
  50172. }
  50173. }
  50174. return SQLITE_OK;
  50175. }
  50176. /*
  50177. ** Clear the current cursor position.
  50178. */
  50179. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  50180. assert( cursorHoldsMutex(pCur) );
  50181. sqlite3_free(pCur->pKey);
  50182. pCur->pKey = 0;
  50183. pCur->eState = CURSOR_INVALID;
  50184. }
  50185. /*
  50186. ** In this version of BtreeMoveto, pKey is a packed index record
  50187. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  50188. ** record and then call BtreeMovetoUnpacked() to do the work.
  50189. */
  50190. static int btreeMoveto(
  50191. BtCursor *pCur, /* Cursor open on the btree to be searched */
  50192. const void *pKey, /* Packed key if the btree is an index */
  50193. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  50194. int bias, /* Bias search to the high end */
  50195. int *pRes /* Write search results here */
  50196. ){
  50197. int rc; /* Status code */
  50198. UnpackedRecord *pIdxKey; /* Unpacked index key */
  50199. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  50200. char *pFree = 0;
  50201. if( pKey ){
  50202. assert( nKey==(i64)(int)nKey );
  50203. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  50204. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  50205. );
  50206. if( pIdxKey==0 ) return SQLITE_NOMEM;
  50207. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  50208. }else{
  50209. pIdxKey = 0;
  50210. }
  50211. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  50212. if( pFree ){
  50213. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50214. }
  50215. return rc;
  50216. }
  50217. /*
  50218. ** Restore the cursor to the position it was in (or as close to as possible)
  50219. ** when saveCursorPosition() was called. Note that this call deletes the
  50220. ** saved position info stored by saveCursorPosition(), so there can be
  50221. ** at most one effective restoreCursorPosition() call after each
  50222. ** saveCursorPosition().
  50223. */
  50224. static int btreeRestoreCursorPosition(BtCursor *pCur){
  50225. int rc;
  50226. assert( cursorHoldsMutex(pCur) );
  50227. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  50228. if( pCur->eState==CURSOR_FAULT ){
  50229. return pCur->skipNext;
  50230. }
  50231. pCur->eState = CURSOR_INVALID;
  50232. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  50233. if( rc==SQLITE_OK ){
  50234. sqlite3_free(pCur->pKey);
  50235. pCur->pKey = 0;
  50236. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  50237. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  50238. pCur->eState = CURSOR_SKIPNEXT;
  50239. }
  50240. }
  50241. return rc;
  50242. }
  50243. #define restoreCursorPosition(p) \
  50244. (p->eState>=CURSOR_REQUIRESEEK ? \
  50245. btreeRestoreCursorPosition(p) : \
  50246. SQLITE_OK)
  50247. /*
  50248. ** Determine whether or not a cursor has moved from the position it
  50249. ** was last placed at. Cursors can move when the row they are pointing
  50250. ** at is deleted out from under them.
  50251. **
  50252. ** This routine returns an error code if something goes wrong. The
  50253. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  50254. */
  50255. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  50256. int rc;
  50257. rc = restoreCursorPosition(pCur);
  50258. if( rc ){
  50259. *pHasMoved = 1;
  50260. return rc;
  50261. }
  50262. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  50263. *pHasMoved = 1;
  50264. }else{
  50265. *pHasMoved = 0;
  50266. }
  50267. return SQLITE_OK;
  50268. }
  50269. #ifndef SQLITE_OMIT_AUTOVACUUM
  50270. /*
  50271. ** Given a page number of a regular database page, return the page
  50272. ** number for the pointer-map page that contains the entry for the
  50273. ** input page number.
  50274. **
  50275. ** Return 0 (not a valid page) for pgno==1 since there is
  50276. ** no pointer map associated with page 1. The integrity_check logic
  50277. ** requires that ptrmapPageno(*,1)!=1.
  50278. */
  50279. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  50280. int nPagesPerMapPage;
  50281. Pgno iPtrMap, ret;
  50282. assert( sqlite3_mutex_held(pBt->mutex) );
  50283. if( pgno<2 ) return 0;
  50284. nPagesPerMapPage = (pBt->usableSize/5)+1;
  50285. iPtrMap = (pgno-2)/nPagesPerMapPage;
  50286. ret = (iPtrMap*nPagesPerMapPage) + 2;
  50287. if( ret==PENDING_BYTE_PAGE(pBt) ){
  50288. ret++;
  50289. }
  50290. return ret;
  50291. }
  50292. /*
  50293. ** Write an entry into the pointer map.
  50294. **
  50295. ** This routine updates the pointer map entry for page number 'key'
  50296. ** so that it maps to type 'eType' and parent page number 'pgno'.
  50297. **
  50298. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  50299. ** a no-op. If an error occurs, the appropriate error code is written
  50300. ** into *pRC.
  50301. */
  50302. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  50303. DbPage *pDbPage; /* The pointer map page */
  50304. u8 *pPtrmap; /* The pointer map data */
  50305. Pgno iPtrmap; /* The pointer map page number */
  50306. int offset; /* Offset in pointer map page */
  50307. int rc; /* Return code from subfunctions */
  50308. if( *pRC ) return;
  50309. assert( sqlite3_mutex_held(pBt->mutex) );
  50310. /* The master-journal page number must never be used as a pointer map page */
  50311. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  50312. assert( pBt->autoVacuum );
  50313. if( key==0 ){
  50314. *pRC = SQLITE_CORRUPT_BKPT;
  50315. return;
  50316. }
  50317. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50318. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50319. if( rc!=SQLITE_OK ){
  50320. *pRC = rc;
  50321. return;
  50322. }
  50323. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50324. if( offset<0 ){
  50325. *pRC = SQLITE_CORRUPT_BKPT;
  50326. goto ptrmap_exit;
  50327. }
  50328. assert( offset <= (int)pBt->usableSize-5 );
  50329. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50330. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  50331. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  50332. *pRC= rc = sqlite3PagerWrite(pDbPage);
  50333. if( rc==SQLITE_OK ){
  50334. pPtrmap[offset] = eType;
  50335. put4byte(&pPtrmap[offset+1], parent);
  50336. }
  50337. }
  50338. ptrmap_exit:
  50339. sqlite3PagerUnref(pDbPage);
  50340. }
  50341. /*
  50342. ** Read an entry from the pointer map.
  50343. **
  50344. ** This routine retrieves the pointer map entry for page 'key', writing
  50345. ** the type and parent page number to *pEType and *pPgno respectively.
  50346. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  50347. */
  50348. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  50349. DbPage *pDbPage; /* The pointer map page */
  50350. int iPtrmap; /* Pointer map page index */
  50351. u8 *pPtrmap; /* Pointer map page data */
  50352. int offset; /* Offset of entry in pointer map */
  50353. int rc;
  50354. assert( sqlite3_mutex_held(pBt->mutex) );
  50355. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50356. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50357. if( rc!=0 ){
  50358. return rc;
  50359. }
  50360. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50361. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50362. if( offset<0 ){
  50363. sqlite3PagerUnref(pDbPage);
  50364. return SQLITE_CORRUPT_BKPT;
  50365. }
  50366. assert( offset <= (int)pBt->usableSize-5 );
  50367. assert( pEType!=0 );
  50368. *pEType = pPtrmap[offset];
  50369. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  50370. sqlite3PagerUnref(pDbPage);
  50371. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  50372. return SQLITE_OK;
  50373. }
  50374. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  50375. #define ptrmapPut(w,x,y,z,rc)
  50376. #define ptrmapGet(w,x,y,z) SQLITE_OK
  50377. #define ptrmapPutOvflPtr(x, y, rc)
  50378. #endif
  50379. /*
  50380. ** Given a btree page and a cell index (0 means the first cell on
  50381. ** the page, 1 means the second cell, and so forth) return a pointer
  50382. ** to the cell content.
  50383. **
  50384. ** This routine works only for pages that do not contain overflow cells.
  50385. */
  50386. #define findCell(P,I) \
  50387. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  50388. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  50389. /*
  50390. ** This a more complex version of findCell() that works for
  50391. ** pages that do contain overflow cells.
  50392. */
  50393. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  50394. int i;
  50395. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50396. for(i=pPage->nOverflow-1; i>=0; i--){
  50397. int k;
  50398. k = pPage->aiOvfl[i];
  50399. if( k<=iCell ){
  50400. if( k==iCell ){
  50401. return pPage->apOvfl[i];
  50402. }
  50403. iCell--;
  50404. }
  50405. }
  50406. return findCell(pPage, iCell);
  50407. }
  50408. /*
  50409. ** Parse a cell content block and fill in the CellInfo structure. There
  50410. ** are two versions of this function. btreeParseCell() takes a
  50411. ** cell index as the second argument and btreeParseCellPtr()
  50412. ** takes a pointer to the body of the cell as its second argument.
  50413. **
  50414. ** Within this file, the parseCell() macro can be called instead of
  50415. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  50416. */
  50417. static void btreeParseCellPtr(
  50418. MemPage *pPage, /* Page containing the cell */
  50419. u8 *pCell, /* Pointer to the cell text. */
  50420. CellInfo *pInfo /* Fill in this structure */
  50421. ){
  50422. u16 n; /* Number bytes in cell content header */
  50423. u32 nPayload; /* Number of bytes of cell payload */
  50424. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50425. pInfo->pCell = pCell;
  50426. assert( pPage->leaf==0 || pPage->leaf==1 );
  50427. n = pPage->childPtrSize;
  50428. assert( n==4-4*pPage->leaf );
  50429. if( pPage->intKey ){
  50430. if( pPage->hasData ){
  50431. assert( n==0 );
  50432. n = getVarint32(pCell, nPayload);
  50433. }else{
  50434. nPayload = 0;
  50435. }
  50436. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  50437. pInfo->nData = nPayload;
  50438. }else{
  50439. pInfo->nData = 0;
  50440. n += getVarint32(&pCell[n], nPayload);
  50441. pInfo->nKey = nPayload;
  50442. }
  50443. pInfo->nPayload = nPayload;
  50444. pInfo->nHeader = n;
  50445. testcase( nPayload==pPage->maxLocal );
  50446. testcase( nPayload==pPage->maxLocal+1 );
  50447. if( likely(nPayload<=pPage->maxLocal) ){
  50448. /* This is the (easy) common case where the entire payload fits
  50449. ** on the local page. No overflow is required.
  50450. */
  50451. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  50452. pInfo->nLocal = (u16)nPayload;
  50453. pInfo->iOverflow = 0;
  50454. }else{
  50455. /* If the payload will not fit completely on the local page, we have
  50456. ** to decide how much to store locally and how much to spill onto
  50457. ** overflow pages. The strategy is to minimize the amount of unused
  50458. ** space on overflow pages while keeping the amount of local storage
  50459. ** in between minLocal and maxLocal.
  50460. **
  50461. ** Warning: changing the way overflow payload is distributed in any
  50462. ** way will result in an incompatible file format.
  50463. */
  50464. int minLocal; /* Minimum amount of payload held locally */
  50465. int maxLocal; /* Maximum amount of payload held locally */
  50466. int surplus; /* Overflow payload available for local storage */
  50467. minLocal = pPage->minLocal;
  50468. maxLocal = pPage->maxLocal;
  50469. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  50470. testcase( surplus==maxLocal );
  50471. testcase( surplus==maxLocal+1 );
  50472. if( surplus <= maxLocal ){
  50473. pInfo->nLocal = (u16)surplus;
  50474. }else{
  50475. pInfo->nLocal = (u16)minLocal;
  50476. }
  50477. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  50478. pInfo->nSize = pInfo->iOverflow + 4;
  50479. }
  50480. }
  50481. #define parseCell(pPage, iCell, pInfo) \
  50482. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  50483. static void btreeParseCell(
  50484. MemPage *pPage, /* Page containing the cell */
  50485. int iCell, /* The cell index. First cell is 0 */
  50486. CellInfo *pInfo /* Fill in this structure */
  50487. ){
  50488. parseCell(pPage, iCell, pInfo);
  50489. }
  50490. /*
  50491. ** Compute the total number of bytes that a Cell needs in the cell
  50492. ** data area of the btree-page. The return number includes the cell
  50493. ** data header and the local payload, but not any overflow page or
  50494. ** the space used by the cell pointer.
  50495. */
  50496. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  50497. u8 *pIter = &pCell[pPage->childPtrSize];
  50498. u32 nSize;
  50499. #ifdef SQLITE_DEBUG
  50500. /* The value returned by this function should always be the same as
  50501. ** the (CellInfo.nSize) value found by doing a full parse of the
  50502. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  50503. ** this function verifies that this invariant is not violated. */
  50504. CellInfo debuginfo;
  50505. btreeParseCellPtr(pPage, pCell, &debuginfo);
  50506. #endif
  50507. if( pPage->intKey ){
  50508. u8 *pEnd;
  50509. if( pPage->hasData ){
  50510. pIter += getVarint32(pIter, nSize);
  50511. }else{
  50512. nSize = 0;
  50513. }
  50514. /* pIter now points at the 64-bit integer key value, a variable length
  50515. ** integer. The following block moves pIter to point at the first byte
  50516. ** past the end of the key value. */
  50517. pEnd = &pIter[9];
  50518. while( (*pIter++)&0x80 && pIter<pEnd );
  50519. }else{
  50520. pIter += getVarint32(pIter, nSize);
  50521. }
  50522. testcase( nSize==pPage->maxLocal );
  50523. testcase( nSize==pPage->maxLocal+1 );
  50524. if( nSize>pPage->maxLocal ){
  50525. int minLocal = pPage->minLocal;
  50526. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  50527. testcase( nSize==pPage->maxLocal );
  50528. testcase( nSize==pPage->maxLocal+1 );
  50529. if( nSize>pPage->maxLocal ){
  50530. nSize = minLocal;
  50531. }
  50532. nSize += 4;
  50533. }
  50534. nSize += (u32)(pIter - pCell);
  50535. /* The minimum size of any cell is 4 bytes. */
  50536. if( nSize<4 ){
  50537. nSize = 4;
  50538. }
  50539. assert( nSize==debuginfo.nSize );
  50540. return (u16)nSize;
  50541. }
  50542. #ifdef SQLITE_DEBUG
  50543. /* This variation on cellSizePtr() is used inside of assert() statements
  50544. ** only. */
  50545. static u16 cellSize(MemPage *pPage, int iCell){
  50546. return cellSizePtr(pPage, findCell(pPage, iCell));
  50547. }
  50548. #endif
  50549. #ifndef SQLITE_OMIT_AUTOVACUUM
  50550. /*
  50551. ** If the cell pCell, part of page pPage contains a pointer
  50552. ** to an overflow page, insert an entry into the pointer-map
  50553. ** for the overflow page.
  50554. */
  50555. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  50556. CellInfo info;
  50557. if( *pRC ) return;
  50558. assert( pCell!=0 );
  50559. btreeParseCellPtr(pPage, pCell, &info);
  50560. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  50561. if( info.iOverflow ){
  50562. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  50563. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  50564. }
  50565. }
  50566. #endif
  50567. /*
  50568. ** Defragment the page given. All Cells are moved to the
  50569. ** end of the page and all free space is collected into one
  50570. ** big FreeBlk that occurs in between the header and cell
  50571. ** pointer array and the cell content area.
  50572. */
  50573. static int defragmentPage(MemPage *pPage){
  50574. int i; /* Loop counter */
  50575. int pc; /* Address of a i-th cell */
  50576. int hdr; /* Offset to the page header */
  50577. int size; /* Size of a cell */
  50578. int usableSize; /* Number of usable bytes on a page */
  50579. int cellOffset; /* Offset to the cell pointer array */
  50580. int cbrk; /* Offset to the cell content area */
  50581. int nCell; /* Number of cells on the page */
  50582. unsigned char *data; /* The page data */
  50583. unsigned char *temp; /* Temp area for cell content */
  50584. int iCellFirst; /* First allowable cell index */
  50585. int iCellLast; /* Last possible cell index */
  50586. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50587. assert( pPage->pBt!=0 );
  50588. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  50589. assert( pPage->nOverflow==0 );
  50590. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50591. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  50592. data = pPage->aData;
  50593. hdr = pPage->hdrOffset;
  50594. cellOffset = pPage->cellOffset;
  50595. nCell = pPage->nCell;
  50596. assert( nCell==get2byte(&data[hdr+3]) );
  50597. usableSize = pPage->pBt->usableSize;
  50598. cbrk = get2byte(&data[hdr+5]);
  50599. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  50600. cbrk = usableSize;
  50601. iCellFirst = cellOffset + 2*nCell;
  50602. iCellLast = usableSize - 4;
  50603. for(i=0; i<nCell; i++){
  50604. u8 *pAddr; /* The i-th cell pointer */
  50605. pAddr = &data[cellOffset + i*2];
  50606. pc = get2byte(pAddr);
  50607. testcase( pc==iCellFirst );
  50608. testcase( pc==iCellLast );
  50609. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50610. /* These conditions have already been verified in btreeInitPage()
  50611. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  50612. */
  50613. if( pc<iCellFirst || pc>iCellLast ){
  50614. return SQLITE_CORRUPT_BKPT;
  50615. }
  50616. #endif
  50617. assert( pc>=iCellFirst && pc<=iCellLast );
  50618. size = cellSizePtr(pPage, &temp[pc]);
  50619. cbrk -= size;
  50620. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50621. if( cbrk<iCellFirst ){
  50622. return SQLITE_CORRUPT_BKPT;
  50623. }
  50624. #else
  50625. if( cbrk<iCellFirst || pc+size>usableSize ){
  50626. return SQLITE_CORRUPT_BKPT;
  50627. }
  50628. #endif
  50629. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  50630. testcase( cbrk+size==usableSize );
  50631. testcase( pc+size==usableSize );
  50632. memcpy(&data[cbrk], &temp[pc], size);
  50633. put2byte(pAddr, cbrk);
  50634. }
  50635. assert( cbrk>=iCellFirst );
  50636. put2byte(&data[hdr+5], cbrk);
  50637. data[hdr+1] = 0;
  50638. data[hdr+2] = 0;
  50639. data[hdr+7] = 0;
  50640. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  50641. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50642. if( cbrk-iCellFirst!=pPage->nFree ){
  50643. return SQLITE_CORRUPT_BKPT;
  50644. }
  50645. return SQLITE_OK;
  50646. }
  50647. /*
  50648. ** Allocate nByte bytes of space from within the B-Tree page passed
  50649. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  50650. ** of the first byte of allocated space. Return either SQLITE_OK or
  50651. ** an error code (usually SQLITE_CORRUPT).
  50652. **
  50653. ** The caller guarantees that there is sufficient space to make the
  50654. ** allocation. This routine might need to defragment in order to bring
  50655. ** all the space together, however. This routine will avoid using
  50656. ** the first two bytes past the cell pointer area since presumably this
  50657. ** allocation is being made in order to insert a new cell, so we will
  50658. ** also end up needing a new cell pointer.
  50659. */
  50660. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  50661. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  50662. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  50663. int nFrag; /* Number of fragmented bytes on pPage */
  50664. int top; /* First byte of cell content area */
  50665. int gap; /* First byte of gap between cell pointers and cell content */
  50666. int rc; /* Integer return code */
  50667. int usableSize; /* Usable size of the page */
  50668. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50669. assert( pPage->pBt );
  50670. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50671. assert( nByte>=0 ); /* Minimum cell size is 4 */
  50672. assert( pPage->nFree>=nByte );
  50673. assert( pPage->nOverflow==0 );
  50674. usableSize = pPage->pBt->usableSize;
  50675. assert( nByte < usableSize-8 );
  50676. nFrag = data[hdr+7];
  50677. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  50678. gap = pPage->cellOffset + 2*pPage->nCell;
  50679. top = get2byteNotZero(&data[hdr+5]);
  50680. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  50681. testcase( gap+2==top );
  50682. testcase( gap+1==top );
  50683. testcase( gap==top );
  50684. if( nFrag>=60 ){
  50685. /* Always defragment highly fragmented pages */
  50686. rc = defragmentPage(pPage);
  50687. if( rc ) return rc;
  50688. top = get2byteNotZero(&data[hdr+5]);
  50689. }else if( gap+2<=top ){
  50690. /* Search the freelist looking for a free slot big enough to satisfy
  50691. ** the request. The allocation is made from the first free slot in
  50692. ** the list that is large enough to accommodate it.
  50693. */
  50694. int pc, addr;
  50695. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  50696. int size; /* Size of the free slot */
  50697. if( pc>usableSize-4 || pc<addr+4 ){
  50698. return SQLITE_CORRUPT_BKPT;
  50699. }
  50700. size = get2byte(&data[pc+2]);
  50701. if( size>=nByte ){
  50702. int x = size - nByte;
  50703. testcase( x==4 );
  50704. testcase( x==3 );
  50705. if( x<4 ){
  50706. /* Remove the slot from the free-list. Update the number of
  50707. ** fragmented bytes within the page. */
  50708. memcpy(&data[addr], &data[pc], 2);
  50709. data[hdr+7] = (u8)(nFrag + x);
  50710. }else if( size+pc > usableSize ){
  50711. return SQLITE_CORRUPT_BKPT;
  50712. }else{
  50713. /* The slot remains on the free-list. Reduce its size to account
  50714. ** for the portion used by the new allocation. */
  50715. put2byte(&data[pc+2], x);
  50716. }
  50717. *pIdx = pc + x;
  50718. return SQLITE_OK;
  50719. }
  50720. }
  50721. }
  50722. /* Check to make sure there is enough space in the gap to satisfy
  50723. ** the allocation. If not, defragment.
  50724. */
  50725. testcase( gap+2+nByte==top );
  50726. if( gap+2+nByte>top ){
  50727. rc = defragmentPage(pPage);
  50728. if( rc ) return rc;
  50729. top = get2byteNotZero(&data[hdr+5]);
  50730. assert( gap+nByte<=top );
  50731. }
  50732. /* Allocate memory from the gap in between the cell pointer array
  50733. ** and the cell content area. The btreeInitPage() call has already
  50734. ** validated the freelist. Given that the freelist is valid, there
  50735. ** is no way that the allocation can extend off the end of the page.
  50736. ** The assert() below verifies the previous sentence.
  50737. */
  50738. top -= nByte;
  50739. put2byte(&data[hdr+5], top);
  50740. assert( top+nByte <= (int)pPage->pBt->usableSize );
  50741. *pIdx = top;
  50742. return SQLITE_OK;
  50743. }
  50744. /*
  50745. ** Return a section of the pPage->aData to the freelist.
  50746. ** The first byte of the new free block is pPage->aDisk[start]
  50747. ** and the size of the block is "size" bytes.
  50748. **
  50749. ** Most of the effort here is involved in coalesing adjacent
  50750. ** free blocks into a single big free block.
  50751. */
  50752. static int freeSpace(MemPage *pPage, int start, int size){
  50753. int addr, pbegin, hdr;
  50754. int iLast; /* Largest possible freeblock offset */
  50755. unsigned char *data = pPage->aData;
  50756. assert( pPage->pBt!=0 );
  50757. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50758. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  50759. assert( (start + size) <= (int)pPage->pBt->usableSize );
  50760. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50761. assert( size>=0 ); /* Minimum cell size is 4 */
  50762. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  50763. /* Overwrite deleted information with zeros when the secure_delete
  50764. ** option is enabled */
  50765. memset(&data[start], 0, size);
  50766. }
  50767. /* Add the space back into the linked list of freeblocks. Note that
  50768. ** even though the freeblock list was checked by btreeInitPage(),
  50769. ** btreeInitPage() did not detect overlapping cells or
  50770. ** freeblocks that overlapped cells. Nor does it detect when the
  50771. ** cell content area exceeds the value in the page header. If these
  50772. ** situations arise, then subsequent insert operations might corrupt
  50773. ** the freelist. So we do need to check for corruption while scanning
  50774. ** the freelist.
  50775. */
  50776. hdr = pPage->hdrOffset;
  50777. addr = hdr + 1;
  50778. iLast = pPage->pBt->usableSize - 4;
  50779. assert( start<=iLast );
  50780. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  50781. if( pbegin<addr+4 ){
  50782. return SQLITE_CORRUPT_BKPT;
  50783. }
  50784. addr = pbegin;
  50785. }
  50786. if( pbegin>iLast ){
  50787. return SQLITE_CORRUPT_BKPT;
  50788. }
  50789. assert( pbegin>addr || pbegin==0 );
  50790. put2byte(&data[addr], start);
  50791. put2byte(&data[start], pbegin);
  50792. put2byte(&data[start+2], size);
  50793. pPage->nFree = pPage->nFree + (u16)size;
  50794. /* Coalesce adjacent free blocks */
  50795. addr = hdr + 1;
  50796. while( (pbegin = get2byte(&data[addr]))>0 ){
  50797. int pnext, psize, x;
  50798. assert( pbegin>addr );
  50799. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  50800. pnext = get2byte(&data[pbegin]);
  50801. psize = get2byte(&data[pbegin+2]);
  50802. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  50803. int frag = pnext - (pbegin+psize);
  50804. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  50805. return SQLITE_CORRUPT_BKPT;
  50806. }
  50807. data[hdr+7] -= (u8)frag;
  50808. x = get2byte(&data[pnext]);
  50809. put2byte(&data[pbegin], x);
  50810. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  50811. put2byte(&data[pbegin+2], x);
  50812. }else{
  50813. addr = pbegin;
  50814. }
  50815. }
  50816. /* If the cell content area begins with a freeblock, remove it. */
  50817. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  50818. int top;
  50819. pbegin = get2byte(&data[hdr+1]);
  50820. memcpy(&data[hdr+1], &data[pbegin], 2);
  50821. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  50822. put2byte(&data[hdr+5], top);
  50823. }
  50824. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50825. return SQLITE_OK;
  50826. }
  50827. /*
  50828. ** Decode the flags byte (the first byte of the header) for a page
  50829. ** and initialize fields of the MemPage structure accordingly.
  50830. **
  50831. ** Only the following combinations are supported. Anything different
  50832. ** indicates a corrupt database files:
  50833. **
  50834. ** PTF_ZERODATA
  50835. ** PTF_ZERODATA | PTF_LEAF
  50836. ** PTF_LEAFDATA | PTF_INTKEY
  50837. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  50838. */
  50839. static int decodeFlags(MemPage *pPage, int flagByte){
  50840. BtShared *pBt; /* A copy of pPage->pBt */
  50841. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  50842. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50843. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  50844. flagByte &= ~PTF_LEAF;
  50845. pPage->childPtrSize = 4-4*pPage->leaf;
  50846. pBt = pPage->pBt;
  50847. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  50848. pPage->intKey = 1;
  50849. pPage->hasData = pPage->leaf;
  50850. pPage->maxLocal = pBt->maxLeaf;
  50851. pPage->minLocal = pBt->minLeaf;
  50852. }else if( flagByte==PTF_ZERODATA ){
  50853. pPage->intKey = 0;
  50854. pPage->hasData = 0;
  50855. pPage->maxLocal = pBt->maxLocal;
  50856. pPage->minLocal = pBt->minLocal;
  50857. }else{
  50858. return SQLITE_CORRUPT_BKPT;
  50859. }
  50860. pPage->max1bytePayload = pBt->max1bytePayload;
  50861. return SQLITE_OK;
  50862. }
  50863. /*
  50864. ** Initialize the auxiliary information for a disk block.
  50865. **
  50866. ** Return SQLITE_OK on success. If we see that the page does
  50867. ** not contain a well-formed database page, then return
  50868. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  50869. ** guarantee that the page is well-formed. It only shows that
  50870. ** we failed to detect any corruption.
  50871. */
  50872. static int btreeInitPage(MemPage *pPage){
  50873. assert( pPage->pBt!=0 );
  50874. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50875. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  50876. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  50877. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  50878. if( !pPage->isInit ){
  50879. u16 pc; /* Address of a freeblock within pPage->aData[] */
  50880. u8 hdr; /* Offset to beginning of page header */
  50881. u8 *data; /* Equal to pPage->aData */
  50882. BtShared *pBt; /* The main btree structure */
  50883. int usableSize; /* Amount of usable space on each page */
  50884. u16 cellOffset; /* Offset from start of page to first cell pointer */
  50885. int nFree; /* Number of unused bytes on the page */
  50886. int top; /* First byte of the cell content area */
  50887. int iCellFirst; /* First allowable cell or freeblock offset */
  50888. int iCellLast; /* Last possible cell or freeblock offset */
  50889. pBt = pPage->pBt;
  50890. hdr = pPage->hdrOffset;
  50891. data = pPage->aData;
  50892. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  50893. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50894. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50895. pPage->nOverflow = 0;
  50896. usableSize = pBt->usableSize;
  50897. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  50898. pPage->aDataEnd = &data[usableSize];
  50899. pPage->aCellIdx = &data[cellOffset];
  50900. top = get2byteNotZero(&data[hdr+5]);
  50901. pPage->nCell = get2byte(&data[hdr+3]);
  50902. if( pPage->nCell>MX_CELL(pBt) ){
  50903. /* To many cells for a single page. The page must be corrupt */
  50904. return SQLITE_CORRUPT_BKPT;
  50905. }
  50906. testcase( pPage->nCell==MX_CELL(pBt) );
  50907. /* A malformed database page might cause us to read past the end
  50908. ** of page when parsing a cell.
  50909. **
  50910. ** The following block of code checks early to see if a cell extends
  50911. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  50912. ** returned if it does.
  50913. */
  50914. iCellFirst = cellOffset + 2*pPage->nCell;
  50915. iCellLast = usableSize - 4;
  50916. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50917. {
  50918. int i; /* Index into the cell pointer array */
  50919. int sz; /* Size of a cell */
  50920. if( !pPage->leaf ) iCellLast--;
  50921. for(i=0; i<pPage->nCell; i++){
  50922. pc = get2byte(&data[cellOffset+i*2]);
  50923. testcase( pc==iCellFirst );
  50924. testcase( pc==iCellLast );
  50925. if( pc<iCellFirst || pc>iCellLast ){
  50926. return SQLITE_CORRUPT_BKPT;
  50927. }
  50928. sz = cellSizePtr(pPage, &data[pc]);
  50929. testcase( pc+sz==usableSize );
  50930. if( pc+sz>usableSize ){
  50931. return SQLITE_CORRUPT_BKPT;
  50932. }
  50933. }
  50934. if( !pPage->leaf ) iCellLast++;
  50935. }
  50936. #endif
  50937. /* Compute the total free space on the page */
  50938. pc = get2byte(&data[hdr+1]);
  50939. nFree = data[hdr+7] + top;
  50940. while( pc>0 ){
  50941. u16 next, size;
  50942. if( pc<iCellFirst || pc>iCellLast ){
  50943. /* Start of free block is off the page */
  50944. return SQLITE_CORRUPT_BKPT;
  50945. }
  50946. next = get2byte(&data[pc]);
  50947. size = get2byte(&data[pc+2]);
  50948. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  50949. /* Free blocks must be in ascending order. And the last byte of
  50950. ** the free-block must lie on the database page. */
  50951. return SQLITE_CORRUPT_BKPT;
  50952. }
  50953. nFree = nFree + size;
  50954. pc = next;
  50955. }
  50956. /* At this point, nFree contains the sum of the offset to the start
  50957. ** of the cell-content area plus the number of free bytes within
  50958. ** the cell-content area. If this is greater than the usable-size
  50959. ** of the page, then the page must be corrupted. This check also
  50960. ** serves to verify that the offset to the start of the cell-content
  50961. ** area, according to the page header, lies within the page.
  50962. */
  50963. if( nFree>usableSize ){
  50964. return SQLITE_CORRUPT_BKPT;
  50965. }
  50966. pPage->nFree = (u16)(nFree - iCellFirst);
  50967. pPage->isInit = 1;
  50968. }
  50969. return SQLITE_OK;
  50970. }
  50971. /*
  50972. ** Set up a raw page so that it looks like a database page holding
  50973. ** no entries.
  50974. */
  50975. static void zeroPage(MemPage *pPage, int flags){
  50976. unsigned char *data = pPage->aData;
  50977. BtShared *pBt = pPage->pBt;
  50978. u8 hdr = pPage->hdrOffset;
  50979. u16 first;
  50980. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  50981. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50982. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  50983. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50984. assert( sqlite3_mutex_held(pBt->mutex) );
  50985. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  50986. memset(&data[hdr], 0, pBt->usableSize - hdr);
  50987. }
  50988. data[hdr] = (char)flags;
  50989. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  50990. memset(&data[hdr+1], 0, 4);
  50991. data[hdr+7] = 0;
  50992. put2byte(&data[hdr+5], pBt->usableSize);
  50993. pPage->nFree = (u16)(pBt->usableSize - first);
  50994. decodeFlags(pPage, flags);
  50995. pPage->hdrOffset = hdr;
  50996. pPage->cellOffset = first;
  50997. pPage->aDataEnd = &data[pBt->usableSize];
  50998. pPage->aCellIdx = &data[first];
  50999. pPage->nOverflow = 0;
  51000. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  51001. pPage->maskPage = (u16)(pBt->pageSize - 1);
  51002. pPage->nCell = 0;
  51003. pPage->isInit = 1;
  51004. }
  51005. /*
  51006. ** Convert a DbPage obtained from the pager into a MemPage used by
  51007. ** the btree layer.
  51008. */
  51009. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  51010. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  51011. pPage->aData = sqlite3PagerGetData(pDbPage);
  51012. pPage->pDbPage = pDbPage;
  51013. pPage->pBt = pBt;
  51014. pPage->pgno = pgno;
  51015. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  51016. return pPage;
  51017. }
  51018. /*
  51019. ** Get a page from the pager. Initialize the MemPage.pBt and
  51020. ** MemPage.aData elements if needed.
  51021. **
  51022. ** If the noContent flag is set, it means that we do not care about
  51023. ** the content of the page at this time. So do not go to the disk
  51024. ** to fetch the content. Just fill in the content with zeros for now.
  51025. ** If in the future we call sqlite3PagerWrite() on this page, that
  51026. ** means we have started to be concerned about content and the disk
  51027. ** read should occur at that point.
  51028. */
  51029. static int btreeGetPage(
  51030. BtShared *pBt, /* The btree */
  51031. Pgno pgno, /* Number of the page to fetch */
  51032. MemPage **ppPage, /* Return the page in this parameter */
  51033. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  51034. ){
  51035. int rc;
  51036. DbPage *pDbPage;
  51037. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  51038. assert( sqlite3_mutex_held(pBt->mutex) );
  51039. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  51040. if( rc ) return rc;
  51041. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  51042. return SQLITE_OK;
  51043. }
  51044. /*
  51045. ** Retrieve a page from the pager cache. If the requested page is not
  51046. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  51047. ** MemPage.aData elements if needed.
  51048. */
  51049. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  51050. DbPage *pDbPage;
  51051. assert( sqlite3_mutex_held(pBt->mutex) );
  51052. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  51053. if( pDbPage ){
  51054. return btreePageFromDbPage(pDbPage, pgno, pBt);
  51055. }
  51056. return 0;
  51057. }
  51058. /*
  51059. ** Return the size of the database file in pages. If there is any kind of
  51060. ** error, return ((unsigned int)-1).
  51061. */
  51062. static Pgno btreePagecount(BtShared *pBt){
  51063. return pBt->nPage;
  51064. }
  51065. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  51066. assert( sqlite3BtreeHoldsMutex(p) );
  51067. assert( ((p->pBt->nPage)&0x8000000)==0 );
  51068. return (int)btreePagecount(p->pBt);
  51069. }
  51070. /*
  51071. ** Get a page from the pager and initialize it. This routine is just a
  51072. ** convenience wrapper around separate calls to btreeGetPage() and
  51073. ** btreeInitPage().
  51074. **
  51075. ** If an error occurs, then the value *ppPage is set to is undefined. It
  51076. ** may remain unchanged, or it may be set to an invalid value.
  51077. */
  51078. static int getAndInitPage(
  51079. BtShared *pBt, /* The database file */
  51080. Pgno pgno, /* Number of the page to get */
  51081. MemPage **ppPage, /* Write the page pointer here */
  51082. int bReadonly /* PAGER_GET_READONLY or 0 */
  51083. ){
  51084. int rc;
  51085. assert( sqlite3_mutex_held(pBt->mutex) );
  51086. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  51087. if( pgno>btreePagecount(pBt) ){
  51088. rc = SQLITE_CORRUPT_BKPT;
  51089. }else{
  51090. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  51091. if( rc==SQLITE_OK ){
  51092. rc = btreeInitPage(*ppPage);
  51093. if( rc!=SQLITE_OK ){
  51094. releasePage(*ppPage);
  51095. }
  51096. }
  51097. }
  51098. testcase( pgno==0 );
  51099. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  51100. return rc;
  51101. }
  51102. /*
  51103. ** Release a MemPage. This should be called once for each prior
  51104. ** call to btreeGetPage.
  51105. */
  51106. static void releasePage(MemPage *pPage){
  51107. if( pPage ){
  51108. assert( pPage->aData );
  51109. assert( pPage->pBt );
  51110. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  51111. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  51112. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51113. sqlite3PagerUnref(pPage->pDbPage);
  51114. }
  51115. }
  51116. /*
  51117. ** During a rollback, when the pager reloads information into the cache
  51118. ** so that the cache is restored to its original state at the start of
  51119. ** the transaction, for each page restored this routine is called.
  51120. **
  51121. ** This routine needs to reset the extra data section at the end of the
  51122. ** page to agree with the restored data.
  51123. */
  51124. static void pageReinit(DbPage *pData){
  51125. MemPage *pPage;
  51126. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  51127. assert( sqlite3PagerPageRefcount(pData)>0 );
  51128. if( pPage->isInit ){
  51129. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51130. pPage->isInit = 0;
  51131. if( sqlite3PagerPageRefcount(pData)>1 ){
  51132. /* pPage might not be a btree page; it might be an overflow page
  51133. ** or ptrmap page or a free page. In those cases, the following
  51134. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  51135. ** But no harm is done by this. And it is very important that
  51136. ** btreeInitPage() be called on every btree page so we make
  51137. ** the call for every page that comes in for re-initing. */
  51138. btreeInitPage(pPage);
  51139. }
  51140. }
  51141. }
  51142. /*
  51143. ** Invoke the busy handler for a btree.
  51144. */
  51145. static int btreeInvokeBusyHandler(void *pArg){
  51146. BtShared *pBt = (BtShared*)pArg;
  51147. assert( pBt->db );
  51148. assert( sqlite3_mutex_held(pBt->db->mutex) );
  51149. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  51150. }
  51151. /*
  51152. ** Open a database file.
  51153. **
  51154. ** zFilename is the name of the database file. If zFilename is NULL
  51155. ** then an ephemeral database is created. The ephemeral database might
  51156. ** be exclusively in memory, or it might use a disk-based memory cache.
  51157. ** Either way, the ephemeral database will be automatically deleted
  51158. ** when sqlite3BtreeClose() is called.
  51159. **
  51160. ** If zFilename is ":memory:" then an in-memory database is created
  51161. ** that is automatically destroyed when it is closed.
  51162. **
  51163. ** The "flags" parameter is a bitmask that might contain bits like
  51164. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  51165. **
  51166. ** If the database is already opened in the same database connection
  51167. ** and we are in shared cache mode, then the open will fail with an
  51168. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  51169. ** objects in the same database connection since doing so will lead
  51170. ** to problems with locking.
  51171. */
  51172. SQLITE_PRIVATE int sqlite3BtreeOpen(
  51173. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  51174. const char *zFilename, /* Name of the file containing the BTree database */
  51175. sqlite3 *db, /* Associated database handle */
  51176. Btree **ppBtree, /* Pointer to new Btree object written here */
  51177. int flags, /* Options */
  51178. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  51179. ){
  51180. BtShared *pBt = 0; /* Shared part of btree structure */
  51181. Btree *p; /* Handle to return */
  51182. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  51183. int rc = SQLITE_OK; /* Result code from this function */
  51184. u8 nReserve; /* Byte of unused space on each page */
  51185. unsigned char zDbHeader[100]; /* Database header content */
  51186. /* True if opening an ephemeral, temporary database */
  51187. const int isTempDb = zFilename==0 || zFilename[0]==0;
  51188. /* Set the variable isMemdb to true for an in-memory database, or
  51189. ** false for a file-based database.
  51190. */
  51191. #ifdef SQLITE_OMIT_MEMORYDB
  51192. const int isMemdb = 0;
  51193. #else
  51194. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  51195. || (isTempDb && sqlite3TempInMemory(db))
  51196. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  51197. #endif
  51198. assert( db!=0 );
  51199. assert( pVfs!=0 );
  51200. assert( sqlite3_mutex_held(db->mutex) );
  51201. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  51202. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  51203. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  51204. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  51205. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  51206. if( isMemdb ){
  51207. flags |= BTREE_MEMORY;
  51208. }
  51209. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  51210. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  51211. }
  51212. p = sqlite3MallocZero(sizeof(Btree));
  51213. if( !p ){
  51214. return SQLITE_NOMEM;
  51215. }
  51216. p->inTrans = TRANS_NONE;
  51217. p->db = db;
  51218. #ifndef SQLITE_OMIT_SHARED_CACHE
  51219. p->lock.pBtree = p;
  51220. p->lock.iTable = 1;
  51221. #endif
  51222. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51223. /*
  51224. ** If this Btree is a candidate for shared cache, try to find an
  51225. ** existing BtShared object that we can share with
  51226. */
  51227. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  51228. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  51229. int nFullPathname = pVfs->mxPathname+1;
  51230. char *zFullPathname = sqlite3Malloc(nFullPathname);
  51231. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51232. p->sharable = 1;
  51233. if( !zFullPathname ){
  51234. sqlite3_free(p);
  51235. return SQLITE_NOMEM;
  51236. }
  51237. if( isMemdb ){
  51238. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  51239. }else{
  51240. rc = sqlite3OsFullPathname(pVfs, zFilename,
  51241. nFullPathname, zFullPathname);
  51242. if( rc ){
  51243. sqlite3_free(zFullPathname);
  51244. sqlite3_free(p);
  51245. return rc;
  51246. }
  51247. }
  51248. #if SQLITE_THREADSAFE
  51249. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  51250. sqlite3_mutex_enter(mutexOpen);
  51251. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  51252. sqlite3_mutex_enter(mutexShared);
  51253. #endif
  51254. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  51255. assert( pBt->nRef>0 );
  51256. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  51257. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  51258. int iDb;
  51259. for(iDb=db->nDb-1; iDb>=0; iDb--){
  51260. Btree *pExisting = db->aDb[iDb].pBt;
  51261. if( pExisting && pExisting->pBt==pBt ){
  51262. sqlite3_mutex_leave(mutexShared);
  51263. sqlite3_mutex_leave(mutexOpen);
  51264. sqlite3_free(zFullPathname);
  51265. sqlite3_free(p);
  51266. return SQLITE_CONSTRAINT;
  51267. }
  51268. }
  51269. p->pBt = pBt;
  51270. pBt->nRef++;
  51271. break;
  51272. }
  51273. }
  51274. sqlite3_mutex_leave(mutexShared);
  51275. sqlite3_free(zFullPathname);
  51276. }
  51277. #ifdef SQLITE_DEBUG
  51278. else{
  51279. /* In debug mode, we mark all persistent databases as sharable
  51280. ** even when they are not. This exercises the locking code and
  51281. ** gives more opportunity for asserts(sqlite3_mutex_held())
  51282. ** statements to find locking problems.
  51283. */
  51284. p->sharable = 1;
  51285. }
  51286. #endif
  51287. }
  51288. #endif
  51289. if( pBt==0 ){
  51290. /*
  51291. ** The following asserts make sure that structures used by the btree are
  51292. ** the right size. This is to guard against size changes that result
  51293. ** when compiling on a different architecture.
  51294. */
  51295. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  51296. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  51297. assert( sizeof(u32)==4 );
  51298. assert( sizeof(u16)==2 );
  51299. assert( sizeof(Pgno)==4 );
  51300. pBt = sqlite3MallocZero( sizeof(*pBt) );
  51301. if( pBt==0 ){
  51302. rc = SQLITE_NOMEM;
  51303. goto btree_open_out;
  51304. }
  51305. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  51306. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  51307. if( rc==SQLITE_OK ){
  51308. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  51309. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  51310. }
  51311. if( rc!=SQLITE_OK ){
  51312. goto btree_open_out;
  51313. }
  51314. pBt->openFlags = (u8)flags;
  51315. pBt->db = db;
  51316. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  51317. p->pBt = pBt;
  51318. pBt->pCursor = 0;
  51319. pBt->pPage1 = 0;
  51320. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  51321. #ifdef SQLITE_SECURE_DELETE
  51322. pBt->btsFlags |= BTS_SECURE_DELETE;
  51323. #endif
  51324. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  51325. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  51326. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  51327. pBt->pageSize = 0;
  51328. #ifndef SQLITE_OMIT_AUTOVACUUM
  51329. /* If the magic name ":memory:" will create an in-memory database, then
  51330. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  51331. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  51332. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  51333. ** regular file-name. In this case the auto-vacuum applies as per normal.
  51334. */
  51335. if( zFilename && !isMemdb ){
  51336. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  51337. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  51338. }
  51339. #endif
  51340. nReserve = 0;
  51341. }else{
  51342. nReserve = zDbHeader[20];
  51343. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51344. #ifndef SQLITE_OMIT_AUTOVACUUM
  51345. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  51346. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  51347. #endif
  51348. }
  51349. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51350. if( rc ) goto btree_open_out;
  51351. pBt->usableSize = pBt->pageSize - nReserve;
  51352. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  51353. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51354. /* Add the new BtShared object to the linked list sharable BtShareds.
  51355. */
  51356. if( p->sharable ){
  51357. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51358. pBt->nRef = 1;
  51359. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  51360. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  51361. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  51362. if( pBt->mutex==0 ){
  51363. rc = SQLITE_NOMEM;
  51364. db->mallocFailed = 0;
  51365. goto btree_open_out;
  51366. }
  51367. }
  51368. sqlite3_mutex_enter(mutexShared);
  51369. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51370. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  51371. sqlite3_mutex_leave(mutexShared);
  51372. }
  51373. #endif
  51374. }
  51375. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51376. /* If the new Btree uses a sharable pBtShared, then link the new
  51377. ** Btree into the list of all sharable Btrees for the same connection.
  51378. ** The list is kept in ascending order by pBt address.
  51379. */
  51380. if( p->sharable ){
  51381. int i;
  51382. Btree *pSib;
  51383. for(i=0; i<db->nDb; i++){
  51384. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  51385. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  51386. if( p->pBt<pSib->pBt ){
  51387. p->pNext = pSib;
  51388. p->pPrev = 0;
  51389. pSib->pPrev = p;
  51390. }else{
  51391. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  51392. pSib = pSib->pNext;
  51393. }
  51394. p->pNext = pSib->pNext;
  51395. p->pPrev = pSib;
  51396. if( p->pNext ){
  51397. p->pNext->pPrev = p;
  51398. }
  51399. pSib->pNext = p;
  51400. }
  51401. break;
  51402. }
  51403. }
  51404. }
  51405. #endif
  51406. *ppBtree = p;
  51407. btree_open_out:
  51408. if( rc!=SQLITE_OK ){
  51409. if( pBt && pBt->pPager ){
  51410. sqlite3PagerClose(pBt->pPager);
  51411. }
  51412. sqlite3_free(pBt);
  51413. sqlite3_free(p);
  51414. *ppBtree = 0;
  51415. }else{
  51416. /* If the B-Tree was successfully opened, set the pager-cache size to the
  51417. ** default value. Except, when opening on an existing shared pager-cache,
  51418. ** do not change the pager-cache size.
  51419. */
  51420. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  51421. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  51422. }
  51423. }
  51424. if( mutexOpen ){
  51425. assert( sqlite3_mutex_held(mutexOpen) );
  51426. sqlite3_mutex_leave(mutexOpen);
  51427. }
  51428. return rc;
  51429. }
  51430. /*
  51431. ** Decrement the BtShared.nRef counter. When it reaches zero,
  51432. ** remove the BtShared structure from the sharing list. Return
  51433. ** true if the BtShared.nRef counter reaches zero and return
  51434. ** false if it is still positive.
  51435. */
  51436. static int removeFromSharingList(BtShared *pBt){
  51437. #ifndef SQLITE_OMIT_SHARED_CACHE
  51438. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  51439. BtShared *pList;
  51440. int removed = 0;
  51441. assert( sqlite3_mutex_notheld(pBt->mutex) );
  51442. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  51443. sqlite3_mutex_enter(pMaster);
  51444. pBt->nRef--;
  51445. if( pBt->nRef<=0 ){
  51446. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  51447. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  51448. }else{
  51449. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51450. while( ALWAYS(pList) && pList->pNext!=pBt ){
  51451. pList=pList->pNext;
  51452. }
  51453. if( ALWAYS(pList) ){
  51454. pList->pNext = pBt->pNext;
  51455. }
  51456. }
  51457. if( SQLITE_THREADSAFE ){
  51458. sqlite3_mutex_free(pBt->mutex);
  51459. }
  51460. removed = 1;
  51461. }
  51462. sqlite3_mutex_leave(pMaster);
  51463. return removed;
  51464. #else
  51465. return 1;
  51466. #endif
  51467. }
  51468. /*
  51469. ** Make sure pBt->pTmpSpace points to an allocation of
  51470. ** MX_CELL_SIZE(pBt) bytes.
  51471. */
  51472. static void allocateTempSpace(BtShared *pBt){
  51473. if( !pBt->pTmpSpace ){
  51474. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  51475. /* One of the uses of pBt->pTmpSpace is to format cells before
  51476. ** inserting them into a leaf page (function fillInCell()). If
  51477. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  51478. ** by the various routines that manipulate binary cells. Which
  51479. ** can mean that fillInCell() only initializes the first 2 or 3
  51480. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  51481. ** it into a database page. This is not actually a problem, but it
  51482. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  51483. ** data is passed to system call write(). So to avoid this error,
  51484. ** zero the first 4 bytes of temp space here. */
  51485. if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
  51486. }
  51487. }
  51488. /*
  51489. ** Free the pBt->pTmpSpace allocation
  51490. */
  51491. static void freeTempSpace(BtShared *pBt){
  51492. sqlite3PageFree( pBt->pTmpSpace);
  51493. pBt->pTmpSpace = 0;
  51494. }
  51495. /*
  51496. ** Close an open database and invalidate all cursors.
  51497. */
  51498. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  51499. BtShared *pBt = p->pBt;
  51500. BtCursor *pCur;
  51501. /* Close all cursors opened via this handle. */
  51502. assert( sqlite3_mutex_held(p->db->mutex) );
  51503. sqlite3BtreeEnter(p);
  51504. pCur = pBt->pCursor;
  51505. while( pCur ){
  51506. BtCursor *pTmp = pCur;
  51507. pCur = pCur->pNext;
  51508. if( pTmp->pBtree==p ){
  51509. sqlite3BtreeCloseCursor(pTmp);
  51510. }
  51511. }
  51512. /* Rollback any active transaction and free the handle structure.
  51513. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  51514. ** this handle.
  51515. */
  51516. sqlite3BtreeRollback(p, SQLITE_OK);
  51517. sqlite3BtreeLeave(p);
  51518. /* If there are still other outstanding references to the shared-btree
  51519. ** structure, return now. The remainder of this procedure cleans
  51520. ** up the shared-btree.
  51521. */
  51522. assert( p->wantToLock==0 && p->locked==0 );
  51523. if( !p->sharable || removeFromSharingList(pBt) ){
  51524. /* The pBt is no longer on the sharing list, so we can access
  51525. ** it without having to hold the mutex.
  51526. **
  51527. ** Clean out and delete the BtShared object.
  51528. */
  51529. assert( !pBt->pCursor );
  51530. sqlite3PagerClose(pBt->pPager);
  51531. if( pBt->xFreeSchema && pBt->pSchema ){
  51532. pBt->xFreeSchema(pBt->pSchema);
  51533. }
  51534. sqlite3DbFree(0, pBt->pSchema);
  51535. freeTempSpace(pBt);
  51536. sqlite3_free(pBt);
  51537. }
  51538. #ifndef SQLITE_OMIT_SHARED_CACHE
  51539. assert( p->wantToLock==0 );
  51540. assert( p->locked==0 );
  51541. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  51542. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  51543. #endif
  51544. sqlite3_free(p);
  51545. return SQLITE_OK;
  51546. }
  51547. /*
  51548. ** Change the limit on the number of pages allowed in the cache.
  51549. **
  51550. ** The maximum number of cache pages is set to the absolute
  51551. ** value of mxPage. If mxPage is negative, the pager will
  51552. ** operate asynchronously - it will not stop to do fsync()s
  51553. ** to insure data is written to the disk surface before
  51554. ** continuing. Transactions still work if synchronous is off,
  51555. ** and the database cannot be corrupted if this program
  51556. ** crashes. But if the operating system crashes or there is
  51557. ** an abrupt power failure when synchronous is off, the database
  51558. ** could be left in an inconsistent and unrecoverable state.
  51559. ** Synchronous is on by default so database corruption is not
  51560. ** normally a worry.
  51561. */
  51562. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  51563. BtShared *pBt = p->pBt;
  51564. assert( sqlite3_mutex_held(p->db->mutex) );
  51565. sqlite3BtreeEnter(p);
  51566. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  51567. sqlite3BtreeLeave(p);
  51568. return SQLITE_OK;
  51569. }
  51570. /*
  51571. ** Change the limit on the amount of the database file that may be
  51572. ** memory mapped.
  51573. */
  51574. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  51575. BtShared *pBt = p->pBt;
  51576. assert( sqlite3_mutex_held(p->db->mutex) );
  51577. sqlite3BtreeEnter(p);
  51578. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  51579. sqlite3BtreeLeave(p);
  51580. return SQLITE_OK;
  51581. }
  51582. /*
  51583. ** Change the way data is synced to disk in order to increase or decrease
  51584. ** how well the database resists damage due to OS crashes and power
  51585. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  51586. ** there is a high probability of damage) Level 2 is the default. There
  51587. ** is a very low but non-zero probability of damage. Level 3 reduces the
  51588. ** probability of damage to near zero but with a write performance reduction.
  51589. */
  51590. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  51591. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  51592. Btree *p, /* The btree to set the safety level on */
  51593. unsigned pgFlags /* Various PAGER_* flags */
  51594. ){
  51595. BtShared *pBt = p->pBt;
  51596. assert( sqlite3_mutex_held(p->db->mutex) );
  51597. sqlite3BtreeEnter(p);
  51598. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  51599. sqlite3BtreeLeave(p);
  51600. return SQLITE_OK;
  51601. }
  51602. #endif
  51603. /*
  51604. ** Return TRUE if the given btree is set to safety level 1. In other
  51605. ** words, return TRUE if no sync() occurs on the disk files.
  51606. */
  51607. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  51608. BtShared *pBt = p->pBt;
  51609. int rc;
  51610. assert( sqlite3_mutex_held(p->db->mutex) );
  51611. sqlite3BtreeEnter(p);
  51612. assert( pBt && pBt->pPager );
  51613. rc = sqlite3PagerNosync(pBt->pPager);
  51614. sqlite3BtreeLeave(p);
  51615. return rc;
  51616. }
  51617. /*
  51618. ** Change the default pages size and the number of reserved bytes per page.
  51619. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  51620. ** without changing anything.
  51621. **
  51622. ** The page size must be a power of 2 between 512 and 65536. If the page
  51623. ** size supplied does not meet this constraint then the page size is not
  51624. ** changed.
  51625. **
  51626. ** Page sizes are constrained to be a power of two so that the region
  51627. ** of the database file used for locking (beginning at PENDING_BYTE,
  51628. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  51629. ** at the beginning of a page.
  51630. **
  51631. ** If parameter nReserve is less than zero, then the number of reserved
  51632. ** bytes per page is left unchanged.
  51633. **
  51634. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  51635. ** and autovacuum mode can no longer be changed.
  51636. */
  51637. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  51638. int rc = SQLITE_OK;
  51639. BtShared *pBt = p->pBt;
  51640. assert( nReserve>=-1 && nReserve<=255 );
  51641. sqlite3BtreeEnter(p);
  51642. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  51643. sqlite3BtreeLeave(p);
  51644. return SQLITE_READONLY;
  51645. }
  51646. if( nReserve<0 ){
  51647. nReserve = pBt->pageSize - pBt->usableSize;
  51648. }
  51649. assert( nReserve>=0 && nReserve<=255 );
  51650. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  51651. ((pageSize-1)&pageSize)==0 ){
  51652. assert( (pageSize & 7)==0 );
  51653. assert( !pBt->pPage1 && !pBt->pCursor );
  51654. pBt->pageSize = (u32)pageSize;
  51655. freeTempSpace(pBt);
  51656. }
  51657. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51658. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  51659. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51660. sqlite3BtreeLeave(p);
  51661. return rc;
  51662. }
  51663. /*
  51664. ** Return the currently defined page size
  51665. */
  51666. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  51667. return p->pBt->pageSize;
  51668. }
  51669. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  51670. /*
  51671. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  51672. ** may only be called if it is guaranteed that the b-tree mutex is already
  51673. ** held.
  51674. **
  51675. ** This is useful in one special case in the backup API code where it is
  51676. ** known that the shared b-tree mutex is held, but the mutex on the
  51677. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  51678. ** were to be called, it might collide with some other operation on the
  51679. ** database handle that owns *p, causing undefined behavior.
  51680. */
  51681. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  51682. assert( sqlite3_mutex_held(p->pBt->mutex) );
  51683. return p->pBt->pageSize - p->pBt->usableSize;
  51684. }
  51685. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  51686. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  51687. /*
  51688. ** Return the number of bytes of space at the end of every page that
  51689. ** are intentually left unused. This is the "reserved" space that is
  51690. ** sometimes used by extensions.
  51691. */
  51692. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  51693. int n;
  51694. sqlite3BtreeEnter(p);
  51695. n = p->pBt->pageSize - p->pBt->usableSize;
  51696. sqlite3BtreeLeave(p);
  51697. return n;
  51698. }
  51699. /*
  51700. ** Set the maximum page count for a database if mxPage is positive.
  51701. ** No changes are made if mxPage is 0 or negative.
  51702. ** Regardless of the value of mxPage, return the maximum page count.
  51703. */
  51704. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  51705. int n;
  51706. sqlite3BtreeEnter(p);
  51707. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  51708. sqlite3BtreeLeave(p);
  51709. return n;
  51710. }
  51711. /*
  51712. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  51713. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  51714. ** setting after the change.
  51715. */
  51716. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  51717. int b;
  51718. if( p==0 ) return 0;
  51719. sqlite3BtreeEnter(p);
  51720. if( newFlag>=0 ){
  51721. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  51722. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  51723. }
  51724. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  51725. sqlite3BtreeLeave(p);
  51726. return b;
  51727. }
  51728. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  51729. /*
  51730. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  51731. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  51732. ** is disabled. The default value for the auto-vacuum property is
  51733. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  51734. */
  51735. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  51736. #ifdef SQLITE_OMIT_AUTOVACUUM
  51737. return SQLITE_READONLY;
  51738. #else
  51739. BtShared *pBt = p->pBt;
  51740. int rc = SQLITE_OK;
  51741. u8 av = (u8)autoVacuum;
  51742. sqlite3BtreeEnter(p);
  51743. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  51744. rc = SQLITE_READONLY;
  51745. }else{
  51746. pBt->autoVacuum = av ?1:0;
  51747. pBt->incrVacuum = av==2 ?1:0;
  51748. }
  51749. sqlite3BtreeLeave(p);
  51750. return rc;
  51751. #endif
  51752. }
  51753. /*
  51754. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  51755. ** enabled 1 is returned. Otherwise 0.
  51756. */
  51757. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  51758. #ifdef SQLITE_OMIT_AUTOVACUUM
  51759. return BTREE_AUTOVACUUM_NONE;
  51760. #else
  51761. int rc;
  51762. sqlite3BtreeEnter(p);
  51763. rc = (
  51764. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  51765. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  51766. BTREE_AUTOVACUUM_INCR
  51767. );
  51768. sqlite3BtreeLeave(p);
  51769. return rc;
  51770. #endif
  51771. }
  51772. /*
  51773. ** Get a reference to pPage1 of the database file. This will
  51774. ** also acquire a readlock on that file.
  51775. **
  51776. ** SQLITE_OK is returned on success. If the file is not a
  51777. ** well-formed database file, then SQLITE_CORRUPT is returned.
  51778. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  51779. ** is returned if we run out of memory.
  51780. */
  51781. static int lockBtree(BtShared *pBt){
  51782. int rc; /* Result code from subfunctions */
  51783. MemPage *pPage1; /* Page 1 of the database file */
  51784. int nPage; /* Number of pages in the database */
  51785. int nPageFile = 0; /* Number of pages in the database file */
  51786. int nPageHeader; /* Number of pages in the database according to hdr */
  51787. assert( sqlite3_mutex_held(pBt->mutex) );
  51788. assert( pBt->pPage1==0 );
  51789. rc = sqlite3PagerSharedLock(pBt->pPager);
  51790. if( rc!=SQLITE_OK ) return rc;
  51791. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  51792. if( rc!=SQLITE_OK ) return rc;
  51793. /* Do some checking to help insure the file we opened really is
  51794. ** a valid database file.
  51795. */
  51796. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  51797. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  51798. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  51799. nPage = nPageFile;
  51800. }
  51801. if( nPage>0 ){
  51802. u32 pageSize;
  51803. u32 usableSize;
  51804. u8 *page1 = pPage1->aData;
  51805. rc = SQLITE_NOTADB;
  51806. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  51807. goto page1_init_failed;
  51808. }
  51809. #ifdef SQLITE_OMIT_WAL
  51810. if( page1[18]>1 ){
  51811. pBt->btsFlags |= BTS_READ_ONLY;
  51812. }
  51813. if( page1[19]>1 ){
  51814. goto page1_init_failed;
  51815. }
  51816. #else
  51817. if( page1[18]>2 ){
  51818. pBt->btsFlags |= BTS_READ_ONLY;
  51819. }
  51820. if( page1[19]>2 ){
  51821. goto page1_init_failed;
  51822. }
  51823. /* If the write version is set to 2, this database should be accessed
  51824. ** in WAL mode. If the log is not already open, open it now. Then
  51825. ** return SQLITE_OK and return without populating BtShared.pPage1.
  51826. ** The caller detects this and calls this function again. This is
  51827. ** required as the version of page 1 currently in the page1 buffer
  51828. ** may not be the latest version - there may be a newer one in the log
  51829. ** file.
  51830. */
  51831. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  51832. int isOpen = 0;
  51833. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  51834. if( rc!=SQLITE_OK ){
  51835. goto page1_init_failed;
  51836. }else if( isOpen==0 ){
  51837. releasePage(pPage1);
  51838. return SQLITE_OK;
  51839. }
  51840. rc = SQLITE_NOTADB;
  51841. }
  51842. #endif
  51843. /* The maximum embedded fraction must be exactly 25%. And the minimum
  51844. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  51845. ** The original design allowed these amounts to vary, but as of
  51846. ** version 3.6.0, we require them to be fixed.
  51847. */
  51848. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  51849. goto page1_init_failed;
  51850. }
  51851. pageSize = (page1[16]<<8) | (page1[17]<<16);
  51852. if( ((pageSize-1)&pageSize)!=0
  51853. || pageSize>SQLITE_MAX_PAGE_SIZE
  51854. || pageSize<=256
  51855. ){
  51856. goto page1_init_failed;
  51857. }
  51858. assert( (pageSize & 7)==0 );
  51859. usableSize = pageSize - page1[20];
  51860. if( (u32)pageSize!=pBt->pageSize ){
  51861. /* After reading the first page of the database assuming a page size
  51862. ** of BtShared.pageSize, we have discovered that the page-size is
  51863. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  51864. ** zero and return SQLITE_OK. The caller will call this function
  51865. ** again with the correct page-size.
  51866. */
  51867. releasePage(pPage1);
  51868. pBt->usableSize = usableSize;
  51869. pBt->pageSize = pageSize;
  51870. freeTempSpace(pBt);
  51871. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  51872. pageSize-usableSize);
  51873. return rc;
  51874. }
  51875. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  51876. rc = SQLITE_CORRUPT_BKPT;
  51877. goto page1_init_failed;
  51878. }
  51879. if( usableSize<480 ){
  51880. goto page1_init_failed;
  51881. }
  51882. pBt->pageSize = pageSize;
  51883. pBt->usableSize = usableSize;
  51884. #ifndef SQLITE_OMIT_AUTOVACUUM
  51885. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  51886. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  51887. #endif
  51888. }
  51889. /* maxLocal is the maximum amount of payload to store locally for
  51890. ** a cell. Make sure it is small enough so that at least minFanout
  51891. ** cells can will fit on one page. We assume a 10-byte page header.
  51892. ** Besides the payload, the cell must store:
  51893. ** 2-byte pointer to the cell
  51894. ** 4-byte child pointer
  51895. ** 9-byte nKey value
  51896. ** 4-byte nData value
  51897. ** 4-byte overflow page pointer
  51898. ** So a cell consists of a 2-byte pointer, a header which is as much as
  51899. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  51900. ** page pointer.
  51901. */
  51902. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  51903. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  51904. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  51905. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  51906. if( pBt->maxLocal>127 ){
  51907. pBt->max1bytePayload = 127;
  51908. }else{
  51909. pBt->max1bytePayload = (u8)pBt->maxLocal;
  51910. }
  51911. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  51912. pBt->pPage1 = pPage1;
  51913. pBt->nPage = nPage;
  51914. return SQLITE_OK;
  51915. page1_init_failed:
  51916. releasePage(pPage1);
  51917. pBt->pPage1 = 0;
  51918. return rc;
  51919. }
  51920. #ifndef NDEBUG
  51921. /*
  51922. ** Return the number of cursors open on pBt. This is for use
  51923. ** in assert() expressions, so it is only compiled if NDEBUG is not
  51924. ** defined.
  51925. **
  51926. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  51927. ** false then all cursors are counted.
  51928. **
  51929. ** For the purposes of this routine, a cursor is any cursor that
  51930. ** is capable of reading or writing to the databse. Cursors that
  51931. ** have been tripped into the CURSOR_FAULT state are not counted.
  51932. */
  51933. static int countValidCursors(BtShared *pBt, int wrOnly){
  51934. BtCursor *pCur;
  51935. int r = 0;
  51936. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  51937. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  51938. }
  51939. return r;
  51940. }
  51941. #endif
  51942. /*
  51943. ** If there are no outstanding cursors and we are not in the middle
  51944. ** of a transaction but there is a read lock on the database, then
  51945. ** this routine unrefs the first page of the database file which
  51946. ** has the effect of releasing the read lock.
  51947. **
  51948. ** If there is a transaction in progress, this routine is a no-op.
  51949. */
  51950. static void unlockBtreeIfUnused(BtShared *pBt){
  51951. assert( sqlite3_mutex_held(pBt->mutex) );
  51952. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  51953. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  51954. assert( pBt->pPage1->aData );
  51955. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  51956. assert( pBt->pPage1->aData );
  51957. releasePage(pBt->pPage1);
  51958. pBt->pPage1 = 0;
  51959. }
  51960. }
  51961. /*
  51962. ** If pBt points to an empty file then convert that empty file
  51963. ** into a new empty database by initializing the first page of
  51964. ** the database.
  51965. */
  51966. static int newDatabase(BtShared *pBt){
  51967. MemPage *pP1;
  51968. unsigned char *data;
  51969. int rc;
  51970. assert( sqlite3_mutex_held(pBt->mutex) );
  51971. if( pBt->nPage>0 ){
  51972. return SQLITE_OK;
  51973. }
  51974. pP1 = pBt->pPage1;
  51975. assert( pP1!=0 );
  51976. data = pP1->aData;
  51977. rc = sqlite3PagerWrite(pP1->pDbPage);
  51978. if( rc ) return rc;
  51979. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  51980. assert( sizeof(zMagicHeader)==16 );
  51981. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  51982. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  51983. data[18] = 1;
  51984. data[19] = 1;
  51985. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  51986. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  51987. data[21] = 64;
  51988. data[22] = 32;
  51989. data[23] = 32;
  51990. memset(&data[24], 0, 100-24);
  51991. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  51992. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51993. #ifndef SQLITE_OMIT_AUTOVACUUM
  51994. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  51995. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  51996. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  51997. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  51998. #endif
  51999. pBt->nPage = 1;
  52000. data[31] = 1;
  52001. return SQLITE_OK;
  52002. }
  52003. /*
  52004. ** Initialize the first page of the database file (creating a database
  52005. ** consisting of a single page and no schema objects). Return SQLITE_OK
  52006. ** if successful, or an SQLite error code otherwise.
  52007. */
  52008. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  52009. int rc;
  52010. sqlite3BtreeEnter(p);
  52011. p->pBt->nPage = 0;
  52012. rc = newDatabase(p->pBt);
  52013. sqlite3BtreeLeave(p);
  52014. return rc;
  52015. }
  52016. /*
  52017. ** Attempt to start a new transaction. A write-transaction
  52018. ** is started if the second argument is nonzero, otherwise a read-
  52019. ** transaction. If the second argument is 2 or more and exclusive
  52020. ** transaction is started, meaning that no other process is allowed
  52021. ** to access the database. A preexisting transaction may not be
  52022. ** upgraded to exclusive by calling this routine a second time - the
  52023. ** exclusivity flag only works for a new transaction.
  52024. **
  52025. ** A write-transaction must be started before attempting any
  52026. ** changes to the database. None of the following routines
  52027. ** will work unless a transaction is started first:
  52028. **
  52029. ** sqlite3BtreeCreateTable()
  52030. ** sqlite3BtreeCreateIndex()
  52031. ** sqlite3BtreeClearTable()
  52032. ** sqlite3BtreeDropTable()
  52033. ** sqlite3BtreeInsert()
  52034. ** sqlite3BtreeDelete()
  52035. ** sqlite3BtreeUpdateMeta()
  52036. **
  52037. ** If an initial attempt to acquire the lock fails because of lock contention
  52038. ** and the database was previously unlocked, then invoke the busy handler
  52039. ** if there is one. But if there was previously a read-lock, do not
  52040. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  52041. ** returned when there is already a read-lock in order to avoid a deadlock.
  52042. **
  52043. ** Suppose there are two processes A and B. A has a read lock and B has
  52044. ** a reserved lock. B tries to promote to exclusive but is blocked because
  52045. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  52046. ** One or the other of the two processes must give way or there can be
  52047. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  52048. ** when A already has a read lock, we encourage A to give up and let B
  52049. ** proceed.
  52050. */
  52051. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  52052. sqlite3 *pBlock = 0;
  52053. BtShared *pBt = p->pBt;
  52054. int rc = SQLITE_OK;
  52055. sqlite3BtreeEnter(p);
  52056. btreeIntegrity(p);
  52057. /* If the btree is already in a write-transaction, or it
  52058. ** is already in a read-transaction and a read-transaction
  52059. ** is requested, this is a no-op.
  52060. */
  52061. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  52062. goto trans_begun;
  52063. }
  52064. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  52065. /* Write transactions are not possible on a read-only database */
  52066. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  52067. rc = SQLITE_READONLY;
  52068. goto trans_begun;
  52069. }
  52070. #ifndef SQLITE_OMIT_SHARED_CACHE
  52071. /* If another database handle has already opened a write transaction
  52072. ** on this shared-btree structure and a second write transaction is
  52073. ** requested, return SQLITE_LOCKED.
  52074. */
  52075. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  52076. || (pBt->btsFlags & BTS_PENDING)!=0
  52077. ){
  52078. pBlock = pBt->pWriter->db;
  52079. }else if( wrflag>1 ){
  52080. BtLock *pIter;
  52081. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  52082. if( pIter->pBtree!=p ){
  52083. pBlock = pIter->pBtree->db;
  52084. break;
  52085. }
  52086. }
  52087. }
  52088. if( pBlock ){
  52089. sqlite3ConnectionBlocked(p->db, pBlock);
  52090. rc = SQLITE_LOCKED_SHAREDCACHE;
  52091. goto trans_begun;
  52092. }
  52093. #endif
  52094. /* Any read-only or read-write transaction implies a read-lock on
  52095. ** page 1. So if some other shared-cache client already has a write-lock
  52096. ** on page 1, the transaction cannot be opened. */
  52097. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  52098. if( SQLITE_OK!=rc ) goto trans_begun;
  52099. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  52100. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  52101. do {
  52102. /* Call lockBtree() until either pBt->pPage1 is populated or
  52103. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  52104. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  52105. ** reading page 1 it discovers that the page-size of the database
  52106. ** file is not pBt->pageSize. In this case lockBtree() will update
  52107. ** pBt->pageSize to the page-size of the file on disk.
  52108. */
  52109. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  52110. if( rc==SQLITE_OK && wrflag ){
  52111. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  52112. rc = SQLITE_READONLY;
  52113. }else{
  52114. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  52115. if( rc==SQLITE_OK ){
  52116. rc = newDatabase(pBt);
  52117. }
  52118. }
  52119. }
  52120. if( rc!=SQLITE_OK ){
  52121. unlockBtreeIfUnused(pBt);
  52122. }
  52123. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  52124. btreeInvokeBusyHandler(pBt) );
  52125. if( rc==SQLITE_OK ){
  52126. if( p->inTrans==TRANS_NONE ){
  52127. pBt->nTransaction++;
  52128. #ifndef SQLITE_OMIT_SHARED_CACHE
  52129. if( p->sharable ){
  52130. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  52131. p->lock.eLock = READ_LOCK;
  52132. p->lock.pNext = pBt->pLock;
  52133. pBt->pLock = &p->lock;
  52134. }
  52135. #endif
  52136. }
  52137. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  52138. if( p->inTrans>pBt->inTransaction ){
  52139. pBt->inTransaction = p->inTrans;
  52140. }
  52141. if( wrflag ){
  52142. MemPage *pPage1 = pBt->pPage1;
  52143. #ifndef SQLITE_OMIT_SHARED_CACHE
  52144. assert( !pBt->pWriter );
  52145. pBt->pWriter = p;
  52146. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  52147. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  52148. #endif
  52149. /* If the db-size header field is incorrect (as it may be if an old
  52150. ** client has been writing the database file), update it now. Doing
  52151. ** this sooner rather than later means the database size can safely
  52152. ** re-read the database size from page 1 if a savepoint or transaction
  52153. ** rollback occurs within the transaction.
  52154. */
  52155. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  52156. rc = sqlite3PagerWrite(pPage1->pDbPage);
  52157. if( rc==SQLITE_OK ){
  52158. put4byte(&pPage1->aData[28], pBt->nPage);
  52159. }
  52160. }
  52161. }
  52162. }
  52163. trans_begun:
  52164. if( rc==SQLITE_OK && wrflag ){
  52165. /* This call makes sure that the pager has the correct number of
  52166. ** open savepoints. If the second parameter is greater than 0 and
  52167. ** the sub-journal is not already open, then it will be opened here.
  52168. */
  52169. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  52170. }
  52171. btreeIntegrity(p);
  52172. sqlite3BtreeLeave(p);
  52173. return rc;
  52174. }
  52175. #ifndef SQLITE_OMIT_AUTOVACUUM
  52176. /*
  52177. ** Set the pointer-map entries for all children of page pPage. Also, if
  52178. ** pPage contains cells that point to overflow pages, set the pointer
  52179. ** map entries for the overflow pages as well.
  52180. */
  52181. static int setChildPtrmaps(MemPage *pPage){
  52182. int i; /* Counter variable */
  52183. int nCell; /* Number of cells in page pPage */
  52184. int rc; /* Return code */
  52185. BtShared *pBt = pPage->pBt;
  52186. u8 isInitOrig = pPage->isInit;
  52187. Pgno pgno = pPage->pgno;
  52188. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52189. rc = btreeInitPage(pPage);
  52190. if( rc!=SQLITE_OK ){
  52191. goto set_child_ptrmaps_out;
  52192. }
  52193. nCell = pPage->nCell;
  52194. for(i=0; i<nCell; i++){
  52195. u8 *pCell = findCell(pPage, i);
  52196. ptrmapPutOvflPtr(pPage, pCell, &rc);
  52197. if( !pPage->leaf ){
  52198. Pgno childPgno = get4byte(pCell);
  52199. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52200. }
  52201. }
  52202. if( !pPage->leaf ){
  52203. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52204. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52205. }
  52206. set_child_ptrmaps_out:
  52207. pPage->isInit = isInitOrig;
  52208. return rc;
  52209. }
  52210. /*
  52211. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  52212. ** that it points to iTo. Parameter eType describes the type of pointer to
  52213. ** be modified, as follows:
  52214. **
  52215. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  52216. ** page of pPage.
  52217. **
  52218. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  52219. ** page pointed to by one of the cells on pPage.
  52220. **
  52221. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  52222. ** overflow page in the list.
  52223. */
  52224. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  52225. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52226. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52227. if( eType==PTRMAP_OVERFLOW2 ){
  52228. /* The pointer is always the first 4 bytes of the page in this case. */
  52229. if( get4byte(pPage->aData)!=iFrom ){
  52230. return SQLITE_CORRUPT_BKPT;
  52231. }
  52232. put4byte(pPage->aData, iTo);
  52233. }else{
  52234. u8 isInitOrig = pPage->isInit;
  52235. int i;
  52236. int nCell;
  52237. btreeInitPage(pPage);
  52238. nCell = pPage->nCell;
  52239. for(i=0; i<nCell; i++){
  52240. u8 *pCell = findCell(pPage, i);
  52241. if( eType==PTRMAP_OVERFLOW1 ){
  52242. CellInfo info;
  52243. btreeParseCellPtr(pPage, pCell, &info);
  52244. if( info.iOverflow
  52245. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  52246. && iFrom==get4byte(&pCell[info.iOverflow])
  52247. ){
  52248. put4byte(&pCell[info.iOverflow], iTo);
  52249. break;
  52250. }
  52251. }else{
  52252. if( get4byte(pCell)==iFrom ){
  52253. put4byte(pCell, iTo);
  52254. break;
  52255. }
  52256. }
  52257. }
  52258. if( i==nCell ){
  52259. if( eType!=PTRMAP_BTREE ||
  52260. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  52261. return SQLITE_CORRUPT_BKPT;
  52262. }
  52263. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  52264. }
  52265. pPage->isInit = isInitOrig;
  52266. }
  52267. return SQLITE_OK;
  52268. }
  52269. /*
  52270. ** Move the open database page pDbPage to location iFreePage in the
  52271. ** database. The pDbPage reference remains valid.
  52272. **
  52273. ** The isCommit flag indicates that there is no need to remember that
  52274. ** the journal needs to be sync()ed before database page pDbPage->pgno
  52275. ** can be written to. The caller has already promised not to write to that
  52276. ** page.
  52277. */
  52278. static int relocatePage(
  52279. BtShared *pBt, /* Btree */
  52280. MemPage *pDbPage, /* Open page to move */
  52281. u8 eType, /* Pointer map 'type' entry for pDbPage */
  52282. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  52283. Pgno iFreePage, /* The location to move pDbPage to */
  52284. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  52285. ){
  52286. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  52287. Pgno iDbPage = pDbPage->pgno;
  52288. Pager *pPager = pBt->pPager;
  52289. int rc;
  52290. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  52291. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  52292. assert( sqlite3_mutex_held(pBt->mutex) );
  52293. assert( pDbPage->pBt==pBt );
  52294. /* Move page iDbPage from its current location to page number iFreePage */
  52295. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  52296. iDbPage, iFreePage, iPtrPage, eType));
  52297. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  52298. if( rc!=SQLITE_OK ){
  52299. return rc;
  52300. }
  52301. pDbPage->pgno = iFreePage;
  52302. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  52303. ** that point to overflow pages. The pointer map entries for all these
  52304. ** pages need to be changed.
  52305. **
  52306. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  52307. ** pointer to a subsequent overflow page. If this is the case, then
  52308. ** the pointer map needs to be updated for the subsequent overflow page.
  52309. */
  52310. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  52311. rc = setChildPtrmaps(pDbPage);
  52312. if( rc!=SQLITE_OK ){
  52313. return rc;
  52314. }
  52315. }else{
  52316. Pgno nextOvfl = get4byte(pDbPage->aData);
  52317. if( nextOvfl!=0 ){
  52318. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  52319. if( rc!=SQLITE_OK ){
  52320. return rc;
  52321. }
  52322. }
  52323. }
  52324. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  52325. ** that it points at iFreePage. Also fix the pointer map entry for
  52326. ** iPtrPage.
  52327. */
  52328. if( eType!=PTRMAP_ROOTPAGE ){
  52329. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  52330. if( rc!=SQLITE_OK ){
  52331. return rc;
  52332. }
  52333. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  52334. if( rc!=SQLITE_OK ){
  52335. releasePage(pPtrPage);
  52336. return rc;
  52337. }
  52338. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  52339. releasePage(pPtrPage);
  52340. if( rc==SQLITE_OK ){
  52341. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  52342. }
  52343. }
  52344. return rc;
  52345. }
  52346. /* Forward declaration required by incrVacuumStep(). */
  52347. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  52348. /*
  52349. ** Perform a single step of an incremental-vacuum. If successful, return
  52350. ** SQLITE_OK. If there is no work to do (and therefore no point in
  52351. ** calling this function again), return SQLITE_DONE. Or, if an error
  52352. ** occurs, return some other error code.
  52353. **
  52354. ** More specificly, this function attempts to re-organize the database so
  52355. ** that the last page of the file currently in use is no longer in use.
  52356. **
  52357. ** Parameter nFin is the number of pages that this database would contain
  52358. ** were this function called until it returns SQLITE_DONE.
  52359. **
  52360. ** If the bCommit parameter is non-zero, this function assumes that the
  52361. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  52362. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  52363. ** operation, or false for an incremental vacuum.
  52364. */
  52365. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  52366. Pgno nFreeList; /* Number of pages still on the free-list */
  52367. int rc;
  52368. assert( sqlite3_mutex_held(pBt->mutex) );
  52369. assert( iLastPg>nFin );
  52370. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  52371. u8 eType;
  52372. Pgno iPtrPage;
  52373. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  52374. if( nFreeList==0 ){
  52375. return SQLITE_DONE;
  52376. }
  52377. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  52378. if( rc!=SQLITE_OK ){
  52379. return rc;
  52380. }
  52381. if( eType==PTRMAP_ROOTPAGE ){
  52382. return SQLITE_CORRUPT_BKPT;
  52383. }
  52384. if( eType==PTRMAP_FREEPAGE ){
  52385. if( bCommit==0 ){
  52386. /* Remove the page from the files free-list. This is not required
  52387. ** if bCommit is non-zero. In that case, the free-list will be
  52388. ** truncated to zero after this function returns, so it doesn't
  52389. ** matter if it still contains some garbage entries.
  52390. */
  52391. Pgno iFreePg;
  52392. MemPage *pFreePg;
  52393. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  52394. if( rc!=SQLITE_OK ){
  52395. return rc;
  52396. }
  52397. assert( iFreePg==iLastPg );
  52398. releasePage(pFreePg);
  52399. }
  52400. } else {
  52401. Pgno iFreePg; /* Index of free page to move pLastPg to */
  52402. MemPage *pLastPg;
  52403. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  52404. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  52405. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  52406. if( rc!=SQLITE_OK ){
  52407. return rc;
  52408. }
  52409. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  52410. ** is swapped with the first free page pulled off the free list.
  52411. **
  52412. ** On the other hand, if bCommit is greater than zero, then keep
  52413. ** looping until a free-page located within the first nFin pages
  52414. ** of the file is found.
  52415. */
  52416. if( bCommit==0 ){
  52417. eMode = BTALLOC_LE;
  52418. iNear = nFin;
  52419. }
  52420. do {
  52421. MemPage *pFreePg;
  52422. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  52423. if( rc!=SQLITE_OK ){
  52424. releasePage(pLastPg);
  52425. return rc;
  52426. }
  52427. releasePage(pFreePg);
  52428. }while( bCommit && iFreePg>nFin );
  52429. assert( iFreePg<iLastPg );
  52430. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  52431. releasePage(pLastPg);
  52432. if( rc!=SQLITE_OK ){
  52433. return rc;
  52434. }
  52435. }
  52436. }
  52437. if( bCommit==0 ){
  52438. do {
  52439. iLastPg--;
  52440. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  52441. pBt->bDoTruncate = 1;
  52442. pBt->nPage = iLastPg;
  52443. }
  52444. return SQLITE_OK;
  52445. }
  52446. /*
  52447. ** The database opened by the first argument is an auto-vacuum database
  52448. ** nOrig pages in size containing nFree free pages. Return the expected
  52449. ** size of the database in pages following an auto-vacuum operation.
  52450. */
  52451. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  52452. int nEntry; /* Number of entries on one ptrmap page */
  52453. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  52454. Pgno nFin; /* Return value */
  52455. nEntry = pBt->usableSize/5;
  52456. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  52457. nFin = nOrig - nFree - nPtrmap;
  52458. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  52459. nFin--;
  52460. }
  52461. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  52462. nFin--;
  52463. }
  52464. return nFin;
  52465. }
  52466. /*
  52467. ** A write-transaction must be opened before calling this function.
  52468. ** It performs a single unit of work towards an incremental vacuum.
  52469. **
  52470. ** If the incremental vacuum is finished after this function has run,
  52471. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  52472. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  52473. */
  52474. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  52475. int rc;
  52476. BtShared *pBt = p->pBt;
  52477. sqlite3BtreeEnter(p);
  52478. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  52479. if( !pBt->autoVacuum ){
  52480. rc = SQLITE_DONE;
  52481. }else{
  52482. Pgno nOrig = btreePagecount(pBt);
  52483. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  52484. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  52485. if( nOrig<nFin ){
  52486. rc = SQLITE_CORRUPT_BKPT;
  52487. }else if( nFree>0 ){
  52488. rc = saveAllCursors(pBt, 0, 0);
  52489. if( rc==SQLITE_OK ){
  52490. invalidateAllOverflowCache(pBt);
  52491. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  52492. }
  52493. if( rc==SQLITE_OK ){
  52494. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52495. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  52496. }
  52497. }else{
  52498. rc = SQLITE_DONE;
  52499. }
  52500. }
  52501. sqlite3BtreeLeave(p);
  52502. return rc;
  52503. }
  52504. /*
  52505. ** This routine is called prior to sqlite3PagerCommit when a transaction
  52506. ** is committed for an auto-vacuum database.
  52507. **
  52508. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  52509. ** the database file should be truncated to during the commit process.
  52510. ** i.e. the database has been reorganized so that only the first *pnTrunc
  52511. ** pages are in use.
  52512. */
  52513. static int autoVacuumCommit(BtShared *pBt){
  52514. int rc = SQLITE_OK;
  52515. Pager *pPager = pBt->pPager;
  52516. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  52517. assert( sqlite3_mutex_held(pBt->mutex) );
  52518. invalidateAllOverflowCache(pBt);
  52519. assert(pBt->autoVacuum);
  52520. if( !pBt->incrVacuum ){
  52521. Pgno nFin; /* Number of pages in database after autovacuuming */
  52522. Pgno nFree; /* Number of pages on the freelist initially */
  52523. Pgno iFree; /* The next page to be freed */
  52524. Pgno nOrig; /* Database size before freeing */
  52525. nOrig = btreePagecount(pBt);
  52526. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  52527. /* It is not possible to create a database for which the final page
  52528. ** is either a pointer-map page or the pending-byte page. If one
  52529. ** is encountered, this indicates corruption.
  52530. */
  52531. return SQLITE_CORRUPT_BKPT;
  52532. }
  52533. nFree = get4byte(&pBt->pPage1->aData[36]);
  52534. nFin = finalDbSize(pBt, nOrig, nFree);
  52535. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  52536. if( nFin<nOrig ){
  52537. rc = saveAllCursors(pBt, 0, 0);
  52538. }
  52539. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  52540. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  52541. }
  52542. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  52543. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52544. put4byte(&pBt->pPage1->aData[32], 0);
  52545. put4byte(&pBt->pPage1->aData[36], 0);
  52546. put4byte(&pBt->pPage1->aData[28], nFin);
  52547. pBt->bDoTruncate = 1;
  52548. pBt->nPage = nFin;
  52549. }
  52550. if( rc!=SQLITE_OK ){
  52551. sqlite3PagerRollback(pPager);
  52552. }
  52553. }
  52554. assert( nRef>=sqlite3PagerRefcount(pPager) );
  52555. return rc;
  52556. }
  52557. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  52558. # define setChildPtrmaps(x) SQLITE_OK
  52559. #endif
  52560. /*
  52561. ** This routine does the first phase of a two-phase commit. This routine
  52562. ** causes a rollback journal to be created (if it does not already exist)
  52563. ** and populated with enough information so that if a power loss occurs
  52564. ** the database can be restored to its original state by playing back
  52565. ** the journal. Then the contents of the journal are flushed out to
  52566. ** the disk. After the journal is safely on oxide, the changes to the
  52567. ** database are written into the database file and flushed to oxide.
  52568. ** At the end of this call, the rollback journal still exists on the
  52569. ** disk and we are still holding all locks, so the transaction has not
  52570. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  52571. ** commit process.
  52572. **
  52573. ** This call is a no-op if no write-transaction is currently active on pBt.
  52574. **
  52575. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  52576. ** the name of a master journal file that should be written into the
  52577. ** individual journal file, or is NULL, indicating no master journal file
  52578. ** (single database transaction).
  52579. **
  52580. ** When this is called, the master journal should already have been
  52581. ** created, populated with this journal pointer and synced to disk.
  52582. **
  52583. ** Once this is routine has returned, the only thing required to commit
  52584. ** the write-transaction for this database file is to delete the journal.
  52585. */
  52586. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  52587. int rc = SQLITE_OK;
  52588. if( p->inTrans==TRANS_WRITE ){
  52589. BtShared *pBt = p->pBt;
  52590. sqlite3BtreeEnter(p);
  52591. #ifndef SQLITE_OMIT_AUTOVACUUM
  52592. if( pBt->autoVacuum ){
  52593. rc = autoVacuumCommit(pBt);
  52594. if( rc!=SQLITE_OK ){
  52595. sqlite3BtreeLeave(p);
  52596. return rc;
  52597. }
  52598. }
  52599. if( pBt->bDoTruncate ){
  52600. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  52601. }
  52602. #endif
  52603. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  52604. sqlite3BtreeLeave(p);
  52605. }
  52606. return rc;
  52607. }
  52608. /*
  52609. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  52610. ** at the conclusion of a transaction.
  52611. */
  52612. static void btreeEndTransaction(Btree *p){
  52613. BtShared *pBt = p->pBt;
  52614. sqlite3 *db = p->db;
  52615. assert( sqlite3BtreeHoldsMutex(p) );
  52616. #ifndef SQLITE_OMIT_AUTOVACUUM
  52617. pBt->bDoTruncate = 0;
  52618. #endif
  52619. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  52620. /* If there are other active statements that belong to this database
  52621. ** handle, downgrade to a read-only transaction. The other statements
  52622. ** may still be reading from the database. */
  52623. downgradeAllSharedCacheTableLocks(p);
  52624. p->inTrans = TRANS_READ;
  52625. }else{
  52626. /* If the handle had any kind of transaction open, decrement the
  52627. ** transaction count of the shared btree. If the transaction count
  52628. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  52629. ** call below will unlock the pager. */
  52630. if( p->inTrans!=TRANS_NONE ){
  52631. clearAllSharedCacheTableLocks(p);
  52632. pBt->nTransaction--;
  52633. if( 0==pBt->nTransaction ){
  52634. pBt->inTransaction = TRANS_NONE;
  52635. }
  52636. }
  52637. /* Set the current transaction state to TRANS_NONE and unlock the
  52638. ** pager if this call closed the only read or write transaction. */
  52639. p->inTrans = TRANS_NONE;
  52640. unlockBtreeIfUnused(pBt);
  52641. }
  52642. btreeIntegrity(p);
  52643. }
  52644. /*
  52645. ** Commit the transaction currently in progress.
  52646. **
  52647. ** This routine implements the second phase of a 2-phase commit. The
  52648. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  52649. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  52650. ** routine did all the work of writing information out to disk and flushing the
  52651. ** contents so that they are written onto the disk platter. All this
  52652. ** routine has to do is delete or truncate or zero the header in the
  52653. ** the rollback journal (which causes the transaction to commit) and
  52654. ** drop locks.
  52655. **
  52656. ** Normally, if an error occurs while the pager layer is attempting to
  52657. ** finalize the underlying journal file, this function returns an error and
  52658. ** the upper layer will attempt a rollback. However, if the second argument
  52659. ** is non-zero then this b-tree transaction is part of a multi-file
  52660. ** transaction. In this case, the transaction has already been committed
  52661. ** (by deleting a master journal file) and the caller will ignore this
  52662. ** functions return code. So, even if an error occurs in the pager layer,
  52663. ** reset the b-tree objects internal state to indicate that the write
  52664. ** transaction has been closed. This is quite safe, as the pager will have
  52665. ** transitioned to the error state.
  52666. **
  52667. ** This will release the write lock on the database file. If there
  52668. ** are no active cursors, it also releases the read lock.
  52669. */
  52670. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  52671. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  52672. sqlite3BtreeEnter(p);
  52673. btreeIntegrity(p);
  52674. /* If the handle has a write-transaction open, commit the shared-btrees
  52675. ** transaction and set the shared state to TRANS_READ.
  52676. */
  52677. if( p->inTrans==TRANS_WRITE ){
  52678. int rc;
  52679. BtShared *pBt = p->pBt;
  52680. assert( pBt->inTransaction==TRANS_WRITE );
  52681. assert( pBt->nTransaction>0 );
  52682. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  52683. if( rc!=SQLITE_OK && bCleanup==0 ){
  52684. sqlite3BtreeLeave(p);
  52685. return rc;
  52686. }
  52687. pBt->inTransaction = TRANS_READ;
  52688. btreeClearHasContent(pBt);
  52689. }
  52690. btreeEndTransaction(p);
  52691. sqlite3BtreeLeave(p);
  52692. return SQLITE_OK;
  52693. }
  52694. /*
  52695. ** Do both phases of a commit.
  52696. */
  52697. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  52698. int rc;
  52699. sqlite3BtreeEnter(p);
  52700. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  52701. if( rc==SQLITE_OK ){
  52702. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  52703. }
  52704. sqlite3BtreeLeave(p);
  52705. return rc;
  52706. }
  52707. /*
  52708. ** This routine sets the state to CURSOR_FAULT and the error
  52709. ** code to errCode for every cursor on BtShared that pBtree
  52710. ** references.
  52711. **
  52712. ** Every cursor is tripped, including cursors that belong
  52713. ** to other database connections that happen to be sharing
  52714. ** the cache with pBtree.
  52715. **
  52716. ** This routine gets called when a rollback occurs.
  52717. ** All cursors using the same cache must be tripped
  52718. ** to prevent them from trying to use the btree after
  52719. ** the rollback. The rollback may have deleted tables
  52720. ** or moved root pages, so it is not sufficient to
  52721. ** save the state of the cursor. The cursor must be
  52722. ** invalidated.
  52723. */
  52724. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  52725. BtCursor *p;
  52726. if( pBtree==0 ) return;
  52727. sqlite3BtreeEnter(pBtree);
  52728. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52729. int i;
  52730. sqlite3BtreeClearCursor(p);
  52731. p->eState = CURSOR_FAULT;
  52732. p->skipNext = errCode;
  52733. for(i=0; i<=p->iPage; i++){
  52734. releasePage(p->apPage[i]);
  52735. p->apPage[i] = 0;
  52736. }
  52737. }
  52738. sqlite3BtreeLeave(pBtree);
  52739. }
  52740. /*
  52741. ** Rollback the transaction in progress. All cursors will be
  52742. ** invalided by this operation. Any attempt to use a cursor
  52743. ** that was open at the beginning of this operation will result
  52744. ** in an error.
  52745. **
  52746. ** This will release the write lock on the database file. If there
  52747. ** are no active cursors, it also releases the read lock.
  52748. */
  52749. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  52750. int rc;
  52751. BtShared *pBt = p->pBt;
  52752. MemPage *pPage1;
  52753. sqlite3BtreeEnter(p);
  52754. if( tripCode==SQLITE_OK ){
  52755. rc = tripCode = saveAllCursors(pBt, 0, 0);
  52756. }else{
  52757. rc = SQLITE_OK;
  52758. }
  52759. if( tripCode ){
  52760. sqlite3BtreeTripAllCursors(p, tripCode);
  52761. }
  52762. btreeIntegrity(p);
  52763. if( p->inTrans==TRANS_WRITE ){
  52764. int rc2;
  52765. assert( TRANS_WRITE==pBt->inTransaction );
  52766. rc2 = sqlite3PagerRollback(pBt->pPager);
  52767. if( rc2!=SQLITE_OK ){
  52768. rc = rc2;
  52769. }
  52770. /* The rollback may have destroyed the pPage1->aData value. So
  52771. ** call btreeGetPage() on page 1 again to make
  52772. ** sure pPage1->aData is set correctly. */
  52773. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  52774. int nPage = get4byte(28+(u8*)pPage1->aData);
  52775. testcase( nPage==0 );
  52776. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  52777. testcase( pBt->nPage!=nPage );
  52778. pBt->nPage = nPage;
  52779. releasePage(pPage1);
  52780. }
  52781. assert( countValidCursors(pBt, 1)==0 );
  52782. pBt->inTransaction = TRANS_READ;
  52783. btreeClearHasContent(pBt);
  52784. }
  52785. btreeEndTransaction(p);
  52786. sqlite3BtreeLeave(p);
  52787. return rc;
  52788. }
  52789. /*
  52790. ** Start a statement subtransaction. The subtransaction can can be rolled
  52791. ** back independently of the main transaction. You must start a transaction
  52792. ** before starting a subtransaction. The subtransaction is ended automatically
  52793. ** if the main transaction commits or rolls back.
  52794. **
  52795. ** Statement subtransactions are used around individual SQL statements
  52796. ** that are contained within a BEGIN...COMMIT block. If a constraint
  52797. ** error occurs within the statement, the effect of that one statement
  52798. ** can be rolled back without having to rollback the entire transaction.
  52799. **
  52800. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  52801. ** value passed as the second parameter is the total number of savepoints,
  52802. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  52803. ** are no active savepoints and no other statement-transactions open,
  52804. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  52805. ** using the sqlite3BtreeSavepoint() function.
  52806. */
  52807. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  52808. int rc;
  52809. BtShared *pBt = p->pBt;
  52810. sqlite3BtreeEnter(p);
  52811. assert( p->inTrans==TRANS_WRITE );
  52812. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52813. assert( iStatement>0 );
  52814. assert( iStatement>p->db->nSavepoint );
  52815. assert( pBt->inTransaction==TRANS_WRITE );
  52816. /* At the pager level, a statement transaction is a savepoint with
  52817. ** an index greater than all savepoints created explicitly using
  52818. ** SQL statements. It is illegal to open, release or rollback any
  52819. ** such savepoints while the statement transaction savepoint is active.
  52820. */
  52821. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  52822. sqlite3BtreeLeave(p);
  52823. return rc;
  52824. }
  52825. /*
  52826. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  52827. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  52828. ** savepoint identified by parameter iSavepoint, depending on the value
  52829. ** of op.
  52830. **
  52831. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  52832. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  52833. ** contents of the entire transaction are rolled back. This is different
  52834. ** from a normal transaction rollback, as no locks are released and the
  52835. ** transaction remains open.
  52836. */
  52837. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  52838. int rc = SQLITE_OK;
  52839. if( p && p->inTrans==TRANS_WRITE ){
  52840. BtShared *pBt = p->pBt;
  52841. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52842. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  52843. sqlite3BtreeEnter(p);
  52844. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  52845. if( rc==SQLITE_OK ){
  52846. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  52847. pBt->nPage = 0;
  52848. }
  52849. rc = newDatabase(pBt);
  52850. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  52851. /* The database size was written into the offset 28 of the header
  52852. ** when the transaction started, so we know that the value at offset
  52853. ** 28 is nonzero. */
  52854. assert( pBt->nPage>0 );
  52855. }
  52856. sqlite3BtreeLeave(p);
  52857. }
  52858. return rc;
  52859. }
  52860. /*
  52861. ** Create a new cursor for the BTree whose root is on the page
  52862. ** iTable. If a read-only cursor is requested, it is assumed that
  52863. ** the caller already has at least a read-only transaction open
  52864. ** on the database already. If a write-cursor is requested, then
  52865. ** the caller is assumed to have an open write transaction.
  52866. **
  52867. ** If wrFlag==0, then the cursor can only be used for reading.
  52868. ** If wrFlag==1, then the cursor can be used for reading or for
  52869. ** writing if other conditions for writing are also met. These
  52870. ** are the conditions that must be met in order for writing to
  52871. ** be allowed:
  52872. **
  52873. ** 1: The cursor must have been opened with wrFlag==1
  52874. **
  52875. ** 2: Other database connections that share the same pager cache
  52876. ** but which are not in the READ_UNCOMMITTED state may not have
  52877. ** cursors open with wrFlag==0 on the same table. Otherwise
  52878. ** the changes made by this write cursor would be visible to
  52879. ** the read cursors in the other database connection.
  52880. **
  52881. ** 3: The database must be writable (not on read-only media)
  52882. **
  52883. ** 4: There must be an active transaction.
  52884. **
  52885. ** No checking is done to make sure that page iTable really is the
  52886. ** root page of a b-tree. If it is not, then the cursor acquired
  52887. ** will not work correctly.
  52888. **
  52889. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  52890. ** on pCur to initialize the memory space prior to invoking this routine.
  52891. */
  52892. static int btreeCursor(
  52893. Btree *p, /* The btree */
  52894. int iTable, /* Root page of table to open */
  52895. int wrFlag, /* 1 to write. 0 read-only */
  52896. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  52897. BtCursor *pCur /* Space for new cursor */
  52898. ){
  52899. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  52900. assert( sqlite3BtreeHoldsMutex(p) );
  52901. assert( wrFlag==0 || wrFlag==1 );
  52902. /* The following assert statements verify that if this is a sharable
  52903. ** b-tree database, the connection is holding the required table locks,
  52904. ** and that no other connection has any open cursor that conflicts with
  52905. ** this lock. */
  52906. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  52907. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  52908. /* Assert that the caller has opened the required transaction. */
  52909. assert( p->inTrans>TRANS_NONE );
  52910. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  52911. assert( pBt->pPage1 && pBt->pPage1->aData );
  52912. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  52913. return SQLITE_READONLY;
  52914. }
  52915. if( iTable==1 && btreePagecount(pBt)==0 ){
  52916. assert( wrFlag==0 );
  52917. iTable = 0;
  52918. }
  52919. /* Now that no other errors can occur, finish filling in the BtCursor
  52920. ** variables and link the cursor into the BtShared list. */
  52921. pCur->pgnoRoot = (Pgno)iTable;
  52922. pCur->iPage = -1;
  52923. pCur->pKeyInfo = pKeyInfo;
  52924. pCur->pBtree = p;
  52925. pCur->pBt = pBt;
  52926. pCur->wrFlag = (u8)wrFlag;
  52927. pCur->pNext = pBt->pCursor;
  52928. if( pCur->pNext ){
  52929. pCur->pNext->pPrev = pCur;
  52930. }
  52931. pBt->pCursor = pCur;
  52932. pCur->eState = CURSOR_INVALID;
  52933. pCur->cachedRowid = 0;
  52934. return SQLITE_OK;
  52935. }
  52936. SQLITE_PRIVATE int sqlite3BtreeCursor(
  52937. Btree *p, /* The btree */
  52938. int iTable, /* Root page of table to open */
  52939. int wrFlag, /* 1 to write. 0 read-only */
  52940. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  52941. BtCursor *pCur /* Write new cursor here */
  52942. ){
  52943. int rc;
  52944. sqlite3BtreeEnter(p);
  52945. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  52946. sqlite3BtreeLeave(p);
  52947. return rc;
  52948. }
  52949. /*
  52950. ** Return the size of a BtCursor object in bytes.
  52951. **
  52952. ** This interfaces is needed so that users of cursors can preallocate
  52953. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  52954. ** to users so they cannot do the sizeof() themselves - they must call
  52955. ** this routine.
  52956. */
  52957. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  52958. return ROUND8(sizeof(BtCursor));
  52959. }
  52960. /*
  52961. ** Initialize memory that will be converted into a BtCursor object.
  52962. **
  52963. ** The simple approach here would be to memset() the entire object
  52964. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  52965. ** do not need to be zeroed and they are large, so we can save a lot
  52966. ** of run-time by skipping the initialization of those elements.
  52967. */
  52968. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  52969. memset(p, 0, offsetof(BtCursor, iPage));
  52970. }
  52971. /*
  52972. ** Set the cached rowid value of every cursor in the same database file
  52973. ** as pCur and having the same root page number as pCur. The value is
  52974. ** set to iRowid.
  52975. **
  52976. ** Only positive rowid values are considered valid for this cache.
  52977. ** The cache is initialized to zero, indicating an invalid cache.
  52978. ** A btree will work fine with zero or negative rowids. We just cannot
  52979. ** cache zero or negative rowids, which means tables that use zero or
  52980. ** negative rowids might run a little slower. But in practice, zero
  52981. ** or negative rowids are very uncommon so this should not be a problem.
  52982. */
  52983. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  52984. BtCursor *p;
  52985. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  52986. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  52987. }
  52988. assert( pCur->cachedRowid==iRowid );
  52989. }
  52990. /*
  52991. ** Return the cached rowid for the given cursor. A negative or zero
  52992. ** return value indicates that the rowid cache is invalid and should be
  52993. ** ignored. If the rowid cache has never before been set, then a
  52994. ** zero is returned.
  52995. */
  52996. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  52997. return pCur->cachedRowid;
  52998. }
  52999. /*
  53000. ** Close a cursor. The read lock on the database file is released
  53001. ** when the last cursor is closed.
  53002. */
  53003. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  53004. Btree *pBtree = pCur->pBtree;
  53005. if( pBtree ){
  53006. int i;
  53007. BtShared *pBt = pCur->pBt;
  53008. sqlite3BtreeEnter(pBtree);
  53009. sqlite3BtreeClearCursor(pCur);
  53010. if( pCur->pPrev ){
  53011. pCur->pPrev->pNext = pCur->pNext;
  53012. }else{
  53013. pBt->pCursor = pCur->pNext;
  53014. }
  53015. if( pCur->pNext ){
  53016. pCur->pNext->pPrev = pCur->pPrev;
  53017. }
  53018. for(i=0; i<=pCur->iPage; i++){
  53019. releasePage(pCur->apPage[i]);
  53020. }
  53021. unlockBtreeIfUnused(pBt);
  53022. invalidateOverflowCache(pCur);
  53023. /* sqlite3_free(pCur); */
  53024. sqlite3BtreeLeave(pBtree);
  53025. }
  53026. return SQLITE_OK;
  53027. }
  53028. /*
  53029. ** Make sure the BtCursor* given in the argument has a valid
  53030. ** BtCursor.info structure. If it is not already valid, call
  53031. ** btreeParseCell() to fill it in.
  53032. **
  53033. ** BtCursor.info is a cache of the information in the current cell.
  53034. ** Using this cache reduces the number of calls to btreeParseCell().
  53035. **
  53036. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  53037. ** compiler to crash when getCellInfo() is implemented as a macro.
  53038. ** But there is a measureable speed advantage to using the macro on gcc
  53039. ** (when less compiler optimizations like -Os or -O0 are used and the
  53040. ** compiler is not doing agressive inlining.) So we use a real function
  53041. ** for MSVC and a macro for everything else. Ticket #2457.
  53042. */
  53043. #ifndef NDEBUG
  53044. static void assertCellInfo(BtCursor *pCur){
  53045. CellInfo info;
  53046. int iPage = pCur->iPage;
  53047. memset(&info, 0, sizeof(info));
  53048. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  53049. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  53050. }
  53051. #else
  53052. #define assertCellInfo(x)
  53053. #endif
  53054. #ifdef _MSC_VER
  53055. /* Use a real function in MSVC to work around bugs in that compiler. */
  53056. static void getCellInfo(BtCursor *pCur){
  53057. if( pCur->info.nSize==0 ){
  53058. int iPage = pCur->iPage;
  53059. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  53060. pCur->validNKey = 1;
  53061. }else{
  53062. assertCellInfo(pCur);
  53063. }
  53064. }
  53065. #else /* if not _MSC_VER */
  53066. /* Use a macro in all other compilers so that the function is inlined */
  53067. #define getCellInfo(pCur) \
  53068. if( pCur->info.nSize==0 ){ \
  53069. int iPage = pCur->iPage; \
  53070. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  53071. pCur->validNKey = 1; \
  53072. }else{ \
  53073. assertCellInfo(pCur); \
  53074. }
  53075. #endif /* _MSC_VER */
  53076. #ifndef NDEBUG /* The next routine used only within assert() statements */
  53077. /*
  53078. ** Return true if the given BtCursor is valid. A valid cursor is one
  53079. ** that is currently pointing to a row in a (non-empty) table.
  53080. ** This is a verification routine is used only within assert() statements.
  53081. */
  53082. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  53083. return pCur && pCur->eState==CURSOR_VALID;
  53084. }
  53085. #endif /* NDEBUG */
  53086. /*
  53087. ** Set *pSize to the size of the buffer needed to hold the value of
  53088. ** the key for the current entry. If the cursor is not pointing
  53089. ** to a valid entry, *pSize is set to 0.
  53090. **
  53091. ** For a table with the INTKEY flag set, this routine returns the key
  53092. ** itself, not the number of bytes in the key.
  53093. **
  53094. ** The caller must position the cursor prior to invoking this routine.
  53095. **
  53096. ** This routine cannot fail. It always returns SQLITE_OK.
  53097. */
  53098. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  53099. assert( cursorHoldsMutex(pCur) );
  53100. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  53101. if( pCur->eState!=CURSOR_VALID ){
  53102. *pSize = 0;
  53103. }else{
  53104. getCellInfo(pCur);
  53105. *pSize = pCur->info.nKey;
  53106. }
  53107. return SQLITE_OK;
  53108. }
  53109. /*
  53110. ** Set *pSize to the number of bytes of data in the entry the
  53111. ** cursor currently points to.
  53112. **
  53113. ** The caller must guarantee that the cursor is pointing to a non-NULL
  53114. ** valid entry. In other words, the calling procedure must guarantee
  53115. ** that the cursor has Cursor.eState==CURSOR_VALID.
  53116. **
  53117. ** Failure is not possible. This function always returns SQLITE_OK.
  53118. ** It might just as well be a procedure (returning void) but we continue
  53119. ** to return an integer result code for historical reasons.
  53120. */
  53121. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  53122. assert( cursorHoldsMutex(pCur) );
  53123. assert( pCur->eState==CURSOR_VALID );
  53124. getCellInfo(pCur);
  53125. *pSize = pCur->info.nData;
  53126. return SQLITE_OK;
  53127. }
  53128. /*
  53129. ** Given the page number of an overflow page in the database (parameter
  53130. ** ovfl), this function finds the page number of the next page in the
  53131. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  53132. ** pointer-map data instead of reading the content of page ovfl to do so.
  53133. **
  53134. ** If an error occurs an SQLite error code is returned. Otherwise:
  53135. **
  53136. ** The page number of the next overflow page in the linked list is
  53137. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  53138. ** list, *pPgnoNext is set to zero.
  53139. **
  53140. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  53141. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  53142. ** reference. It is the responsibility of the caller to call releasePage()
  53143. ** on *ppPage to free the reference. In no reference was obtained (because
  53144. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  53145. ** *ppPage is set to zero.
  53146. */
  53147. static int getOverflowPage(
  53148. BtShared *pBt, /* The database file */
  53149. Pgno ovfl, /* Current overflow page number */
  53150. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  53151. Pgno *pPgnoNext /* OUT: Next overflow page number */
  53152. ){
  53153. Pgno next = 0;
  53154. MemPage *pPage = 0;
  53155. int rc = SQLITE_OK;
  53156. assert( sqlite3_mutex_held(pBt->mutex) );
  53157. assert(pPgnoNext);
  53158. #ifndef SQLITE_OMIT_AUTOVACUUM
  53159. /* Try to find the next page in the overflow list using the
  53160. ** autovacuum pointer-map pages. Guess that the next page in
  53161. ** the overflow list is page number (ovfl+1). If that guess turns
  53162. ** out to be wrong, fall back to loading the data of page
  53163. ** number ovfl to determine the next page number.
  53164. */
  53165. if( pBt->autoVacuum ){
  53166. Pgno pgno;
  53167. Pgno iGuess = ovfl+1;
  53168. u8 eType;
  53169. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  53170. iGuess++;
  53171. }
  53172. if( iGuess<=btreePagecount(pBt) ){
  53173. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  53174. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  53175. next = iGuess;
  53176. rc = SQLITE_DONE;
  53177. }
  53178. }
  53179. }
  53180. #endif
  53181. assert( next==0 || rc==SQLITE_DONE );
  53182. if( rc==SQLITE_OK ){
  53183. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  53184. assert( rc==SQLITE_OK || pPage==0 );
  53185. if( rc==SQLITE_OK ){
  53186. next = get4byte(pPage->aData);
  53187. }
  53188. }
  53189. *pPgnoNext = next;
  53190. if( ppPage ){
  53191. *ppPage = pPage;
  53192. }else{
  53193. releasePage(pPage);
  53194. }
  53195. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  53196. }
  53197. /*
  53198. ** Copy data from a buffer to a page, or from a page to a buffer.
  53199. **
  53200. ** pPayload is a pointer to data stored on database page pDbPage.
  53201. ** If argument eOp is false, then nByte bytes of data are copied
  53202. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  53203. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  53204. ** of data are copied from the buffer pBuf to pPayload.
  53205. **
  53206. ** SQLITE_OK is returned on success, otherwise an error code.
  53207. */
  53208. static int copyPayload(
  53209. void *pPayload, /* Pointer to page data */
  53210. void *pBuf, /* Pointer to buffer */
  53211. int nByte, /* Number of bytes to copy */
  53212. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  53213. DbPage *pDbPage /* Page containing pPayload */
  53214. ){
  53215. if( eOp ){
  53216. /* Copy data from buffer to page (a write operation) */
  53217. int rc = sqlite3PagerWrite(pDbPage);
  53218. if( rc!=SQLITE_OK ){
  53219. return rc;
  53220. }
  53221. memcpy(pPayload, pBuf, nByte);
  53222. }else{
  53223. /* Copy data from page to buffer (a read operation) */
  53224. memcpy(pBuf, pPayload, nByte);
  53225. }
  53226. return SQLITE_OK;
  53227. }
  53228. /*
  53229. ** This function is used to read or overwrite payload information
  53230. ** for the entry that the pCur cursor is pointing to. If the eOp
  53231. ** parameter is 0, this is a read operation (data copied into
  53232. ** buffer pBuf). If it is non-zero, a write (data copied from
  53233. ** buffer pBuf).
  53234. **
  53235. ** A total of "amt" bytes are read or written beginning at "offset".
  53236. ** Data is read to or from the buffer pBuf.
  53237. **
  53238. ** The content being read or written might appear on the main page
  53239. ** or be scattered out on multiple overflow pages.
  53240. **
  53241. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  53242. ** cursor entry uses one or more overflow pages, this function
  53243. ** allocates space for and lazily popluates the overflow page-list
  53244. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  53245. ** cache to make seeking to the supplied offset more efficient.
  53246. **
  53247. ** Once an overflow page-list cache has been allocated, it may be
  53248. ** invalidated if some other cursor writes to the same table, or if
  53249. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  53250. ** mode, the following events may invalidate an overflow page-list cache.
  53251. **
  53252. ** * An incremental vacuum,
  53253. ** * A commit in auto_vacuum="full" mode,
  53254. ** * Creating a table (may require moving an overflow page).
  53255. */
  53256. static int accessPayload(
  53257. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53258. u32 offset, /* Begin reading this far into payload */
  53259. u32 amt, /* Read this many bytes */
  53260. unsigned char *pBuf, /* Write the bytes into this buffer */
  53261. int eOp /* zero to read. non-zero to write. */
  53262. ){
  53263. unsigned char *aPayload;
  53264. int rc = SQLITE_OK;
  53265. u32 nKey;
  53266. int iIdx = 0;
  53267. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  53268. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  53269. assert( pPage );
  53270. assert( pCur->eState==CURSOR_VALID );
  53271. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53272. assert( cursorHoldsMutex(pCur) );
  53273. getCellInfo(pCur);
  53274. aPayload = pCur->info.pCell + pCur->info.nHeader;
  53275. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  53276. if( NEVER(offset+amt > nKey+pCur->info.nData)
  53277. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  53278. ){
  53279. /* Trying to read or write past the end of the data is an error */
  53280. return SQLITE_CORRUPT_BKPT;
  53281. }
  53282. /* Check if data must be read/written to/from the btree page itself. */
  53283. if( offset<pCur->info.nLocal ){
  53284. int a = amt;
  53285. if( a+offset>pCur->info.nLocal ){
  53286. a = pCur->info.nLocal - offset;
  53287. }
  53288. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  53289. offset = 0;
  53290. pBuf += a;
  53291. amt -= a;
  53292. }else{
  53293. offset -= pCur->info.nLocal;
  53294. }
  53295. if( rc==SQLITE_OK && amt>0 ){
  53296. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  53297. Pgno nextPage;
  53298. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  53299. #ifndef SQLITE_OMIT_INCRBLOB
  53300. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  53301. ** has not been allocated, allocate it now. The array is sized at
  53302. ** one entry for each overflow page in the overflow chain. The
  53303. ** page number of the first overflow page is stored in aOverflow[0],
  53304. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  53305. ** (the cache is lazily populated).
  53306. */
  53307. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  53308. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  53309. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  53310. /* nOvfl is always positive. If it were zero, fetchPayload would have
  53311. ** been used instead of this routine. */
  53312. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  53313. rc = SQLITE_NOMEM;
  53314. }
  53315. }
  53316. /* If the overflow page-list cache has been allocated and the
  53317. ** entry for the first required overflow page is valid, skip
  53318. ** directly to it.
  53319. */
  53320. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  53321. iIdx = (offset/ovflSize);
  53322. nextPage = pCur->aOverflow[iIdx];
  53323. offset = (offset%ovflSize);
  53324. }
  53325. #endif
  53326. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  53327. #ifndef SQLITE_OMIT_INCRBLOB
  53328. /* If required, populate the overflow page-list cache. */
  53329. if( pCur->aOverflow ){
  53330. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  53331. pCur->aOverflow[iIdx] = nextPage;
  53332. }
  53333. #endif
  53334. if( offset>=ovflSize ){
  53335. /* The only reason to read this page is to obtain the page
  53336. ** number for the next page in the overflow chain. The page
  53337. ** data is not required. So first try to lookup the overflow
  53338. ** page-list cache, if any, then fall back to the getOverflowPage()
  53339. ** function.
  53340. */
  53341. #ifndef SQLITE_OMIT_INCRBLOB
  53342. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  53343. nextPage = pCur->aOverflow[iIdx+1];
  53344. } else
  53345. #endif
  53346. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  53347. offset -= ovflSize;
  53348. }else{
  53349. /* Need to read this page properly. It contains some of the
  53350. ** range of data that is being read (eOp==0) or written (eOp!=0).
  53351. */
  53352. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53353. sqlite3_file *fd;
  53354. #endif
  53355. int a = amt;
  53356. if( a + offset > ovflSize ){
  53357. a = ovflSize - offset;
  53358. }
  53359. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53360. /* If all the following are true:
  53361. **
  53362. ** 1) this is a read operation, and
  53363. ** 2) data is required from the start of this overflow page, and
  53364. ** 3) the database is file-backed, and
  53365. ** 4) there is no open write-transaction, and
  53366. ** 5) the database is not a WAL database,
  53367. **
  53368. ** then data can be read directly from the database file into the
  53369. ** output buffer, bypassing the page-cache altogether. This speeds
  53370. ** up loading large records that span many overflow pages.
  53371. */
  53372. if( eOp==0 /* (1) */
  53373. && offset==0 /* (2) */
  53374. && pBt->inTransaction==TRANS_READ /* (4) */
  53375. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  53376. && pBt->pPage1->aData[19]==0x01 /* (5) */
  53377. ){
  53378. u8 aSave[4];
  53379. u8 *aWrite = &pBuf[-4];
  53380. memcpy(aSave, aWrite, 4);
  53381. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  53382. nextPage = get4byte(aWrite);
  53383. memcpy(aWrite, aSave, 4);
  53384. }else
  53385. #endif
  53386. {
  53387. DbPage *pDbPage;
  53388. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  53389. (eOp==0 ? PAGER_GET_READONLY : 0)
  53390. );
  53391. if( rc==SQLITE_OK ){
  53392. aPayload = sqlite3PagerGetData(pDbPage);
  53393. nextPage = get4byte(aPayload);
  53394. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  53395. sqlite3PagerUnref(pDbPage);
  53396. offset = 0;
  53397. }
  53398. }
  53399. amt -= a;
  53400. pBuf += a;
  53401. }
  53402. }
  53403. }
  53404. if( rc==SQLITE_OK && amt>0 ){
  53405. return SQLITE_CORRUPT_BKPT;
  53406. }
  53407. return rc;
  53408. }
  53409. /*
  53410. ** Read part of the key associated with cursor pCur. Exactly
  53411. ** "amt" bytes will be transfered into pBuf[]. The transfer
  53412. ** begins at "offset".
  53413. **
  53414. ** The caller must ensure that pCur is pointing to a valid row
  53415. ** in the table.
  53416. **
  53417. ** Return SQLITE_OK on success or an error code if anything goes
  53418. ** wrong. An error is returned if "offset+amt" is larger than
  53419. ** the available payload.
  53420. */
  53421. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53422. assert( cursorHoldsMutex(pCur) );
  53423. assert( pCur->eState==CURSOR_VALID );
  53424. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53425. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53426. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  53427. }
  53428. /*
  53429. ** Read part of the data associated with cursor pCur. Exactly
  53430. ** "amt" bytes will be transfered into pBuf[]. The transfer
  53431. ** begins at "offset".
  53432. **
  53433. ** Return SQLITE_OK on success or an error code if anything goes
  53434. ** wrong. An error is returned if "offset+amt" is larger than
  53435. ** the available payload.
  53436. */
  53437. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53438. int rc;
  53439. #ifndef SQLITE_OMIT_INCRBLOB
  53440. if ( pCur->eState==CURSOR_INVALID ){
  53441. return SQLITE_ABORT;
  53442. }
  53443. #endif
  53444. assert( cursorHoldsMutex(pCur) );
  53445. rc = restoreCursorPosition(pCur);
  53446. if( rc==SQLITE_OK ){
  53447. assert( pCur->eState==CURSOR_VALID );
  53448. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53449. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53450. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  53451. }
  53452. return rc;
  53453. }
  53454. /*
  53455. ** Return a pointer to payload information from the entry that the
  53456. ** pCur cursor is pointing to. The pointer is to the beginning of
  53457. ** the key if skipKey==0 and it points to the beginning of data if
  53458. ** skipKey==1. The number of bytes of available key/data is written
  53459. ** into *pAmt. If *pAmt==0, then the value returned will not be
  53460. ** a valid pointer.
  53461. **
  53462. ** This routine is an optimization. It is common for the entire key
  53463. ** and data to fit on the local page and for there to be no overflow
  53464. ** pages. When that is so, this routine can be used to access the
  53465. ** key and data without making a copy. If the key and/or data spills
  53466. ** onto overflow pages, then accessPayload() must be used to reassemble
  53467. ** the key/data and copy it into a preallocated buffer.
  53468. **
  53469. ** The pointer returned by this routine looks directly into the cached
  53470. ** page of the database. The data might change or move the next time
  53471. ** any btree routine is called.
  53472. */
  53473. static const unsigned char *fetchPayload(
  53474. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53475. int *pAmt, /* Write the number of available bytes here */
  53476. int skipKey /* read beginning at data if this is true */
  53477. ){
  53478. unsigned char *aPayload;
  53479. MemPage *pPage;
  53480. u32 nKey;
  53481. u32 nLocal;
  53482. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  53483. assert( pCur->eState==CURSOR_VALID );
  53484. assert( cursorHoldsMutex(pCur) );
  53485. pPage = pCur->apPage[pCur->iPage];
  53486. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53487. if( NEVER(pCur->info.nSize==0) ){
  53488. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  53489. &pCur->info);
  53490. }
  53491. aPayload = pCur->info.pCell;
  53492. aPayload += pCur->info.nHeader;
  53493. if( pPage->intKey ){
  53494. nKey = 0;
  53495. }else{
  53496. nKey = (int)pCur->info.nKey;
  53497. }
  53498. if( skipKey ){
  53499. aPayload += nKey;
  53500. nLocal = pCur->info.nLocal - nKey;
  53501. }else{
  53502. nLocal = pCur->info.nLocal;
  53503. assert( nLocal<=nKey );
  53504. }
  53505. *pAmt = nLocal;
  53506. return aPayload;
  53507. }
  53508. /*
  53509. ** For the entry that cursor pCur is point to, return as
  53510. ** many bytes of the key or data as are available on the local
  53511. ** b-tree page. Write the number of available bytes into *pAmt.
  53512. **
  53513. ** The pointer returned is ephemeral. The key/data may move
  53514. ** or be destroyed on the next call to any Btree routine,
  53515. ** including calls from other threads against the same cache.
  53516. ** Hence, a mutex on the BtShared should be held prior to calling
  53517. ** this routine.
  53518. **
  53519. ** These routines is used to get quick access to key and data
  53520. ** in the common case where no overflow pages are used.
  53521. */
  53522. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  53523. const void *p = 0;
  53524. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53525. assert( cursorHoldsMutex(pCur) );
  53526. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  53527. p = (const void*)fetchPayload(pCur, pAmt, 0);
  53528. }
  53529. return p;
  53530. }
  53531. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  53532. const void *p = 0;
  53533. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53534. assert( cursorHoldsMutex(pCur) );
  53535. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  53536. p = (const void*)fetchPayload(pCur, pAmt, 1);
  53537. }
  53538. return p;
  53539. }
  53540. /*
  53541. ** Move the cursor down to a new child page. The newPgno argument is the
  53542. ** page number of the child page to move to.
  53543. **
  53544. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  53545. ** the new child page does not match the flags field of the parent (i.e.
  53546. ** if an intkey page appears to be the parent of a non-intkey page, or
  53547. ** vice-versa).
  53548. */
  53549. static int moveToChild(BtCursor *pCur, u32 newPgno){
  53550. int rc;
  53551. int i = pCur->iPage;
  53552. MemPage *pNewPage;
  53553. BtShared *pBt = pCur->pBt;
  53554. assert( cursorHoldsMutex(pCur) );
  53555. assert( pCur->eState==CURSOR_VALID );
  53556. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  53557. assert( pCur->iPage>=0 );
  53558. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  53559. return SQLITE_CORRUPT_BKPT;
  53560. }
  53561. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  53562. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  53563. if( rc ) return rc;
  53564. pCur->apPage[i+1] = pNewPage;
  53565. pCur->aiIdx[i+1] = 0;
  53566. pCur->iPage++;
  53567. pCur->info.nSize = 0;
  53568. pCur->validNKey = 0;
  53569. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  53570. return SQLITE_CORRUPT_BKPT;
  53571. }
  53572. return SQLITE_OK;
  53573. }
  53574. #if 0
  53575. /*
  53576. ** Page pParent is an internal (non-leaf) tree page. This function
  53577. ** asserts that page number iChild is the left-child if the iIdx'th
  53578. ** cell in page pParent. Or, if iIdx is equal to the total number of
  53579. ** cells in pParent, that page number iChild is the right-child of
  53580. ** the page.
  53581. */
  53582. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  53583. assert( iIdx<=pParent->nCell );
  53584. if( iIdx==pParent->nCell ){
  53585. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  53586. }else{
  53587. assert( get4byte(findCell(pParent, iIdx))==iChild );
  53588. }
  53589. }
  53590. #else
  53591. # define assertParentIndex(x,y,z)
  53592. #endif
  53593. /*
  53594. ** Move the cursor up to the parent page.
  53595. **
  53596. ** pCur->idx is set to the cell index that contains the pointer
  53597. ** to the page we are coming from. If we are coming from the
  53598. ** right-most child page then pCur->idx is set to one more than
  53599. ** the largest cell index.
  53600. */
  53601. static void moveToParent(BtCursor *pCur){
  53602. assert( cursorHoldsMutex(pCur) );
  53603. assert( pCur->eState==CURSOR_VALID );
  53604. assert( pCur->iPage>0 );
  53605. assert( pCur->apPage[pCur->iPage] );
  53606. /* UPDATE: It is actually possible for the condition tested by the assert
  53607. ** below to be untrue if the database file is corrupt. This can occur if
  53608. ** one cursor has modified page pParent while a reference to it is held
  53609. ** by a second cursor. Which can only happen if a single page is linked
  53610. ** into more than one b-tree structure in a corrupt database. */
  53611. #if 0
  53612. assertParentIndex(
  53613. pCur->apPage[pCur->iPage-1],
  53614. pCur->aiIdx[pCur->iPage-1],
  53615. pCur->apPage[pCur->iPage]->pgno
  53616. );
  53617. #endif
  53618. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  53619. releasePage(pCur->apPage[pCur->iPage]);
  53620. pCur->iPage--;
  53621. pCur->info.nSize = 0;
  53622. pCur->validNKey = 0;
  53623. }
  53624. /*
  53625. ** Move the cursor to point to the root page of its b-tree structure.
  53626. **
  53627. ** If the table has a virtual root page, then the cursor is moved to point
  53628. ** to the virtual root page instead of the actual root page. A table has a
  53629. ** virtual root page when the actual root page contains no cells and a
  53630. ** single child page. This can only happen with the table rooted at page 1.
  53631. **
  53632. ** If the b-tree structure is empty, the cursor state is set to
  53633. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  53634. ** cell located on the root (or virtual root) page and the cursor state
  53635. ** is set to CURSOR_VALID.
  53636. **
  53637. ** If this function returns successfully, it may be assumed that the
  53638. ** page-header flags indicate that the [virtual] root-page is the expected
  53639. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  53640. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  53641. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  53642. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  53643. ** b-tree).
  53644. */
  53645. static int moveToRoot(BtCursor *pCur){
  53646. MemPage *pRoot;
  53647. int rc = SQLITE_OK;
  53648. Btree *p = pCur->pBtree;
  53649. BtShared *pBt = p->pBt;
  53650. assert( cursorHoldsMutex(pCur) );
  53651. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  53652. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  53653. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  53654. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  53655. if( pCur->eState==CURSOR_FAULT ){
  53656. assert( pCur->skipNext!=SQLITE_OK );
  53657. return pCur->skipNext;
  53658. }
  53659. sqlite3BtreeClearCursor(pCur);
  53660. }
  53661. if( pCur->iPage>=0 ){
  53662. int i;
  53663. for(i=1; i<=pCur->iPage; i++){
  53664. releasePage(pCur->apPage[i]);
  53665. }
  53666. pCur->iPage = 0;
  53667. }else if( pCur->pgnoRoot==0 ){
  53668. pCur->eState = CURSOR_INVALID;
  53669. return SQLITE_OK;
  53670. }else{
  53671. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
  53672. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  53673. if( rc!=SQLITE_OK ){
  53674. pCur->eState = CURSOR_INVALID;
  53675. return rc;
  53676. }
  53677. pCur->iPage = 0;
  53678. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  53679. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  53680. ** NULL, the caller expects a table b-tree. If this is not the case,
  53681. ** return an SQLITE_CORRUPT error. */
  53682. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  53683. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  53684. return SQLITE_CORRUPT_BKPT;
  53685. }
  53686. }
  53687. /* Assert that the root page is of the correct type. This must be the
  53688. ** case as the call to this function that loaded the root-page (either
  53689. ** this call or a previous invocation) would have detected corruption
  53690. ** if the assumption were not true, and it is not possible for the flags
  53691. ** byte to have been modified while this cursor is holding a reference
  53692. ** to the page. */
  53693. pRoot = pCur->apPage[0];
  53694. assert( pRoot->pgno==pCur->pgnoRoot );
  53695. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  53696. pCur->aiIdx[0] = 0;
  53697. pCur->info.nSize = 0;
  53698. pCur->atLast = 0;
  53699. pCur->validNKey = 0;
  53700. if( pRoot->nCell==0 && !pRoot->leaf ){
  53701. Pgno subpage;
  53702. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  53703. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  53704. pCur->eState = CURSOR_VALID;
  53705. rc = moveToChild(pCur, subpage);
  53706. }else{
  53707. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  53708. }
  53709. return rc;
  53710. }
  53711. /*
  53712. ** Move the cursor down to the left-most leaf entry beneath the
  53713. ** entry to which it is currently pointing.
  53714. **
  53715. ** The left-most leaf is the one with the smallest key - the first
  53716. ** in ascending order.
  53717. */
  53718. static int moveToLeftmost(BtCursor *pCur){
  53719. Pgno pgno;
  53720. int rc = SQLITE_OK;
  53721. MemPage *pPage;
  53722. assert( cursorHoldsMutex(pCur) );
  53723. assert( pCur->eState==CURSOR_VALID );
  53724. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53725. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53726. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  53727. rc = moveToChild(pCur, pgno);
  53728. }
  53729. return rc;
  53730. }
  53731. /*
  53732. ** Move the cursor down to the right-most leaf entry beneath the
  53733. ** page to which it is currently pointing. Notice the difference
  53734. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  53735. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  53736. ** finds the right-most entry beneath the *page*.
  53737. **
  53738. ** The right-most entry is the one with the largest key - the last
  53739. ** key in ascending order.
  53740. */
  53741. static int moveToRightmost(BtCursor *pCur){
  53742. Pgno pgno;
  53743. int rc = SQLITE_OK;
  53744. MemPage *pPage = 0;
  53745. assert( cursorHoldsMutex(pCur) );
  53746. assert( pCur->eState==CURSOR_VALID );
  53747. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53748. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53749. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  53750. rc = moveToChild(pCur, pgno);
  53751. }
  53752. if( rc==SQLITE_OK ){
  53753. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  53754. pCur->info.nSize = 0;
  53755. pCur->validNKey = 0;
  53756. }
  53757. return rc;
  53758. }
  53759. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  53760. ** on success. Set *pRes to 0 if the cursor actually points to something
  53761. ** or set *pRes to 1 if the table is empty.
  53762. */
  53763. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  53764. int rc;
  53765. assert( cursorHoldsMutex(pCur) );
  53766. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53767. rc = moveToRoot(pCur);
  53768. if( rc==SQLITE_OK ){
  53769. if( pCur->eState==CURSOR_INVALID ){
  53770. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53771. *pRes = 1;
  53772. }else{
  53773. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  53774. *pRes = 0;
  53775. rc = moveToLeftmost(pCur);
  53776. }
  53777. }
  53778. return rc;
  53779. }
  53780. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  53781. ** on success. Set *pRes to 0 if the cursor actually points to something
  53782. ** or set *pRes to 1 if the table is empty.
  53783. */
  53784. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  53785. int rc;
  53786. assert( cursorHoldsMutex(pCur) );
  53787. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53788. /* If the cursor already points to the last entry, this is a no-op. */
  53789. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  53790. #ifdef SQLITE_DEBUG
  53791. /* This block serves to assert() that the cursor really does point
  53792. ** to the last entry in the b-tree. */
  53793. int ii;
  53794. for(ii=0; ii<pCur->iPage; ii++){
  53795. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  53796. }
  53797. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  53798. assert( pCur->apPage[pCur->iPage]->leaf );
  53799. #endif
  53800. return SQLITE_OK;
  53801. }
  53802. rc = moveToRoot(pCur);
  53803. if( rc==SQLITE_OK ){
  53804. if( CURSOR_INVALID==pCur->eState ){
  53805. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53806. *pRes = 1;
  53807. }else{
  53808. assert( pCur->eState==CURSOR_VALID );
  53809. *pRes = 0;
  53810. rc = moveToRightmost(pCur);
  53811. pCur->atLast = rc==SQLITE_OK ?1:0;
  53812. }
  53813. }
  53814. return rc;
  53815. }
  53816. /* Move the cursor so that it points to an entry near the key
  53817. ** specified by pIdxKey or intKey. Return a success code.
  53818. **
  53819. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  53820. ** must be NULL. For index tables, pIdxKey is used and intKey
  53821. ** is ignored.
  53822. **
  53823. ** If an exact match is not found, then the cursor is always
  53824. ** left pointing at a leaf page which would hold the entry if it
  53825. ** were present. The cursor might point to an entry that comes
  53826. ** before or after the key.
  53827. **
  53828. ** An integer is written into *pRes which is the result of
  53829. ** comparing the key with the entry to which the cursor is
  53830. ** pointing. The meaning of the integer written into
  53831. ** *pRes is as follows:
  53832. **
  53833. ** *pRes<0 The cursor is left pointing at an entry that
  53834. ** is smaller than intKey/pIdxKey or if the table is empty
  53835. ** and the cursor is therefore left point to nothing.
  53836. **
  53837. ** *pRes==0 The cursor is left pointing at an entry that
  53838. ** exactly matches intKey/pIdxKey.
  53839. **
  53840. ** *pRes>0 The cursor is left pointing at an entry that
  53841. ** is larger than intKey/pIdxKey.
  53842. **
  53843. */
  53844. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  53845. BtCursor *pCur, /* The cursor to be moved */
  53846. UnpackedRecord *pIdxKey, /* Unpacked index key */
  53847. i64 intKey, /* The table key */
  53848. int biasRight, /* If true, bias the search to the high end */
  53849. int *pRes /* Write search results here */
  53850. ){
  53851. int rc;
  53852. assert( cursorHoldsMutex(pCur) );
  53853. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53854. assert( pRes );
  53855. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  53856. /* If the cursor is already positioned at the point we are trying
  53857. ** to move to, then just return without doing any work */
  53858. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  53859. && pCur->apPage[0]->intKey
  53860. ){
  53861. if( pCur->info.nKey==intKey ){
  53862. *pRes = 0;
  53863. return SQLITE_OK;
  53864. }
  53865. if( pCur->atLast && pCur->info.nKey<intKey ){
  53866. *pRes = -1;
  53867. return SQLITE_OK;
  53868. }
  53869. }
  53870. rc = moveToRoot(pCur);
  53871. if( rc ){
  53872. return rc;
  53873. }
  53874. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  53875. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  53876. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  53877. if( pCur->eState==CURSOR_INVALID ){
  53878. *pRes = -1;
  53879. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53880. return SQLITE_OK;
  53881. }
  53882. assert( pCur->apPage[0]->intKey || pIdxKey );
  53883. for(;;){
  53884. int lwr, upr, idx;
  53885. Pgno chldPg;
  53886. MemPage *pPage = pCur->apPage[pCur->iPage];
  53887. int c;
  53888. /* pPage->nCell must be greater than zero. If this is the root-page
  53889. ** the cursor would have been INVALID above and this for(;;) loop
  53890. ** not run. If this is not the root-page, then the moveToChild() routine
  53891. ** would have already detected db corruption. Similarly, pPage must
  53892. ** be the right kind (index or table) of b-tree page. Otherwise
  53893. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  53894. assert( pPage->nCell>0 );
  53895. assert( pPage->intKey==(pIdxKey==0) );
  53896. lwr = 0;
  53897. upr = pPage->nCell-1;
  53898. if( biasRight ){
  53899. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  53900. }else{
  53901. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  53902. }
  53903. for(;;){
  53904. u8 *pCell; /* Pointer to current cell in pPage */
  53905. assert( idx==pCur->aiIdx[pCur->iPage] );
  53906. pCur->info.nSize = 0;
  53907. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53908. if( pPage->intKey ){
  53909. i64 nCellKey;
  53910. if( pPage->hasData ){
  53911. u32 dummy;
  53912. pCell += getVarint32(pCell, dummy);
  53913. }
  53914. getVarint(pCell, (u64*)&nCellKey);
  53915. if( nCellKey==intKey ){
  53916. c = 0;
  53917. }else if( nCellKey<intKey ){
  53918. c = -1;
  53919. }else{
  53920. assert( nCellKey>intKey );
  53921. c = +1;
  53922. }
  53923. pCur->validNKey = 1;
  53924. pCur->info.nKey = nCellKey;
  53925. }else{
  53926. /* The maximum supported page-size is 65536 bytes. This means that
  53927. ** the maximum number of record bytes stored on an index B-Tree
  53928. ** page is less than 16384 bytes and may be stored as a 2-byte
  53929. ** varint. This information is used to attempt to avoid parsing
  53930. ** the entire cell by checking for the cases where the record is
  53931. ** stored entirely within the b-tree page by inspecting the first
  53932. ** 2 bytes of the cell.
  53933. */
  53934. int nCell = pCell[0];
  53935. if( nCell<=pPage->max1bytePayload
  53936. /* && (pCell+nCell)<pPage->aDataEnd */
  53937. ){
  53938. /* This branch runs if the record-size field of the cell is a
  53939. ** single byte varint and the record fits entirely on the main
  53940. ** b-tree page. */
  53941. testcase( pCell+nCell+1==pPage->aDataEnd );
  53942. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  53943. }else if( !(pCell[1] & 0x80)
  53944. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  53945. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  53946. ){
  53947. /* The record-size field is a 2 byte varint and the record
  53948. ** fits entirely on the main b-tree page. */
  53949. testcase( pCell+nCell+2==pPage->aDataEnd );
  53950. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  53951. }else{
  53952. /* The record flows over onto one or more overflow pages. In
  53953. ** this case the whole cell needs to be parsed, a buffer allocated
  53954. ** and accessPayload() used to retrieve the record into the
  53955. ** buffer before VdbeRecordCompare() can be called. */
  53956. void *pCellKey;
  53957. u8 * const pCellBody = pCell - pPage->childPtrSize;
  53958. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  53959. nCell = (int)pCur->info.nKey;
  53960. pCellKey = sqlite3Malloc( nCell );
  53961. if( pCellKey==0 ){
  53962. rc = SQLITE_NOMEM;
  53963. goto moveto_finish;
  53964. }
  53965. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  53966. if( rc ){
  53967. sqlite3_free(pCellKey);
  53968. goto moveto_finish;
  53969. }
  53970. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  53971. sqlite3_free(pCellKey);
  53972. }
  53973. }
  53974. if( c==0 ){
  53975. if( pPage->intKey && !pPage->leaf ){
  53976. lwr = idx;
  53977. break;
  53978. }else{
  53979. *pRes = 0;
  53980. rc = SQLITE_OK;
  53981. goto moveto_finish;
  53982. }
  53983. }
  53984. if( c<0 ){
  53985. lwr = idx+1;
  53986. }else{
  53987. upr = idx-1;
  53988. }
  53989. if( lwr>upr ){
  53990. break;
  53991. }
  53992. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  53993. }
  53994. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  53995. assert( pPage->isInit );
  53996. if( pPage->leaf ){
  53997. chldPg = 0;
  53998. }else if( lwr>=pPage->nCell ){
  53999. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54000. }else{
  54001. chldPg = get4byte(findCell(pPage, lwr));
  54002. }
  54003. if( chldPg==0 ){
  54004. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  54005. *pRes = c;
  54006. rc = SQLITE_OK;
  54007. goto moveto_finish;
  54008. }
  54009. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  54010. pCur->info.nSize = 0;
  54011. pCur->validNKey = 0;
  54012. rc = moveToChild(pCur, chldPg);
  54013. if( rc ) goto moveto_finish;
  54014. }
  54015. moveto_finish:
  54016. return rc;
  54017. }
  54018. /*
  54019. ** Return TRUE if the cursor is not pointing at an entry of the table.
  54020. **
  54021. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  54022. ** past the last entry in the table or sqlite3BtreePrev() moves past
  54023. ** the first entry. TRUE is also returned if the table is empty.
  54024. */
  54025. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  54026. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  54027. ** have been deleted? This API will need to change to return an error code
  54028. ** as well as the boolean result value.
  54029. */
  54030. return (CURSOR_VALID!=pCur->eState);
  54031. }
  54032. /*
  54033. ** Advance the cursor to the next entry in the database. If
  54034. ** successful then set *pRes=0. If the cursor
  54035. ** was already pointing to the last entry in the database before
  54036. ** this routine was called, then set *pRes=1.
  54037. */
  54038. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  54039. int rc;
  54040. int idx;
  54041. MemPage *pPage;
  54042. assert( cursorHoldsMutex(pCur) );
  54043. assert( pRes!=0 );
  54044. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54045. if( pCur->eState!=CURSOR_VALID ){
  54046. rc = restoreCursorPosition(pCur);
  54047. if( rc!=SQLITE_OK ){
  54048. *pRes = 0;
  54049. return rc;
  54050. }
  54051. if( CURSOR_INVALID==pCur->eState ){
  54052. *pRes = 1;
  54053. return SQLITE_OK;
  54054. }
  54055. if( pCur->skipNext ){
  54056. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54057. pCur->eState = CURSOR_VALID;
  54058. if( pCur->skipNext>0 ){
  54059. pCur->skipNext = 0;
  54060. *pRes = 0;
  54061. return SQLITE_OK;
  54062. }
  54063. pCur->skipNext = 0;
  54064. }
  54065. }
  54066. pPage = pCur->apPage[pCur->iPage];
  54067. idx = ++pCur->aiIdx[pCur->iPage];
  54068. assert( pPage->isInit );
  54069. /* If the database file is corrupt, it is possible for the value of idx
  54070. ** to be invalid here. This can only occur if a second cursor modifies
  54071. ** the page while cursor pCur is holding a reference to it. Which can
  54072. ** only happen if the database is corrupt in such a way as to link the
  54073. ** page into more than one b-tree structure. */
  54074. testcase( idx>pPage->nCell );
  54075. pCur->info.nSize = 0;
  54076. pCur->validNKey = 0;
  54077. if( idx>=pPage->nCell ){
  54078. if( !pPage->leaf ){
  54079. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  54080. if( rc ){
  54081. *pRes = 0;
  54082. return rc;
  54083. }
  54084. rc = moveToLeftmost(pCur);
  54085. *pRes = 0;
  54086. return rc;
  54087. }
  54088. do{
  54089. if( pCur->iPage==0 ){
  54090. *pRes = 1;
  54091. pCur->eState = CURSOR_INVALID;
  54092. return SQLITE_OK;
  54093. }
  54094. moveToParent(pCur);
  54095. pPage = pCur->apPage[pCur->iPage];
  54096. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  54097. *pRes = 0;
  54098. if( pPage->intKey ){
  54099. rc = sqlite3BtreeNext(pCur, pRes);
  54100. }else{
  54101. rc = SQLITE_OK;
  54102. }
  54103. return rc;
  54104. }
  54105. *pRes = 0;
  54106. if( pPage->leaf ){
  54107. return SQLITE_OK;
  54108. }
  54109. rc = moveToLeftmost(pCur);
  54110. return rc;
  54111. }
  54112. /*
  54113. ** Step the cursor to the back to the previous entry in the database. If
  54114. ** successful then set *pRes=0. If the cursor
  54115. ** was already pointing to the first entry in the database before
  54116. ** this routine was called, then set *pRes=1.
  54117. */
  54118. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  54119. int rc;
  54120. MemPage *pPage;
  54121. assert( cursorHoldsMutex(pCur) );
  54122. assert( pRes!=0 );
  54123. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54124. pCur->atLast = 0;
  54125. if( pCur->eState!=CURSOR_VALID ){
  54126. if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
  54127. rc = btreeRestoreCursorPosition(pCur);
  54128. if( rc!=SQLITE_OK ){
  54129. *pRes = 0;
  54130. return rc;
  54131. }
  54132. }
  54133. if( CURSOR_INVALID==pCur->eState ){
  54134. *pRes = 1;
  54135. return SQLITE_OK;
  54136. }
  54137. if( pCur->skipNext ){
  54138. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54139. pCur->eState = CURSOR_VALID;
  54140. if( pCur->skipNext<0 ){
  54141. pCur->skipNext = 0;
  54142. *pRes = 0;
  54143. return SQLITE_OK;
  54144. }
  54145. pCur->skipNext = 0;
  54146. }
  54147. }
  54148. pPage = pCur->apPage[pCur->iPage];
  54149. assert( pPage->isInit );
  54150. if( !pPage->leaf ){
  54151. int idx = pCur->aiIdx[pCur->iPage];
  54152. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  54153. if( rc ){
  54154. *pRes = 0;
  54155. return rc;
  54156. }
  54157. rc = moveToRightmost(pCur);
  54158. }else{
  54159. while( pCur->aiIdx[pCur->iPage]==0 ){
  54160. if( pCur->iPage==0 ){
  54161. pCur->eState = CURSOR_INVALID;
  54162. *pRes = 1;
  54163. return SQLITE_OK;
  54164. }
  54165. moveToParent(pCur);
  54166. }
  54167. pCur->info.nSize = 0;
  54168. pCur->validNKey = 0;
  54169. pCur->aiIdx[pCur->iPage]--;
  54170. pPage = pCur->apPage[pCur->iPage];
  54171. if( pPage->intKey && !pPage->leaf ){
  54172. rc = sqlite3BtreePrevious(pCur, pRes);
  54173. }else{
  54174. rc = SQLITE_OK;
  54175. }
  54176. }
  54177. *pRes = 0;
  54178. return rc;
  54179. }
  54180. /*
  54181. ** Allocate a new page from the database file.
  54182. **
  54183. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  54184. ** has already been called on the new page.) The new page has also
  54185. ** been referenced and the calling routine is responsible for calling
  54186. ** sqlite3PagerUnref() on the new page when it is done.
  54187. **
  54188. ** SQLITE_OK is returned on success. Any other return value indicates
  54189. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  54190. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  54191. **
  54192. ** If the "nearby" parameter is not 0, then an effort is made to
  54193. ** locate a page close to the page number "nearby". This can be used in an
  54194. ** attempt to keep related pages close to each other in the database file,
  54195. ** which in turn can make database access faster.
  54196. **
  54197. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  54198. ** anywhere on the free-list, then it is guaranteed to be returned. If
  54199. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  54200. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  54201. ** are no restrictions on which page is returned.
  54202. */
  54203. static int allocateBtreePage(
  54204. BtShared *pBt, /* The btree */
  54205. MemPage **ppPage, /* Store pointer to the allocated page here */
  54206. Pgno *pPgno, /* Store the page number here */
  54207. Pgno nearby, /* Search for a page near this one */
  54208. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  54209. ){
  54210. MemPage *pPage1;
  54211. int rc;
  54212. u32 n; /* Number of pages on the freelist */
  54213. u32 k; /* Number of leaves on the trunk of the freelist */
  54214. MemPage *pTrunk = 0;
  54215. MemPage *pPrevTrunk = 0;
  54216. Pgno mxPage; /* Total size of the database file */
  54217. assert( sqlite3_mutex_held(pBt->mutex) );
  54218. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  54219. pPage1 = pBt->pPage1;
  54220. mxPage = btreePagecount(pBt);
  54221. n = get4byte(&pPage1->aData[36]);
  54222. testcase( n==mxPage-1 );
  54223. if( n>=mxPage ){
  54224. return SQLITE_CORRUPT_BKPT;
  54225. }
  54226. if( n>0 ){
  54227. /* There are pages on the freelist. Reuse one of those pages. */
  54228. Pgno iTrunk;
  54229. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  54230. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  54231. ** shows that the page 'nearby' is somewhere on the free-list, then
  54232. ** the entire-list will be searched for that page.
  54233. */
  54234. #ifndef SQLITE_OMIT_AUTOVACUUM
  54235. if( eMode==BTALLOC_EXACT ){
  54236. if( nearby<=mxPage ){
  54237. u8 eType;
  54238. assert( nearby>0 );
  54239. assert( pBt->autoVacuum );
  54240. rc = ptrmapGet(pBt, nearby, &eType, 0);
  54241. if( rc ) return rc;
  54242. if( eType==PTRMAP_FREEPAGE ){
  54243. searchList = 1;
  54244. }
  54245. }
  54246. }else if( eMode==BTALLOC_LE ){
  54247. searchList = 1;
  54248. }
  54249. #endif
  54250. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  54251. ** first free-list trunk page. iPrevTrunk is initially 1.
  54252. */
  54253. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54254. if( rc ) return rc;
  54255. put4byte(&pPage1->aData[36], n-1);
  54256. /* The code within this loop is run only once if the 'searchList' variable
  54257. ** is not true. Otherwise, it runs once for each trunk-page on the
  54258. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  54259. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  54260. */
  54261. do {
  54262. pPrevTrunk = pTrunk;
  54263. if( pPrevTrunk ){
  54264. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  54265. }else{
  54266. iTrunk = get4byte(&pPage1->aData[32]);
  54267. }
  54268. testcase( iTrunk==mxPage );
  54269. if( iTrunk>mxPage ){
  54270. rc = SQLITE_CORRUPT_BKPT;
  54271. }else{
  54272. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54273. }
  54274. if( rc ){
  54275. pTrunk = 0;
  54276. goto end_allocate_page;
  54277. }
  54278. assert( pTrunk!=0 );
  54279. assert( pTrunk->aData!=0 );
  54280. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  54281. if( k==0 && !searchList ){
  54282. /* The trunk has no leaves and the list is not being searched.
  54283. ** So extract the trunk page itself and use it as the newly
  54284. ** allocated page */
  54285. assert( pPrevTrunk==0 );
  54286. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54287. if( rc ){
  54288. goto end_allocate_page;
  54289. }
  54290. *pPgno = iTrunk;
  54291. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54292. *ppPage = pTrunk;
  54293. pTrunk = 0;
  54294. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54295. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  54296. /* Value of k is out of range. Database corruption */
  54297. rc = SQLITE_CORRUPT_BKPT;
  54298. goto end_allocate_page;
  54299. #ifndef SQLITE_OMIT_AUTOVACUUM
  54300. }else if( searchList
  54301. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  54302. ){
  54303. /* The list is being searched and this trunk page is the page
  54304. ** to allocate, regardless of whether it has leaves.
  54305. */
  54306. *pPgno = iTrunk;
  54307. *ppPage = pTrunk;
  54308. searchList = 0;
  54309. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54310. if( rc ){
  54311. goto end_allocate_page;
  54312. }
  54313. if( k==0 ){
  54314. if( !pPrevTrunk ){
  54315. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54316. }else{
  54317. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54318. if( rc!=SQLITE_OK ){
  54319. goto end_allocate_page;
  54320. }
  54321. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  54322. }
  54323. }else{
  54324. /* The trunk page is required by the caller but it contains
  54325. ** pointers to free-list leaves. The first leaf becomes a trunk
  54326. ** page in this case.
  54327. */
  54328. MemPage *pNewTrunk;
  54329. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  54330. if( iNewTrunk>mxPage ){
  54331. rc = SQLITE_CORRUPT_BKPT;
  54332. goto end_allocate_page;
  54333. }
  54334. testcase( iNewTrunk==mxPage );
  54335. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  54336. if( rc!=SQLITE_OK ){
  54337. goto end_allocate_page;
  54338. }
  54339. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  54340. if( rc!=SQLITE_OK ){
  54341. releasePage(pNewTrunk);
  54342. goto end_allocate_page;
  54343. }
  54344. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  54345. put4byte(&pNewTrunk->aData[4], k-1);
  54346. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  54347. releasePage(pNewTrunk);
  54348. if( !pPrevTrunk ){
  54349. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  54350. put4byte(&pPage1->aData[32], iNewTrunk);
  54351. }else{
  54352. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54353. if( rc ){
  54354. goto end_allocate_page;
  54355. }
  54356. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  54357. }
  54358. }
  54359. pTrunk = 0;
  54360. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54361. #endif
  54362. }else if( k>0 ){
  54363. /* Extract a leaf from the trunk */
  54364. u32 closest;
  54365. Pgno iPage;
  54366. unsigned char *aData = pTrunk->aData;
  54367. if( nearby>0 ){
  54368. u32 i;
  54369. closest = 0;
  54370. if( eMode==BTALLOC_LE ){
  54371. for(i=0; i<k; i++){
  54372. iPage = get4byte(&aData[8+i*4]);
  54373. if( iPage<=nearby ){
  54374. closest = i;
  54375. break;
  54376. }
  54377. }
  54378. }else{
  54379. int dist;
  54380. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  54381. for(i=1; i<k; i++){
  54382. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  54383. if( d2<dist ){
  54384. closest = i;
  54385. dist = d2;
  54386. }
  54387. }
  54388. }
  54389. }else{
  54390. closest = 0;
  54391. }
  54392. iPage = get4byte(&aData[8+closest*4]);
  54393. testcase( iPage==mxPage );
  54394. if( iPage>mxPage ){
  54395. rc = SQLITE_CORRUPT_BKPT;
  54396. goto end_allocate_page;
  54397. }
  54398. testcase( iPage==mxPage );
  54399. if( !searchList
  54400. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  54401. ){
  54402. int noContent;
  54403. *pPgno = iPage;
  54404. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  54405. ": %d more free pages\n",
  54406. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  54407. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54408. if( rc ) goto end_allocate_page;
  54409. if( closest<k-1 ){
  54410. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  54411. }
  54412. put4byte(&aData[4], k-1);
  54413. noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
  54414. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  54415. if( rc==SQLITE_OK ){
  54416. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54417. if( rc!=SQLITE_OK ){
  54418. releasePage(*ppPage);
  54419. }
  54420. }
  54421. searchList = 0;
  54422. }
  54423. }
  54424. releasePage(pPrevTrunk);
  54425. pPrevTrunk = 0;
  54426. }while( searchList );
  54427. }else{
  54428. /* There are no pages on the freelist, so append a new page to the
  54429. ** database image.
  54430. **
  54431. ** Normally, new pages allocated by this block can be requested from the
  54432. ** pager layer with the 'no-content' flag set. This prevents the pager
  54433. ** from trying to read the pages content from disk. However, if the
  54434. ** current transaction has already run one or more incremental-vacuum
  54435. ** steps, then the page we are about to allocate may contain content
  54436. ** that is required in the event of a rollback. In this case, do
  54437. ** not set the no-content flag. This causes the pager to load and journal
  54438. ** the current page content before overwriting it.
  54439. **
  54440. ** Note that the pager will not actually attempt to load or journal
  54441. ** content for any page that really does lie past the end of the database
  54442. ** file on disk. So the effects of disabling the no-content optimization
  54443. ** here are confined to those pages that lie between the end of the
  54444. ** database image and the end of the database file.
  54445. */
  54446. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
  54447. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54448. if( rc ) return rc;
  54449. pBt->nPage++;
  54450. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  54451. #ifndef SQLITE_OMIT_AUTOVACUUM
  54452. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  54453. /* If *pPgno refers to a pointer-map page, allocate two new pages
  54454. ** at the end of the file instead of one. The first allocated page
  54455. ** becomes a new pointer-map page, the second is used by the caller.
  54456. */
  54457. MemPage *pPg = 0;
  54458. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  54459. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  54460. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  54461. if( rc==SQLITE_OK ){
  54462. rc = sqlite3PagerWrite(pPg->pDbPage);
  54463. releasePage(pPg);
  54464. }
  54465. if( rc ) return rc;
  54466. pBt->nPage++;
  54467. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  54468. }
  54469. #endif
  54470. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  54471. *pPgno = pBt->nPage;
  54472. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54473. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  54474. if( rc ) return rc;
  54475. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54476. if( rc!=SQLITE_OK ){
  54477. releasePage(*ppPage);
  54478. }
  54479. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  54480. }
  54481. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54482. end_allocate_page:
  54483. releasePage(pTrunk);
  54484. releasePage(pPrevTrunk);
  54485. if( rc==SQLITE_OK ){
  54486. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  54487. releasePage(*ppPage);
  54488. return SQLITE_CORRUPT_BKPT;
  54489. }
  54490. (*ppPage)->isInit = 0;
  54491. }else{
  54492. *ppPage = 0;
  54493. }
  54494. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  54495. return rc;
  54496. }
  54497. /*
  54498. ** This function is used to add page iPage to the database file free-list.
  54499. ** It is assumed that the page is not already a part of the free-list.
  54500. **
  54501. ** The value passed as the second argument to this function is optional.
  54502. ** If the caller happens to have a pointer to the MemPage object
  54503. ** corresponding to page iPage handy, it may pass it as the second value.
  54504. ** Otherwise, it may pass NULL.
  54505. **
  54506. ** If a pointer to a MemPage object is passed as the second argument,
  54507. ** its reference count is not altered by this function.
  54508. */
  54509. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  54510. MemPage *pTrunk = 0; /* Free-list trunk page */
  54511. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  54512. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  54513. MemPage *pPage; /* Page being freed. May be NULL. */
  54514. int rc; /* Return Code */
  54515. int nFree; /* Initial number of pages on free-list */
  54516. assert( sqlite3_mutex_held(pBt->mutex) );
  54517. assert( iPage>1 );
  54518. assert( !pMemPage || pMemPage->pgno==iPage );
  54519. if( pMemPage ){
  54520. pPage = pMemPage;
  54521. sqlite3PagerRef(pPage->pDbPage);
  54522. }else{
  54523. pPage = btreePageLookup(pBt, iPage);
  54524. }
  54525. /* Increment the free page count on pPage1 */
  54526. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54527. if( rc ) goto freepage_out;
  54528. nFree = get4byte(&pPage1->aData[36]);
  54529. put4byte(&pPage1->aData[36], nFree+1);
  54530. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  54531. /* If the secure_delete option is enabled, then
  54532. ** always fully overwrite deleted information with zeros.
  54533. */
  54534. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  54535. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  54536. ){
  54537. goto freepage_out;
  54538. }
  54539. memset(pPage->aData, 0, pPage->pBt->pageSize);
  54540. }
  54541. /* If the database supports auto-vacuum, write an entry in the pointer-map
  54542. ** to indicate that the page is free.
  54543. */
  54544. if( ISAUTOVACUUM ){
  54545. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  54546. if( rc ) goto freepage_out;
  54547. }
  54548. /* Now manipulate the actual database free-list structure. There are two
  54549. ** possibilities. If the free-list is currently empty, or if the first
  54550. ** trunk page in the free-list is full, then this page will become a
  54551. ** new free-list trunk page. Otherwise, it will become a leaf of the
  54552. ** first trunk page in the current free-list. This block tests if it
  54553. ** is possible to add the page as a new free-list leaf.
  54554. */
  54555. if( nFree!=0 ){
  54556. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  54557. iTrunk = get4byte(&pPage1->aData[32]);
  54558. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54559. if( rc!=SQLITE_OK ){
  54560. goto freepage_out;
  54561. }
  54562. nLeaf = get4byte(&pTrunk->aData[4]);
  54563. assert( pBt->usableSize>32 );
  54564. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  54565. rc = SQLITE_CORRUPT_BKPT;
  54566. goto freepage_out;
  54567. }
  54568. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  54569. /* In this case there is room on the trunk page to insert the page
  54570. ** being freed as a new leaf.
  54571. **
  54572. ** Note that the trunk page is not really full until it contains
  54573. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  54574. ** coded. But due to a coding error in versions of SQLite prior to
  54575. ** 3.6.0, databases with freelist trunk pages holding more than
  54576. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  54577. ** to maintain backwards compatibility with older versions of SQLite,
  54578. ** we will continue to restrict the number of entries to usableSize/4 - 8
  54579. ** for now. At some point in the future (once everyone has upgraded
  54580. ** to 3.6.0 or later) we should consider fixing the conditional above
  54581. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  54582. */
  54583. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54584. if( rc==SQLITE_OK ){
  54585. put4byte(&pTrunk->aData[4], nLeaf+1);
  54586. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  54587. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  54588. sqlite3PagerDontWrite(pPage->pDbPage);
  54589. }
  54590. rc = btreeSetHasContent(pBt, iPage);
  54591. }
  54592. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  54593. goto freepage_out;
  54594. }
  54595. }
  54596. /* If control flows to this point, then it was not possible to add the
  54597. ** the page being freed as a leaf page of the first trunk in the free-list.
  54598. ** Possibly because the free-list is empty, or possibly because the
  54599. ** first trunk in the free-list is full. Either way, the page being freed
  54600. ** will become the new first trunk page in the free-list.
  54601. */
  54602. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  54603. goto freepage_out;
  54604. }
  54605. rc = sqlite3PagerWrite(pPage->pDbPage);
  54606. if( rc!=SQLITE_OK ){
  54607. goto freepage_out;
  54608. }
  54609. put4byte(pPage->aData, iTrunk);
  54610. put4byte(&pPage->aData[4], 0);
  54611. put4byte(&pPage1->aData[32], iPage);
  54612. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  54613. freepage_out:
  54614. if( pPage ){
  54615. pPage->isInit = 0;
  54616. }
  54617. releasePage(pPage);
  54618. releasePage(pTrunk);
  54619. return rc;
  54620. }
  54621. static void freePage(MemPage *pPage, int *pRC){
  54622. if( (*pRC)==SQLITE_OK ){
  54623. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  54624. }
  54625. }
  54626. /*
  54627. ** Free any overflow pages associated with the given Cell.
  54628. */
  54629. static int clearCell(MemPage *pPage, unsigned char *pCell){
  54630. BtShared *pBt = pPage->pBt;
  54631. CellInfo info;
  54632. Pgno ovflPgno;
  54633. int rc;
  54634. int nOvfl;
  54635. u32 ovflPageSize;
  54636. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54637. btreeParseCellPtr(pPage, pCell, &info);
  54638. if( info.iOverflow==0 ){
  54639. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  54640. }
  54641. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  54642. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  54643. }
  54644. ovflPgno = get4byte(&pCell[info.iOverflow]);
  54645. assert( pBt->usableSize > 4 );
  54646. ovflPageSize = pBt->usableSize - 4;
  54647. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  54648. assert( ovflPgno==0 || nOvfl>0 );
  54649. while( nOvfl-- ){
  54650. Pgno iNext = 0;
  54651. MemPage *pOvfl = 0;
  54652. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  54653. /* 0 is not a legal page number and page 1 cannot be an
  54654. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  54655. ** file the database must be corrupt. */
  54656. return SQLITE_CORRUPT_BKPT;
  54657. }
  54658. if( nOvfl ){
  54659. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  54660. if( rc ) return rc;
  54661. }
  54662. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  54663. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  54664. ){
  54665. /* There is no reason any cursor should have an outstanding reference
  54666. ** to an overflow page belonging to a cell that is being deleted/updated.
  54667. ** So if there exists more than one reference to this page, then it
  54668. ** must not really be an overflow page and the database must be corrupt.
  54669. ** It is helpful to detect this before calling freePage2(), as
  54670. ** freePage2() may zero the page contents if secure-delete mode is
  54671. ** enabled. If this 'overflow' page happens to be a page that the
  54672. ** caller is iterating through or using in some other way, this
  54673. ** can be problematic.
  54674. */
  54675. rc = SQLITE_CORRUPT_BKPT;
  54676. }else{
  54677. rc = freePage2(pBt, pOvfl, ovflPgno);
  54678. }
  54679. if( pOvfl ){
  54680. sqlite3PagerUnref(pOvfl->pDbPage);
  54681. }
  54682. if( rc ) return rc;
  54683. ovflPgno = iNext;
  54684. }
  54685. return SQLITE_OK;
  54686. }
  54687. /*
  54688. ** Create the byte sequence used to represent a cell on page pPage
  54689. ** and write that byte sequence into pCell[]. Overflow pages are
  54690. ** allocated and filled in as necessary. The calling procedure
  54691. ** is responsible for making sure sufficient space has been allocated
  54692. ** for pCell[].
  54693. **
  54694. ** Note that pCell does not necessary need to point to the pPage->aData
  54695. ** area. pCell might point to some temporary storage. The cell will
  54696. ** be constructed in this temporary area then copied into pPage->aData
  54697. ** later.
  54698. */
  54699. static int fillInCell(
  54700. MemPage *pPage, /* The page that contains the cell */
  54701. unsigned char *pCell, /* Complete text of the cell */
  54702. const void *pKey, i64 nKey, /* The key */
  54703. const void *pData,int nData, /* The data */
  54704. int nZero, /* Extra zero bytes to append to pData */
  54705. int *pnSize /* Write cell size here */
  54706. ){
  54707. int nPayload;
  54708. const u8 *pSrc;
  54709. int nSrc, n, rc;
  54710. int spaceLeft;
  54711. MemPage *pOvfl = 0;
  54712. MemPage *pToRelease = 0;
  54713. unsigned char *pPrior;
  54714. unsigned char *pPayload;
  54715. BtShared *pBt = pPage->pBt;
  54716. Pgno pgnoOvfl = 0;
  54717. int nHeader;
  54718. CellInfo info;
  54719. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54720. /* pPage is not necessarily writeable since pCell might be auxiliary
  54721. ** buffer space that is separate from the pPage buffer area */
  54722. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  54723. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54724. /* Fill in the header. */
  54725. nHeader = 0;
  54726. if( !pPage->leaf ){
  54727. nHeader += 4;
  54728. }
  54729. if( pPage->hasData ){
  54730. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  54731. }else{
  54732. nData = nZero = 0;
  54733. }
  54734. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  54735. btreeParseCellPtr(pPage, pCell, &info);
  54736. assert( info.nHeader==nHeader );
  54737. assert( info.nKey==nKey );
  54738. assert( info.nData==(u32)(nData+nZero) );
  54739. /* Fill in the payload */
  54740. nPayload = nData + nZero;
  54741. if( pPage->intKey ){
  54742. pSrc = pData;
  54743. nSrc = nData;
  54744. nData = 0;
  54745. }else{
  54746. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  54747. return SQLITE_CORRUPT_BKPT;
  54748. }
  54749. nPayload += (int)nKey;
  54750. pSrc = pKey;
  54751. nSrc = (int)nKey;
  54752. }
  54753. *pnSize = info.nSize;
  54754. spaceLeft = info.nLocal;
  54755. pPayload = &pCell[nHeader];
  54756. pPrior = &pCell[info.iOverflow];
  54757. while( nPayload>0 ){
  54758. if( spaceLeft==0 ){
  54759. #ifndef SQLITE_OMIT_AUTOVACUUM
  54760. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  54761. if( pBt->autoVacuum ){
  54762. do{
  54763. pgnoOvfl++;
  54764. } while(
  54765. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  54766. );
  54767. }
  54768. #endif
  54769. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  54770. #ifndef SQLITE_OMIT_AUTOVACUUM
  54771. /* If the database supports auto-vacuum, and the second or subsequent
  54772. ** overflow page is being allocated, add an entry to the pointer-map
  54773. ** for that page now.
  54774. **
  54775. ** If this is the first overflow page, then write a partial entry
  54776. ** to the pointer-map. If we write nothing to this pointer-map slot,
  54777. ** then the optimistic overflow chain processing in clearCell()
  54778. ** may misinterpret the uninitialized values and delete the
  54779. ** wrong pages from the database.
  54780. */
  54781. if( pBt->autoVacuum && rc==SQLITE_OK ){
  54782. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  54783. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  54784. if( rc ){
  54785. releasePage(pOvfl);
  54786. }
  54787. }
  54788. #endif
  54789. if( rc ){
  54790. releasePage(pToRelease);
  54791. return rc;
  54792. }
  54793. /* If pToRelease is not zero than pPrior points into the data area
  54794. ** of pToRelease. Make sure pToRelease is still writeable. */
  54795. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54796. /* If pPrior is part of the data area of pPage, then make sure pPage
  54797. ** is still writeable */
  54798. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  54799. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54800. put4byte(pPrior, pgnoOvfl);
  54801. releasePage(pToRelease);
  54802. pToRelease = pOvfl;
  54803. pPrior = pOvfl->aData;
  54804. put4byte(pPrior, 0);
  54805. pPayload = &pOvfl->aData[4];
  54806. spaceLeft = pBt->usableSize - 4;
  54807. }
  54808. n = nPayload;
  54809. if( n>spaceLeft ) n = spaceLeft;
  54810. /* If pToRelease is not zero than pPayload points into the data area
  54811. ** of pToRelease. Make sure pToRelease is still writeable. */
  54812. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54813. /* If pPayload is part of the data area of pPage, then make sure pPage
  54814. ** is still writeable */
  54815. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  54816. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54817. if( nSrc>0 ){
  54818. if( n>nSrc ) n = nSrc;
  54819. assert( pSrc );
  54820. memcpy(pPayload, pSrc, n);
  54821. }else{
  54822. memset(pPayload, 0, n);
  54823. }
  54824. nPayload -= n;
  54825. pPayload += n;
  54826. pSrc += n;
  54827. nSrc -= n;
  54828. spaceLeft -= n;
  54829. if( nSrc==0 ){
  54830. nSrc = nData;
  54831. pSrc = pData;
  54832. }
  54833. }
  54834. releasePage(pToRelease);
  54835. return SQLITE_OK;
  54836. }
  54837. /*
  54838. ** Remove the i-th cell from pPage. This routine effects pPage only.
  54839. ** The cell content is not freed or deallocated. It is assumed that
  54840. ** the cell content has been copied someplace else. This routine just
  54841. ** removes the reference to the cell from pPage.
  54842. **
  54843. ** "sz" must be the number of bytes in the cell.
  54844. */
  54845. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  54846. u32 pc; /* Offset to cell content of cell being deleted */
  54847. u8 *data; /* pPage->aData */
  54848. u8 *ptr; /* Used to move bytes around within data[] */
  54849. u8 *endPtr; /* End of loop */
  54850. int rc; /* The return code */
  54851. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  54852. if( *pRC ) return;
  54853. assert( idx>=0 && idx<pPage->nCell );
  54854. assert( sz==cellSize(pPage, idx) );
  54855. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54856. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54857. data = pPage->aData;
  54858. ptr = &pPage->aCellIdx[2*idx];
  54859. pc = get2byte(ptr);
  54860. hdr = pPage->hdrOffset;
  54861. testcase( pc==get2byte(&data[hdr+5]) );
  54862. testcase( pc+sz==pPage->pBt->usableSize );
  54863. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  54864. *pRC = SQLITE_CORRUPT_BKPT;
  54865. return;
  54866. }
  54867. rc = freeSpace(pPage, pc, sz);
  54868. if( rc ){
  54869. *pRC = rc;
  54870. return;
  54871. }
  54872. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  54873. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  54874. while( ptr<endPtr ){
  54875. *(u16*)ptr = *(u16*)&ptr[2];
  54876. ptr += 2;
  54877. }
  54878. pPage->nCell--;
  54879. put2byte(&data[hdr+3], pPage->nCell);
  54880. pPage->nFree += 2;
  54881. }
  54882. /*
  54883. ** Insert a new cell on pPage at cell index "i". pCell points to the
  54884. ** content of the cell.
  54885. **
  54886. ** If the cell content will fit on the page, then put it there. If it
  54887. ** will not fit, then make a copy of the cell content into pTemp if
  54888. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  54889. ** in pPage->apOvfl[] and make it point to the cell content (either
  54890. ** in pTemp or the original pCell) and also record its index.
  54891. ** Allocating a new entry in pPage->aCell[] implies that
  54892. ** pPage->nOverflow is incremented.
  54893. **
  54894. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  54895. ** cell. The caller will overwrite them after this function returns. If
  54896. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  54897. ** (but pCell+nSkip is always valid).
  54898. */
  54899. static void insertCell(
  54900. MemPage *pPage, /* Page into which we are copying */
  54901. int i, /* New cell becomes the i-th cell of the page */
  54902. u8 *pCell, /* Content of the new cell */
  54903. int sz, /* Bytes of content in pCell */
  54904. u8 *pTemp, /* Temp storage space for pCell, if needed */
  54905. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  54906. int *pRC /* Read and write return code from here */
  54907. ){
  54908. int idx = 0; /* Where to write new cell content in data[] */
  54909. int j; /* Loop counter */
  54910. int end; /* First byte past the last cell pointer in data[] */
  54911. int ins; /* Index in data[] where new cell pointer is inserted */
  54912. int cellOffset; /* Address of first cell pointer in data[] */
  54913. u8 *data; /* The content of the whole page */
  54914. u8 *ptr; /* Used for moving information around in data[] */
  54915. u8 *endPtr; /* End of the loop */
  54916. int nSkip = (iChild ? 4 : 0);
  54917. if( *pRC ) return;
  54918. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  54919. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  54920. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  54921. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  54922. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54923. /* The cell should normally be sized correctly. However, when moving a
  54924. ** malformed cell from a leaf page to an interior page, if the cell size
  54925. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  54926. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  54927. ** the term after the || in the following assert(). */
  54928. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  54929. if( pPage->nOverflow || sz+2>pPage->nFree ){
  54930. if( pTemp ){
  54931. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  54932. pCell = pTemp;
  54933. }
  54934. if( iChild ){
  54935. put4byte(pCell, iChild);
  54936. }
  54937. j = pPage->nOverflow++;
  54938. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  54939. pPage->apOvfl[j] = pCell;
  54940. pPage->aiOvfl[j] = (u16)i;
  54941. }else{
  54942. int rc = sqlite3PagerWrite(pPage->pDbPage);
  54943. if( rc!=SQLITE_OK ){
  54944. *pRC = rc;
  54945. return;
  54946. }
  54947. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54948. data = pPage->aData;
  54949. cellOffset = pPage->cellOffset;
  54950. end = cellOffset + 2*pPage->nCell;
  54951. ins = cellOffset + 2*i;
  54952. rc = allocateSpace(pPage, sz, &idx);
  54953. if( rc ){ *pRC = rc; return; }
  54954. /* The allocateSpace() routine guarantees the following two properties
  54955. ** if it returns success */
  54956. assert( idx >= end+2 );
  54957. assert( idx+sz <= (int)pPage->pBt->usableSize );
  54958. pPage->nCell++;
  54959. pPage->nFree -= (u16)(2 + sz);
  54960. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  54961. if( iChild ){
  54962. put4byte(&data[idx], iChild);
  54963. }
  54964. ptr = &data[end];
  54965. endPtr = &data[ins];
  54966. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  54967. while( ptr>endPtr ){
  54968. *(u16*)ptr = *(u16*)&ptr[-2];
  54969. ptr -= 2;
  54970. }
  54971. put2byte(&data[ins], idx);
  54972. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  54973. #ifndef SQLITE_OMIT_AUTOVACUUM
  54974. if( pPage->pBt->autoVacuum ){
  54975. /* The cell may contain a pointer to an overflow page. If so, write
  54976. ** the entry for the overflow page into the pointer map.
  54977. */
  54978. ptrmapPutOvflPtr(pPage, pCell, pRC);
  54979. }
  54980. #endif
  54981. }
  54982. }
  54983. /*
  54984. ** Add a list of cells to a page. The page should be initially empty.
  54985. ** The cells are guaranteed to fit on the page.
  54986. */
  54987. static void assemblePage(
  54988. MemPage *pPage, /* The page to be assemblied */
  54989. int nCell, /* The number of cells to add to this page */
  54990. u8 **apCell, /* Pointers to cell bodies */
  54991. u16 *aSize /* Sizes of the cells */
  54992. ){
  54993. int i; /* Loop counter */
  54994. u8 *pCellptr; /* Address of next cell pointer */
  54995. int cellbody; /* Address of next cell body */
  54996. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  54997. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  54998. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  54999. assert( pPage->nOverflow==0 );
  55000. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55001. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  55002. && (int)MX_CELL(pPage->pBt)<=10921);
  55003. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  55004. /* Check that the page has just been zeroed by zeroPage() */
  55005. assert( pPage->nCell==0 );
  55006. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  55007. pCellptr = &pPage->aCellIdx[nCell*2];
  55008. cellbody = nUsable;
  55009. for(i=nCell-1; i>=0; i--){
  55010. u16 sz = aSize[i];
  55011. pCellptr -= 2;
  55012. cellbody -= sz;
  55013. put2byte(pCellptr, cellbody);
  55014. memcpy(&data[cellbody], apCell[i], sz);
  55015. }
  55016. put2byte(&data[hdr+3], nCell);
  55017. put2byte(&data[hdr+5], cellbody);
  55018. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  55019. pPage->nCell = (u16)nCell;
  55020. }
  55021. /*
  55022. ** The following parameters determine how many adjacent pages get involved
  55023. ** in a balancing operation. NN is the number of neighbors on either side
  55024. ** of the page that participate in the balancing operation. NB is the
  55025. ** total number of pages that participate, including the target page and
  55026. ** NN neighbors on either side.
  55027. **
  55028. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  55029. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  55030. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  55031. ** The value of NN appears to give the best results overall.
  55032. */
  55033. #define NN 1 /* Number of neighbors on either side of pPage */
  55034. #define NB (NN*2+1) /* Total pages involved in the balance */
  55035. #ifndef SQLITE_OMIT_QUICKBALANCE
  55036. /*
  55037. ** This version of balance() handles the common special case where
  55038. ** a new entry is being inserted on the extreme right-end of the
  55039. ** tree, in other words, when the new entry will become the largest
  55040. ** entry in the tree.
  55041. **
  55042. ** Instead of trying to balance the 3 right-most leaf pages, just add
  55043. ** a new page to the right-hand side and put the one new entry in
  55044. ** that page. This leaves the right side of the tree somewhat
  55045. ** unbalanced. But odds are that we will be inserting new entries
  55046. ** at the end soon afterwards so the nearly empty page will quickly
  55047. ** fill up. On average.
  55048. **
  55049. ** pPage is the leaf page which is the right-most page in the tree.
  55050. ** pParent is its parent. pPage must have a single overflow entry
  55051. ** which is also the right-most entry on the page.
  55052. **
  55053. ** The pSpace buffer is used to store a temporary copy of the divider
  55054. ** cell that will be inserted into pParent. Such a cell consists of a 4
  55055. ** byte page number followed by a variable length integer. In other
  55056. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  55057. ** least 13 bytes in size.
  55058. */
  55059. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  55060. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  55061. MemPage *pNew; /* Newly allocated page */
  55062. int rc; /* Return Code */
  55063. Pgno pgnoNew; /* Page number of pNew */
  55064. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55065. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55066. assert( pPage->nOverflow==1 );
  55067. /* This error condition is now caught prior to reaching this function */
  55068. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  55069. /* Allocate a new page. This page will become the right-sibling of
  55070. ** pPage. Make the parent page writable, so that the new divider cell
  55071. ** may be inserted. If both these operations are successful, proceed.
  55072. */
  55073. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  55074. if( rc==SQLITE_OK ){
  55075. u8 *pOut = &pSpace[4];
  55076. u8 *pCell = pPage->apOvfl[0];
  55077. u16 szCell = cellSizePtr(pPage, pCell);
  55078. u8 *pStop;
  55079. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  55080. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  55081. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  55082. assemblePage(pNew, 1, &pCell, &szCell);
  55083. /* If this is an auto-vacuum database, update the pointer map
  55084. ** with entries for the new page, and any pointer from the
  55085. ** cell on the page to an overflow page. If either of these
  55086. ** operations fails, the return code is set, but the contents
  55087. ** of the parent page are still manipulated by thh code below.
  55088. ** That is Ok, at this point the parent page is guaranteed to
  55089. ** be marked as dirty. Returning an error code will cause a
  55090. ** rollback, undoing any changes made to the parent page.
  55091. */
  55092. if( ISAUTOVACUUM ){
  55093. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  55094. if( szCell>pNew->minLocal ){
  55095. ptrmapPutOvflPtr(pNew, pCell, &rc);
  55096. }
  55097. }
  55098. /* Create a divider cell to insert into pParent. The divider cell
  55099. ** consists of a 4-byte page number (the page number of pPage) and
  55100. ** a variable length key value (which must be the same value as the
  55101. ** largest key on pPage).
  55102. **
  55103. ** To find the largest key value on pPage, first find the right-most
  55104. ** cell on pPage. The first two fields of this cell are the
  55105. ** record-length (a variable length integer at most 32-bits in size)
  55106. ** and the key value (a variable length integer, may have any value).
  55107. ** The first of the while(...) loops below skips over the record-length
  55108. ** field. The second while(...) loop copies the key value from the
  55109. ** cell on pPage into the pSpace buffer.
  55110. */
  55111. pCell = findCell(pPage, pPage->nCell-1);
  55112. pStop = &pCell[9];
  55113. while( (*(pCell++)&0x80) && pCell<pStop );
  55114. pStop = &pCell[9];
  55115. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  55116. /* Insert the new divider cell into pParent. */
  55117. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  55118. 0, pPage->pgno, &rc);
  55119. /* Set the right-child pointer of pParent to point to the new page. */
  55120. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  55121. /* Release the reference to the new page. */
  55122. releasePage(pNew);
  55123. }
  55124. return rc;
  55125. }
  55126. #endif /* SQLITE_OMIT_QUICKBALANCE */
  55127. #if 0
  55128. /*
  55129. ** This function does not contribute anything to the operation of SQLite.
  55130. ** it is sometimes activated temporarily while debugging code responsible
  55131. ** for setting pointer-map entries.
  55132. */
  55133. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  55134. int i, j;
  55135. for(i=0; i<nPage; i++){
  55136. Pgno n;
  55137. u8 e;
  55138. MemPage *pPage = apPage[i];
  55139. BtShared *pBt = pPage->pBt;
  55140. assert( pPage->isInit );
  55141. for(j=0; j<pPage->nCell; j++){
  55142. CellInfo info;
  55143. u8 *z;
  55144. z = findCell(pPage, j);
  55145. btreeParseCellPtr(pPage, z, &info);
  55146. if( info.iOverflow ){
  55147. Pgno ovfl = get4byte(&z[info.iOverflow]);
  55148. ptrmapGet(pBt, ovfl, &e, &n);
  55149. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  55150. }
  55151. if( !pPage->leaf ){
  55152. Pgno child = get4byte(z);
  55153. ptrmapGet(pBt, child, &e, &n);
  55154. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55155. }
  55156. }
  55157. if( !pPage->leaf ){
  55158. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55159. ptrmapGet(pBt, child, &e, &n);
  55160. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55161. }
  55162. }
  55163. return 1;
  55164. }
  55165. #endif
  55166. /*
  55167. ** This function is used to copy the contents of the b-tree node stored
  55168. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  55169. ** the pointer-map entries for each child page are updated so that the
  55170. ** parent page stored in the pointer map is page pTo. If pFrom contained
  55171. ** any cells with overflow page pointers, then the corresponding pointer
  55172. ** map entries are also updated so that the parent page is page pTo.
  55173. **
  55174. ** If pFrom is currently carrying any overflow cells (entries in the
  55175. ** MemPage.apOvfl[] array), they are not copied to pTo.
  55176. **
  55177. ** Before returning, page pTo is reinitialized using btreeInitPage().
  55178. **
  55179. ** The performance of this function is not critical. It is only used by
  55180. ** the balance_shallower() and balance_deeper() procedures, neither of
  55181. ** which are called often under normal circumstances.
  55182. */
  55183. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  55184. if( (*pRC)==SQLITE_OK ){
  55185. BtShared * const pBt = pFrom->pBt;
  55186. u8 * const aFrom = pFrom->aData;
  55187. u8 * const aTo = pTo->aData;
  55188. int const iFromHdr = pFrom->hdrOffset;
  55189. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  55190. int rc;
  55191. int iData;
  55192. assert( pFrom->isInit );
  55193. assert( pFrom->nFree>=iToHdr );
  55194. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  55195. /* Copy the b-tree node content from page pFrom to page pTo. */
  55196. iData = get2byte(&aFrom[iFromHdr+5]);
  55197. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  55198. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  55199. /* Reinitialize page pTo so that the contents of the MemPage structure
  55200. ** match the new data. The initialization of pTo can actually fail under
  55201. ** fairly obscure circumstances, even though it is a copy of initialized
  55202. ** page pFrom.
  55203. */
  55204. pTo->isInit = 0;
  55205. rc = btreeInitPage(pTo);
  55206. if( rc!=SQLITE_OK ){
  55207. *pRC = rc;
  55208. return;
  55209. }
  55210. /* If this is an auto-vacuum database, update the pointer-map entries
  55211. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  55212. */
  55213. if( ISAUTOVACUUM ){
  55214. *pRC = setChildPtrmaps(pTo);
  55215. }
  55216. }
  55217. }
  55218. /*
  55219. ** This routine redistributes cells on the iParentIdx'th child of pParent
  55220. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  55221. ** same amount of free space. Usually a single sibling on either side of the
  55222. ** page are used in the balancing, though both siblings might come from one
  55223. ** side if the page is the first or last child of its parent. If the page
  55224. ** has fewer than 2 siblings (something which can only happen if the page
  55225. ** is a root page or a child of a root page) then all available siblings
  55226. ** participate in the balancing.
  55227. **
  55228. ** The number of siblings of the page might be increased or decreased by
  55229. ** one or two in an effort to keep pages nearly full but not over full.
  55230. **
  55231. ** Note that when this routine is called, some of the cells on the page
  55232. ** might not actually be stored in MemPage.aData[]. This can happen
  55233. ** if the page is overfull. This routine ensures that all cells allocated
  55234. ** to the page and its siblings fit into MemPage.aData[] before returning.
  55235. **
  55236. ** In the course of balancing the page and its siblings, cells may be
  55237. ** inserted into or removed from the parent page (pParent). Doing so
  55238. ** may cause the parent page to become overfull or underfull. If this
  55239. ** happens, it is the responsibility of the caller to invoke the correct
  55240. ** balancing routine to fix this problem (see the balance() routine).
  55241. **
  55242. ** If this routine fails for any reason, it might leave the database
  55243. ** in a corrupted state. So if this routine fails, the database should
  55244. ** be rolled back.
  55245. **
  55246. ** The third argument to this function, aOvflSpace, is a pointer to a
  55247. ** buffer big enough to hold one page. If while inserting cells into the parent
  55248. ** page (pParent) the parent page becomes overfull, this buffer is
  55249. ** used to store the parent's overflow cells. Because this function inserts
  55250. ** a maximum of four divider cells into the parent page, and the maximum
  55251. ** size of a cell stored within an internal node is always less than 1/4
  55252. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  55253. ** enough for all overflow cells.
  55254. **
  55255. ** If aOvflSpace is set to a null pointer, this function returns
  55256. ** SQLITE_NOMEM.
  55257. */
  55258. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55259. #pragma optimize("", off)
  55260. #endif
  55261. static int balance_nonroot(
  55262. MemPage *pParent, /* Parent page of siblings being balanced */
  55263. int iParentIdx, /* Index of "the page" in pParent */
  55264. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  55265. int isRoot, /* True if pParent is a root-page */
  55266. int bBulk /* True if this call is part of a bulk load */
  55267. ){
  55268. BtShared *pBt; /* The whole database */
  55269. int nCell = 0; /* Number of cells in apCell[] */
  55270. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  55271. int nNew = 0; /* Number of pages in apNew[] */
  55272. int nOld; /* Number of pages in apOld[] */
  55273. int i, j, k; /* Loop counters */
  55274. int nxDiv; /* Next divider slot in pParent->aCell[] */
  55275. int rc = SQLITE_OK; /* The return code */
  55276. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  55277. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  55278. int usableSpace; /* Bytes in pPage beyond the header */
  55279. int pageFlags; /* Value of pPage->aData[0] */
  55280. int subtotal; /* Subtotal of bytes in cells on one page */
  55281. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  55282. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  55283. int szScratch; /* Size of scratch memory requested */
  55284. MemPage *apOld[NB]; /* pPage and up to two siblings */
  55285. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  55286. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  55287. u8 *pRight; /* Location in parent of right-sibling pointer */
  55288. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  55289. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  55290. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  55291. u8 **apCell = 0; /* All cells begin balanced */
  55292. u16 *szCell; /* Local size of all cells in apCell[] */
  55293. u8 *aSpace1; /* Space for copies of dividers cells */
  55294. Pgno pgno; /* Temp var to store a page number in */
  55295. pBt = pParent->pBt;
  55296. assert( sqlite3_mutex_held(pBt->mutex) );
  55297. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55298. #if 0
  55299. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  55300. #endif
  55301. /* At this point pParent may have at most one overflow cell. And if
  55302. ** this overflow cell is present, it must be the cell with
  55303. ** index iParentIdx. This scenario comes about when this function
  55304. ** is called (indirectly) from sqlite3BtreeDelete().
  55305. */
  55306. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  55307. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  55308. if( !aOvflSpace ){
  55309. return SQLITE_NOMEM;
  55310. }
  55311. /* Find the sibling pages to balance. Also locate the cells in pParent
  55312. ** that divide the siblings. An attempt is made to find NN siblings on
  55313. ** either side of pPage. More siblings are taken from one side, however,
  55314. ** if there are fewer than NN siblings on the other side. If pParent
  55315. ** has NB or fewer children then all children of pParent are taken.
  55316. **
  55317. ** This loop also drops the divider cells from the parent page. This
  55318. ** way, the remainder of the function does not have to deal with any
  55319. ** overflow cells in the parent page, since if any existed they will
  55320. ** have already been removed.
  55321. */
  55322. i = pParent->nOverflow + pParent->nCell;
  55323. if( i<2 ){
  55324. nxDiv = 0;
  55325. }else{
  55326. assert( bBulk==0 || bBulk==1 );
  55327. if( iParentIdx==0 ){
  55328. nxDiv = 0;
  55329. }else if( iParentIdx==i ){
  55330. nxDiv = i-2+bBulk;
  55331. }else{
  55332. assert( bBulk==0 );
  55333. nxDiv = iParentIdx-1;
  55334. }
  55335. i = 2-bBulk;
  55336. }
  55337. nOld = i+1;
  55338. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  55339. pRight = &pParent->aData[pParent->hdrOffset+8];
  55340. }else{
  55341. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55342. }
  55343. pgno = get4byte(pRight);
  55344. while( 1 ){
  55345. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  55346. if( rc ){
  55347. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55348. goto balance_cleanup;
  55349. }
  55350. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  55351. if( (i--)==0 ) break;
  55352. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  55353. apDiv[i] = pParent->apOvfl[0];
  55354. pgno = get4byte(apDiv[i]);
  55355. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55356. pParent->nOverflow = 0;
  55357. }else{
  55358. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55359. pgno = get4byte(apDiv[i]);
  55360. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55361. /* Drop the cell from the parent page. apDiv[i] still points to
  55362. ** the cell within the parent, even though it has been dropped.
  55363. ** This is safe because dropping a cell only overwrites the first
  55364. ** four bytes of it, and this function does not need the first
  55365. ** four bytes of the divider cell. So the pointer is safe to use
  55366. ** later on.
  55367. **
  55368. ** But not if we are in secure-delete mode. In secure-delete mode,
  55369. ** the dropCell() routine will overwrite the entire cell with zeroes.
  55370. ** In this case, temporarily copy the cell into the aOvflSpace[]
  55371. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  55372. ** is allocated. */
  55373. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  55374. int iOff;
  55375. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  55376. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  55377. rc = SQLITE_CORRUPT_BKPT;
  55378. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55379. goto balance_cleanup;
  55380. }else{
  55381. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  55382. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  55383. }
  55384. }
  55385. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  55386. }
  55387. }
  55388. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  55389. ** alignment */
  55390. nMaxCells = (nMaxCells + 3)&~3;
  55391. /*
  55392. ** Allocate space for memory structures
  55393. */
  55394. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  55395. szScratch =
  55396. nMaxCells*sizeof(u8*) /* apCell */
  55397. + nMaxCells*sizeof(u16) /* szCell */
  55398. + pBt->pageSize /* aSpace1 */
  55399. + k*nOld; /* Page copies (apCopy) */
  55400. apCell = sqlite3ScratchMalloc( szScratch );
  55401. if( apCell==0 ){
  55402. rc = SQLITE_NOMEM;
  55403. goto balance_cleanup;
  55404. }
  55405. szCell = (u16*)&apCell[nMaxCells];
  55406. aSpace1 = (u8*)&szCell[nMaxCells];
  55407. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  55408. /*
  55409. ** Load pointers to all cells on sibling pages and the divider cells
  55410. ** into the local apCell[] array. Make copies of the divider cells
  55411. ** into space obtained from aSpace1[] and remove the divider cells
  55412. ** from pParent.
  55413. **
  55414. ** If the siblings are on leaf pages, then the child pointers of the
  55415. ** divider cells are stripped from the cells before they are copied
  55416. ** into aSpace1[]. In this way, all cells in apCell[] are without
  55417. ** child pointers. If siblings are not leaves, then all cell in
  55418. ** apCell[] include child pointers. Either way, all cells in apCell[]
  55419. ** are alike.
  55420. **
  55421. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  55422. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  55423. */
  55424. leafCorrection = apOld[0]->leaf*4;
  55425. leafData = apOld[0]->hasData;
  55426. for(i=0; i<nOld; i++){
  55427. int limit;
  55428. /* Before doing anything else, take a copy of the i'th original sibling
  55429. ** The rest of this function will use data from the copies rather
  55430. ** that the original pages since the original pages will be in the
  55431. ** process of being overwritten. */
  55432. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  55433. memcpy(pOld, apOld[i], sizeof(MemPage));
  55434. pOld->aData = (void*)&pOld[1];
  55435. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  55436. limit = pOld->nCell+pOld->nOverflow;
  55437. if( pOld->nOverflow>0 ){
  55438. for(j=0; j<limit; j++){
  55439. assert( nCell<nMaxCells );
  55440. apCell[nCell] = findOverflowCell(pOld, j);
  55441. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55442. nCell++;
  55443. }
  55444. }else{
  55445. u8 *aData = pOld->aData;
  55446. u16 maskPage = pOld->maskPage;
  55447. u16 cellOffset = pOld->cellOffset;
  55448. for(j=0; j<limit; j++){
  55449. assert( nCell<nMaxCells );
  55450. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  55451. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55452. nCell++;
  55453. }
  55454. }
  55455. if( i<nOld-1 && !leafData){
  55456. u16 sz = (u16)szNew[i];
  55457. u8 *pTemp;
  55458. assert( nCell<nMaxCells );
  55459. szCell[nCell] = sz;
  55460. pTemp = &aSpace1[iSpace1];
  55461. iSpace1 += sz;
  55462. assert( sz<=pBt->maxLocal+23 );
  55463. assert( iSpace1 <= (int)pBt->pageSize );
  55464. memcpy(pTemp, apDiv[i], sz);
  55465. apCell[nCell] = pTemp+leafCorrection;
  55466. assert( leafCorrection==0 || leafCorrection==4 );
  55467. szCell[nCell] = szCell[nCell] - leafCorrection;
  55468. if( !pOld->leaf ){
  55469. assert( leafCorrection==0 );
  55470. assert( pOld->hdrOffset==0 );
  55471. /* The right pointer of the child page pOld becomes the left
  55472. ** pointer of the divider cell */
  55473. memcpy(apCell[nCell], &pOld->aData[8], 4);
  55474. }else{
  55475. assert( leafCorrection==4 );
  55476. if( szCell[nCell]<4 ){
  55477. /* Do not allow any cells smaller than 4 bytes. */
  55478. szCell[nCell] = 4;
  55479. }
  55480. }
  55481. nCell++;
  55482. }
  55483. }
  55484. /*
  55485. ** Figure out the number of pages needed to hold all nCell cells.
  55486. ** Store this number in "k". Also compute szNew[] which is the total
  55487. ** size of all cells on the i-th page and cntNew[] which is the index
  55488. ** in apCell[] of the cell that divides page i from page i+1.
  55489. ** cntNew[k] should equal nCell.
  55490. **
  55491. ** Values computed by this block:
  55492. **
  55493. ** k: The total number of sibling pages
  55494. ** szNew[i]: Spaced used on the i-th sibling page.
  55495. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  55496. ** the right of the i-th sibling page.
  55497. ** usableSpace: Number of bytes of space available on each sibling.
  55498. **
  55499. */
  55500. usableSpace = pBt->usableSize - 12 + leafCorrection;
  55501. for(subtotal=k=i=0; i<nCell; i++){
  55502. assert( i<nMaxCells );
  55503. subtotal += szCell[i] + 2;
  55504. if( subtotal > usableSpace ){
  55505. szNew[k] = subtotal - szCell[i];
  55506. cntNew[k] = i;
  55507. if( leafData ){ i--; }
  55508. subtotal = 0;
  55509. k++;
  55510. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  55511. }
  55512. }
  55513. szNew[k] = subtotal;
  55514. cntNew[k] = nCell;
  55515. k++;
  55516. /*
  55517. ** The packing computed by the previous block is biased toward the siblings
  55518. ** on the left side. The left siblings are always nearly full, while the
  55519. ** right-most sibling might be nearly empty. This block of code attempts
  55520. ** to adjust the packing of siblings to get a better balance.
  55521. **
  55522. ** This adjustment is more than an optimization. The packing above might
  55523. ** be so out of balance as to be illegal. For example, the right-most
  55524. ** sibling might be completely empty. This adjustment is not optional.
  55525. */
  55526. for(i=k-1; i>0; i--){
  55527. int szRight = szNew[i]; /* Size of sibling on the right */
  55528. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  55529. int r; /* Index of right-most cell in left sibling */
  55530. int d; /* Index of first cell to the left of right sibling */
  55531. r = cntNew[i-1] - 1;
  55532. d = r + 1 - leafData;
  55533. assert( d<nMaxCells );
  55534. assert( r<nMaxCells );
  55535. while( szRight==0
  55536. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  55537. ){
  55538. szRight += szCell[d] + 2;
  55539. szLeft -= szCell[r] + 2;
  55540. cntNew[i-1]--;
  55541. r = cntNew[i-1] - 1;
  55542. d = r + 1 - leafData;
  55543. }
  55544. szNew[i] = szRight;
  55545. szNew[i-1] = szLeft;
  55546. }
  55547. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  55548. ** a virtual root page. A virtual root page is when the real root
  55549. ** page is page 1 and we are the only child of that page.
  55550. **
  55551. ** UPDATE: The assert() below is not necessarily true if the database
  55552. ** file is corrupt. The corruption will be detected and reported later
  55553. ** in this procedure so there is no need to act upon it now.
  55554. */
  55555. #if 0
  55556. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  55557. #endif
  55558. TRACE(("BALANCE: old: %d %d %d ",
  55559. apOld[0]->pgno,
  55560. nOld>=2 ? apOld[1]->pgno : 0,
  55561. nOld>=3 ? apOld[2]->pgno : 0
  55562. ));
  55563. /*
  55564. ** Allocate k new pages. Reuse old pages where possible.
  55565. */
  55566. if( apOld[0]->pgno<=1 ){
  55567. rc = SQLITE_CORRUPT_BKPT;
  55568. goto balance_cleanup;
  55569. }
  55570. pageFlags = apOld[0]->aData[0];
  55571. for(i=0; i<k; i++){
  55572. MemPage *pNew;
  55573. if( i<nOld ){
  55574. pNew = apNew[i] = apOld[i];
  55575. apOld[i] = 0;
  55576. rc = sqlite3PagerWrite(pNew->pDbPage);
  55577. nNew++;
  55578. if( rc ) goto balance_cleanup;
  55579. }else{
  55580. assert( i>0 );
  55581. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  55582. if( rc ) goto balance_cleanup;
  55583. apNew[i] = pNew;
  55584. nNew++;
  55585. /* Set the pointer-map entry for the new sibling page. */
  55586. if( ISAUTOVACUUM ){
  55587. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  55588. if( rc!=SQLITE_OK ){
  55589. goto balance_cleanup;
  55590. }
  55591. }
  55592. }
  55593. }
  55594. /* Free any old pages that were not reused as new pages.
  55595. */
  55596. while( i<nOld ){
  55597. freePage(apOld[i], &rc);
  55598. if( rc ) goto balance_cleanup;
  55599. releasePage(apOld[i]);
  55600. apOld[i] = 0;
  55601. i++;
  55602. }
  55603. /*
  55604. ** Put the new pages in accending order. This helps to
  55605. ** keep entries in the disk file in order so that a scan
  55606. ** of the table is a linear scan through the file. That
  55607. ** in turn helps the operating system to deliver pages
  55608. ** from the disk more rapidly.
  55609. **
  55610. ** An O(n^2) insertion sort algorithm is used, but since
  55611. ** n is never more than NB (a small constant), that should
  55612. ** not be a problem.
  55613. **
  55614. ** When NB==3, this one optimization makes the database
  55615. ** about 25% faster for large insertions and deletions.
  55616. */
  55617. for(i=0; i<k-1; i++){
  55618. int minV = apNew[i]->pgno;
  55619. int minI = i;
  55620. for(j=i+1; j<k; j++){
  55621. if( apNew[j]->pgno<(unsigned)minV ){
  55622. minI = j;
  55623. minV = apNew[j]->pgno;
  55624. }
  55625. }
  55626. if( minI>i ){
  55627. MemPage *pT;
  55628. pT = apNew[i];
  55629. apNew[i] = apNew[minI];
  55630. apNew[minI] = pT;
  55631. }
  55632. }
  55633. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  55634. apNew[0]->pgno, szNew[0],
  55635. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  55636. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  55637. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  55638. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  55639. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55640. put4byte(pRight, apNew[nNew-1]->pgno);
  55641. /*
  55642. ** Evenly distribute the data in apCell[] across the new pages.
  55643. ** Insert divider cells into pParent as necessary.
  55644. */
  55645. j = 0;
  55646. for(i=0; i<nNew; i++){
  55647. /* Assemble the new sibling page. */
  55648. MemPage *pNew = apNew[i];
  55649. assert( j<nMaxCells );
  55650. zeroPage(pNew, pageFlags);
  55651. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  55652. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  55653. assert( pNew->nOverflow==0 );
  55654. j = cntNew[i];
  55655. /* If the sibling page assembled above was not the right-most sibling,
  55656. ** insert a divider cell into the parent page.
  55657. */
  55658. assert( i<nNew-1 || j==nCell );
  55659. if( j<nCell ){
  55660. u8 *pCell;
  55661. u8 *pTemp;
  55662. int sz;
  55663. assert( j<nMaxCells );
  55664. pCell = apCell[j];
  55665. sz = szCell[j] + leafCorrection;
  55666. pTemp = &aOvflSpace[iOvflSpace];
  55667. if( !pNew->leaf ){
  55668. memcpy(&pNew->aData[8], pCell, 4);
  55669. }else if( leafData ){
  55670. /* If the tree is a leaf-data tree, and the siblings are leaves,
  55671. ** then there is no divider cell in apCell[]. Instead, the divider
  55672. ** cell consists of the integer key for the right-most cell of
  55673. ** the sibling-page assembled above only.
  55674. */
  55675. CellInfo info;
  55676. j--;
  55677. btreeParseCellPtr(pNew, apCell[j], &info);
  55678. pCell = pTemp;
  55679. sz = 4 + putVarint(&pCell[4], info.nKey);
  55680. pTemp = 0;
  55681. }else{
  55682. pCell -= 4;
  55683. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  55684. ** previously stored on a leaf node, and its reported size was 4
  55685. ** bytes, then it may actually be smaller than this
  55686. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  55687. ** any cell). But it is important to pass the correct size to
  55688. ** insertCell(), so reparse the cell now.
  55689. **
  55690. ** Note that this can never happen in an SQLite data file, as all
  55691. ** cells are at least 4 bytes. It only happens in b-trees used
  55692. ** to evaluate "IN (SELECT ...)" and similar clauses.
  55693. */
  55694. if( szCell[j]==4 ){
  55695. assert(leafCorrection==4);
  55696. sz = cellSizePtr(pParent, pCell);
  55697. }
  55698. }
  55699. iOvflSpace += sz;
  55700. assert( sz<=pBt->maxLocal+23 );
  55701. assert( iOvflSpace <= (int)pBt->pageSize );
  55702. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  55703. if( rc!=SQLITE_OK ) goto balance_cleanup;
  55704. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55705. j++;
  55706. nxDiv++;
  55707. }
  55708. }
  55709. assert( j==nCell );
  55710. assert( nOld>0 );
  55711. assert( nNew>0 );
  55712. if( (pageFlags & PTF_LEAF)==0 ){
  55713. u8 *zChild = &apCopy[nOld-1]->aData[8];
  55714. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  55715. }
  55716. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  55717. /* The root page of the b-tree now contains no cells. The only sibling
  55718. ** page is the right-child of the parent. Copy the contents of the
  55719. ** child page into the parent, decreasing the overall height of the
  55720. ** b-tree structure by one. This is described as the "balance-shallower"
  55721. ** sub-algorithm in some documentation.
  55722. **
  55723. ** If this is an auto-vacuum database, the call to copyNodeContent()
  55724. ** sets all pointer-map entries corresponding to database image pages
  55725. ** for which the pointer is stored within the content being copied.
  55726. **
  55727. ** The second assert below verifies that the child page is defragmented
  55728. ** (it must be, as it was just reconstructed using assemblePage()). This
  55729. ** is important if the parent page happens to be page 1 of the database
  55730. ** image. */
  55731. assert( nNew==1 );
  55732. assert( apNew[0]->nFree ==
  55733. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  55734. );
  55735. copyNodeContent(apNew[0], pParent, &rc);
  55736. freePage(apNew[0], &rc);
  55737. }else if( ISAUTOVACUUM ){
  55738. /* Fix the pointer-map entries for all the cells that were shifted around.
  55739. ** There are several different types of pointer-map entries that need to
  55740. ** be dealt with by this routine. Some of these have been set already, but
  55741. ** many have not. The following is a summary:
  55742. **
  55743. ** 1) The entries associated with new sibling pages that were not
  55744. ** siblings when this function was called. These have already
  55745. ** been set. We don't need to worry about old siblings that were
  55746. ** moved to the free-list - the freePage() code has taken care
  55747. ** of those.
  55748. **
  55749. ** 2) The pointer-map entries associated with the first overflow
  55750. ** page in any overflow chains used by new divider cells. These
  55751. ** have also already been taken care of by the insertCell() code.
  55752. **
  55753. ** 3) If the sibling pages are not leaves, then the child pages of
  55754. ** cells stored on the sibling pages may need to be updated.
  55755. **
  55756. ** 4) If the sibling pages are not internal intkey nodes, then any
  55757. ** overflow pages used by these cells may need to be updated
  55758. ** (internal intkey nodes never contain pointers to overflow pages).
  55759. **
  55760. ** 5) If the sibling pages are not leaves, then the pointer-map
  55761. ** entries for the right-child pages of each sibling may need
  55762. ** to be updated.
  55763. **
  55764. ** Cases 1 and 2 are dealt with above by other code. The next
  55765. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  55766. ** setting a pointer map entry is a relatively expensive operation, this
  55767. ** code only sets pointer map entries for child or overflow pages that have
  55768. ** actually moved between pages. */
  55769. MemPage *pNew = apNew[0];
  55770. MemPage *pOld = apCopy[0];
  55771. int nOverflow = pOld->nOverflow;
  55772. int iNextOld = pOld->nCell + nOverflow;
  55773. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  55774. j = 0; /* Current 'old' sibling page */
  55775. k = 0; /* Current 'new' sibling page */
  55776. for(i=0; i<nCell; i++){
  55777. int isDivider = 0;
  55778. while( i==iNextOld ){
  55779. /* Cell i is the cell immediately following the last cell on old
  55780. ** sibling page j. If the siblings are not leaf pages of an
  55781. ** intkey b-tree, then cell i was a divider cell. */
  55782. assert( j+1 < ArraySize(apCopy) );
  55783. assert( j+1 < nOld );
  55784. pOld = apCopy[++j];
  55785. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  55786. if( pOld->nOverflow ){
  55787. nOverflow = pOld->nOverflow;
  55788. iOverflow = i + !leafData + pOld->aiOvfl[0];
  55789. }
  55790. isDivider = !leafData;
  55791. }
  55792. assert(nOverflow>0 || iOverflow<i );
  55793. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  55794. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  55795. if( i==iOverflow ){
  55796. isDivider = 1;
  55797. if( (--nOverflow)>0 ){
  55798. iOverflow++;
  55799. }
  55800. }
  55801. if( i==cntNew[k] ){
  55802. /* Cell i is the cell immediately following the last cell on new
  55803. ** sibling page k. If the siblings are not leaf pages of an
  55804. ** intkey b-tree, then cell i is a divider cell. */
  55805. pNew = apNew[++k];
  55806. if( !leafData ) continue;
  55807. }
  55808. assert( j<nOld );
  55809. assert( k<nNew );
  55810. /* If the cell was originally divider cell (and is not now) or
  55811. ** an overflow cell, or if the cell was located on a different sibling
  55812. ** page before the balancing, then the pointer map entries associated
  55813. ** with any child or overflow pages need to be updated. */
  55814. if( isDivider || pOld->pgno!=pNew->pgno ){
  55815. if( !leafCorrection ){
  55816. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  55817. }
  55818. if( szCell[i]>pNew->minLocal ){
  55819. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  55820. }
  55821. }
  55822. }
  55823. if( !leafCorrection ){
  55824. for(i=0; i<nNew; i++){
  55825. u32 key = get4byte(&apNew[i]->aData[8]);
  55826. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  55827. }
  55828. }
  55829. #if 0
  55830. /* The ptrmapCheckPages() contains assert() statements that verify that
  55831. ** all pointer map pages are set correctly. This is helpful while
  55832. ** debugging. This is usually disabled because a corrupt database may
  55833. ** cause an assert() statement to fail. */
  55834. ptrmapCheckPages(apNew, nNew);
  55835. ptrmapCheckPages(&pParent, 1);
  55836. #endif
  55837. }
  55838. assert( pParent->isInit );
  55839. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  55840. nOld, nNew, nCell));
  55841. /*
  55842. ** Cleanup before returning.
  55843. */
  55844. balance_cleanup:
  55845. sqlite3ScratchFree(apCell);
  55846. for(i=0; i<nOld; i++){
  55847. releasePage(apOld[i]);
  55848. }
  55849. for(i=0; i<nNew; i++){
  55850. releasePage(apNew[i]);
  55851. }
  55852. return rc;
  55853. }
  55854. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55855. #pragma optimize("", on)
  55856. #endif
  55857. /*
  55858. ** This function is called when the root page of a b-tree structure is
  55859. ** overfull (has one or more overflow pages).
  55860. **
  55861. ** A new child page is allocated and the contents of the current root
  55862. ** page, including overflow cells, are copied into the child. The root
  55863. ** page is then overwritten to make it an empty page with the right-child
  55864. ** pointer pointing to the new page.
  55865. **
  55866. ** Before returning, all pointer-map entries corresponding to pages
  55867. ** that the new child-page now contains pointers to are updated. The
  55868. ** entry corresponding to the new right-child pointer of the root
  55869. ** page is also updated.
  55870. **
  55871. ** If successful, *ppChild is set to contain a reference to the child
  55872. ** page and SQLITE_OK is returned. In this case the caller is required
  55873. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  55874. ** an error code is returned and *ppChild is set to 0.
  55875. */
  55876. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  55877. int rc; /* Return value from subprocedures */
  55878. MemPage *pChild = 0; /* Pointer to a new child page */
  55879. Pgno pgnoChild = 0; /* Page number of the new child page */
  55880. BtShared *pBt = pRoot->pBt; /* The BTree */
  55881. assert( pRoot->nOverflow>0 );
  55882. assert( sqlite3_mutex_held(pBt->mutex) );
  55883. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  55884. ** page that will become the new right-child of pPage. Copy the contents
  55885. ** of the node stored on pRoot into the new child page.
  55886. */
  55887. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55888. if( rc==SQLITE_OK ){
  55889. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  55890. copyNodeContent(pRoot, pChild, &rc);
  55891. if( ISAUTOVACUUM ){
  55892. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  55893. }
  55894. }
  55895. if( rc ){
  55896. *ppChild = 0;
  55897. releasePage(pChild);
  55898. return rc;
  55899. }
  55900. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  55901. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55902. assert( pChild->nCell==pRoot->nCell );
  55903. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  55904. /* Copy the overflow cells from pRoot to pChild */
  55905. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  55906. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  55907. memcpy(pChild->apOvfl, pRoot->apOvfl,
  55908. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  55909. pChild->nOverflow = pRoot->nOverflow;
  55910. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  55911. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  55912. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  55913. *ppChild = pChild;
  55914. return SQLITE_OK;
  55915. }
  55916. /*
  55917. ** The page that pCur currently points to has just been modified in
  55918. ** some way. This function figures out if this modification means the
  55919. ** tree needs to be balanced, and if so calls the appropriate balancing
  55920. ** routine. Balancing routines are:
  55921. **
  55922. ** balance_quick()
  55923. ** balance_deeper()
  55924. ** balance_nonroot()
  55925. */
  55926. static int balance(BtCursor *pCur){
  55927. int rc = SQLITE_OK;
  55928. const int nMin = pCur->pBt->usableSize * 2 / 3;
  55929. u8 aBalanceQuickSpace[13];
  55930. u8 *pFree = 0;
  55931. TESTONLY( int balance_quick_called = 0 );
  55932. TESTONLY( int balance_deeper_called = 0 );
  55933. do {
  55934. int iPage = pCur->iPage;
  55935. MemPage *pPage = pCur->apPage[iPage];
  55936. if( iPage==0 ){
  55937. if( pPage->nOverflow ){
  55938. /* The root page of the b-tree is overfull. In this case call the
  55939. ** balance_deeper() function to create a new child for the root-page
  55940. ** and copy the current contents of the root-page to it. The
  55941. ** next iteration of the do-loop will balance the child page.
  55942. */
  55943. assert( (balance_deeper_called++)==0 );
  55944. rc = balance_deeper(pPage, &pCur->apPage[1]);
  55945. if( rc==SQLITE_OK ){
  55946. pCur->iPage = 1;
  55947. pCur->aiIdx[0] = 0;
  55948. pCur->aiIdx[1] = 0;
  55949. assert( pCur->apPage[1]->nOverflow );
  55950. }
  55951. }else{
  55952. break;
  55953. }
  55954. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  55955. break;
  55956. }else{
  55957. MemPage * const pParent = pCur->apPage[iPage-1];
  55958. int const iIdx = pCur->aiIdx[iPage-1];
  55959. rc = sqlite3PagerWrite(pParent->pDbPage);
  55960. if( rc==SQLITE_OK ){
  55961. #ifndef SQLITE_OMIT_QUICKBALANCE
  55962. if( pPage->hasData
  55963. && pPage->nOverflow==1
  55964. && pPage->aiOvfl[0]==pPage->nCell
  55965. && pParent->pgno!=1
  55966. && pParent->nCell==iIdx
  55967. ){
  55968. /* Call balance_quick() to create a new sibling of pPage on which
  55969. ** to store the overflow cell. balance_quick() inserts a new cell
  55970. ** into pParent, which may cause pParent overflow. If this
  55971. ** happens, the next interation of the do-loop will balance pParent
  55972. ** use either balance_nonroot() or balance_deeper(). Until this
  55973. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  55974. ** buffer.
  55975. **
  55976. ** The purpose of the following assert() is to check that only a
  55977. ** single call to balance_quick() is made for each call to this
  55978. ** function. If this were not verified, a subtle bug involving reuse
  55979. ** of the aBalanceQuickSpace[] might sneak in.
  55980. */
  55981. assert( (balance_quick_called++)==0 );
  55982. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  55983. }else
  55984. #endif
  55985. {
  55986. /* In this case, call balance_nonroot() to redistribute cells
  55987. ** between pPage and up to 2 of its sibling pages. This involves
  55988. ** modifying the contents of pParent, which may cause pParent to
  55989. ** become overfull or underfull. The next iteration of the do-loop
  55990. ** will balance the parent page to correct this.
  55991. **
  55992. ** If the parent page becomes overfull, the overflow cell or cells
  55993. ** are stored in the pSpace buffer allocated immediately below.
  55994. ** A subsequent iteration of the do-loop will deal with this by
  55995. ** calling balance_nonroot() (balance_deeper() may be called first,
  55996. ** but it doesn't deal with overflow cells - just moves them to a
  55997. ** different page). Once this subsequent call to balance_nonroot()
  55998. ** has completed, it is safe to release the pSpace buffer used by
  55999. ** the previous call, as the overflow cell data will have been
  56000. ** copied either into the body of a database page or into the new
  56001. ** pSpace buffer passed to the latter call to balance_nonroot().
  56002. */
  56003. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  56004. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  56005. if( pFree ){
  56006. /* If pFree is not NULL, it points to the pSpace buffer used
  56007. ** by a previous call to balance_nonroot(). Its contents are
  56008. ** now stored either on real database pages or within the
  56009. ** new pSpace buffer, so it may be safely freed here. */
  56010. sqlite3PageFree(pFree);
  56011. }
  56012. /* The pSpace buffer will be freed after the next call to
  56013. ** balance_nonroot(), or just before this function returns, whichever
  56014. ** comes first. */
  56015. pFree = pSpace;
  56016. }
  56017. }
  56018. pPage->nOverflow = 0;
  56019. /* The next iteration of the do-loop balances the parent page. */
  56020. releasePage(pPage);
  56021. pCur->iPage--;
  56022. }
  56023. }while( rc==SQLITE_OK );
  56024. if( pFree ){
  56025. sqlite3PageFree(pFree);
  56026. }
  56027. return rc;
  56028. }
  56029. /*
  56030. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  56031. ** and the data is given by (pData,nData). The cursor is used only to
  56032. ** define what table the record should be inserted into. The cursor
  56033. ** is left pointing at a random location.
  56034. **
  56035. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  56036. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  56037. **
  56038. ** If the seekResult parameter is non-zero, then a successful call to
  56039. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  56040. ** been performed. seekResult is the search result returned (a negative
  56041. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  56042. ** a positive value if pCur points at an etry that is larger than
  56043. ** (pKey, nKey)).
  56044. **
  56045. ** If the seekResult parameter is non-zero, then the caller guarantees that
  56046. ** cursor pCur is pointing at the existing copy of a row that is to be
  56047. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  56048. ** point to any entry or to no entry at all and so this function has to seek
  56049. ** the cursor before the new key can be inserted.
  56050. */
  56051. SQLITE_PRIVATE int sqlite3BtreeInsert(
  56052. BtCursor *pCur, /* Insert data into the table of this cursor */
  56053. const void *pKey, i64 nKey, /* The key of the new record */
  56054. const void *pData, int nData, /* The data of the new record */
  56055. int nZero, /* Number of extra 0 bytes to append to data */
  56056. int appendBias, /* True if this is likely an append */
  56057. int seekResult /* Result of prior MovetoUnpacked() call */
  56058. ){
  56059. int rc;
  56060. int loc = seekResult; /* -1: before desired location +1: after */
  56061. int szNew = 0;
  56062. int idx;
  56063. MemPage *pPage;
  56064. Btree *p = pCur->pBtree;
  56065. BtShared *pBt = p->pBt;
  56066. unsigned char *oldCell;
  56067. unsigned char *newCell = 0;
  56068. if( pCur->eState==CURSOR_FAULT ){
  56069. assert( pCur->skipNext!=SQLITE_OK );
  56070. return pCur->skipNext;
  56071. }
  56072. assert( cursorHoldsMutex(pCur) );
  56073. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  56074. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56075. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56076. /* Assert that the caller has been consistent. If this cursor was opened
  56077. ** expecting an index b-tree, then the caller should be inserting blob
  56078. ** keys with no associated data. If the cursor was opened expecting an
  56079. ** intkey table, the caller should be inserting integer keys with a
  56080. ** blob of associated data. */
  56081. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  56082. /* Save the positions of any other cursors open on this table.
  56083. **
  56084. ** In some cases, the call to btreeMoveto() below is a no-op. For
  56085. ** example, when inserting data into a table with auto-generated integer
  56086. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  56087. ** integer key to use. It then calls this function to actually insert the
  56088. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  56089. ** that the cursor is already where it needs to be and returns without
  56090. ** doing any work. To avoid thwarting these optimizations, it is important
  56091. ** not to clear the cursor here.
  56092. */
  56093. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56094. if( rc ) return rc;
  56095. /* If this is an insert into a table b-tree, invalidate any incrblob
  56096. ** cursors open on the row being replaced (assuming this is a replace
  56097. ** operation - if it is not, the following is a no-op). */
  56098. if( pCur->pKeyInfo==0 ){
  56099. invalidateIncrblobCursors(p, nKey, 0);
  56100. }
  56101. if( !loc ){
  56102. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  56103. if( rc ) return rc;
  56104. }
  56105. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  56106. pPage = pCur->apPage[pCur->iPage];
  56107. assert( pPage->intKey || nKey>=0 );
  56108. assert( pPage->leaf || !pPage->intKey );
  56109. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  56110. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  56111. loc==0 ? "overwrite" : "new entry"));
  56112. assert( pPage->isInit );
  56113. allocateTempSpace(pBt);
  56114. newCell = pBt->pTmpSpace;
  56115. if( newCell==0 ) return SQLITE_NOMEM;
  56116. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  56117. if( rc ) goto end_insert;
  56118. assert( szNew==cellSizePtr(pPage, newCell) );
  56119. assert( szNew <= MX_CELL_SIZE(pBt) );
  56120. idx = pCur->aiIdx[pCur->iPage];
  56121. if( loc==0 ){
  56122. u16 szOld;
  56123. assert( idx<pPage->nCell );
  56124. rc = sqlite3PagerWrite(pPage->pDbPage);
  56125. if( rc ){
  56126. goto end_insert;
  56127. }
  56128. oldCell = findCell(pPage, idx);
  56129. if( !pPage->leaf ){
  56130. memcpy(newCell, oldCell, 4);
  56131. }
  56132. szOld = cellSizePtr(pPage, oldCell);
  56133. rc = clearCell(pPage, oldCell);
  56134. dropCell(pPage, idx, szOld, &rc);
  56135. if( rc ) goto end_insert;
  56136. }else if( loc<0 && pPage->nCell>0 ){
  56137. assert( pPage->leaf );
  56138. idx = ++pCur->aiIdx[pCur->iPage];
  56139. }else{
  56140. assert( pPage->leaf );
  56141. }
  56142. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  56143. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  56144. /* If no error has occurred and pPage has an overflow cell, call balance()
  56145. ** to redistribute the cells within the tree. Since balance() may move
  56146. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  56147. ** variables.
  56148. **
  56149. ** Previous versions of SQLite called moveToRoot() to move the cursor
  56150. ** back to the root page as balance() used to invalidate the contents
  56151. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  56152. ** set the cursor state to "invalid". This makes common insert operations
  56153. ** slightly faster.
  56154. **
  56155. ** There is a subtle but important optimization here too. When inserting
  56156. ** multiple records into an intkey b-tree using a single cursor (as can
  56157. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  56158. ** is advantageous to leave the cursor pointing to the last entry in
  56159. ** the b-tree if possible. If the cursor is left pointing to the last
  56160. ** entry in the table, and the next row inserted has an integer key
  56161. ** larger than the largest existing key, it is possible to insert the
  56162. ** row without seeking the cursor. This can be a big performance boost.
  56163. */
  56164. pCur->info.nSize = 0;
  56165. pCur->validNKey = 0;
  56166. if( rc==SQLITE_OK && pPage->nOverflow ){
  56167. rc = balance(pCur);
  56168. /* Must make sure nOverflow is reset to zero even if the balance()
  56169. ** fails. Internal data structure corruption will result otherwise.
  56170. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  56171. ** from trying to save the current position of the cursor. */
  56172. pCur->apPage[pCur->iPage]->nOverflow = 0;
  56173. pCur->eState = CURSOR_INVALID;
  56174. }
  56175. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  56176. end_insert:
  56177. return rc;
  56178. }
  56179. /*
  56180. ** Delete the entry that the cursor is pointing to. The cursor
  56181. ** is left pointing at a arbitrary location.
  56182. */
  56183. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  56184. Btree *p = pCur->pBtree;
  56185. BtShared *pBt = p->pBt;
  56186. int rc; /* Return code */
  56187. MemPage *pPage; /* Page to delete cell from */
  56188. unsigned char *pCell; /* Pointer to cell to delete */
  56189. int iCellIdx; /* Index of cell to delete */
  56190. int iCellDepth; /* Depth of node containing pCell */
  56191. assert( cursorHoldsMutex(pCur) );
  56192. assert( pBt->inTransaction==TRANS_WRITE );
  56193. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56194. assert( pCur->wrFlag );
  56195. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56196. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  56197. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  56198. || NEVER(pCur->eState!=CURSOR_VALID)
  56199. ){
  56200. return SQLITE_ERROR; /* Something has gone awry. */
  56201. }
  56202. iCellDepth = pCur->iPage;
  56203. iCellIdx = pCur->aiIdx[iCellDepth];
  56204. pPage = pCur->apPage[iCellDepth];
  56205. pCell = findCell(pPage, iCellIdx);
  56206. /* If the page containing the entry to delete is not a leaf page, move
  56207. ** the cursor to the largest entry in the tree that is smaller than
  56208. ** the entry being deleted. This cell will replace the cell being deleted
  56209. ** from the internal node. The 'previous' entry is used for this instead
  56210. ** of the 'next' entry, as the previous entry is always a part of the
  56211. ** sub-tree headed by the child page of the cell being deleted. This makes
  56212. ** balancing the tree following the delete operation easier. */
  56213. if( !pPage->leaf ){
  56214. int notUsed;
  56215. rc = sqlite3BtreePrevious(pCur, &notUsed);
  56216. if( rc ) return rc;
  56217. }
  56218. /* Save the positions of any other cursors open on this table before
  56219. ** making any modifications. Make the page containing the entry to be
  56220. ** deleted writable. Then free any overflow pages associated with the
  56221. ** entry and finally remove the cell itself from within the page.
  56222. */
  56223. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56224. if( rc ) return rc;
  56225. /* If this is a delete operation to remove a row from a table b-tree,
  56226. ** invalidate any incrblob cursors open on the row being deleted. */
  56227. if( pCur->pKeyInfo==0 ){
  56228. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  56229. }
  56230. rc = sqlite3PagerWrite(pPage->pDbPage);
  56231. if( rc ) return rc;
  56232. rc = clearCell(pPage, pCell);
  56233. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  56234. if( rc ) return rc;
  56235. /* If the cell deleted was not located on a leaf page, then the cursor
  56236. ** is currently pointing to the largest entry in the sub-tree headed
  56237. ** by the child-page of the cell that was just deleted from an internal
  56238. ** node. The cell from the leaf node needs to be moved to the internal
  56239. ** node to replace the deleted cell. */
  56240. if( !pPage->leaf ){
  56241. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  56242. int nCell;
  56243. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  56244. unsigned char *pTmp;
  56245. pCell = findCell(pLeaf, pLeaf->nCell-1);
  56246. nCell = cellSizePtr(pLeaf, pCell);
  56247. assert( MX_CELL_SIZE(pBt) >= nCell );
  56248. allocateTempSpace(pBt);
  56249. pTmp = pBt->pTmpSpace;
  56250. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  56251. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  56252. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  56253. if( rc ) return rc;
  56254. }
  56255. /* Balance the tree. If the entry deleted was located on a leaf page,
  56256. ** then the cursor still points to that page. In this case the first
  56257. ** call to balance() repairs the tree, and the if(...) condition is
  56258. ** never true.
  56259. **
  56260. ** Otherwise, if the entry deleted was on an internal node page, then
  56261. ** pCur is pointing to the leaf page from which a cell was removed to
  56262. ** replace the cell deleted from the internal node. This is slightly
  56263. ** tricky as the leaf node may be underfull, and the internal node may
  56264. ** be either under or overfull. In this case run the balancing algorithm
  56265. ** on the leaf node first. If the balance proceeds far enough up the
  56266. ** tree that we can be sure that any problem in the internal node has
  56267. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  56268. ** walk the cursor up the tree to the internal node and balance it as
  56269. ** well. */
  56270. rc = balance(pCur);
  56271. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  56272. while( pCur->iPage>iCellDepth ){
  56273. releasePage(pCur->apPage[pCur->iPage--]);
  56274. }
  56275. rc = balance(pCur);
  56276. }
  56277. if( rc==SQLITE_OK ){
  56278. moveToRoot(pCur);
  56279. }
  56280. return rc;
  56281. }
  56282. /*
  56283. ** Create a new BTree table. Write into *piTable the page
  56284. ** number for the root page of the new table.
  56285. **
  56286. ** The type of type is determined by the flags parameter. Only the
  56287. ** following values of flags are currently in use. Other values for
  56288. ** flags might not work:
  56289. **
  56290. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  56291. ** BTREE_ZERODATA Used for SQL indices
  56292. */
  56293. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  56294. BtShared *pBt = p->pBt;
  56295. MemPage *pRoot;
  56296. Pgno pgnoRoot;
  56297. int rc;
  56298. int ptfFlags; /* Page-type flage for the root page of new table */
  56299. assert( sqlite3BtreeHoldsMutex(p) );
  56300. assert( pBt->inTransaction==TRANS_WRITE );
  56301. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56302. #ifdef SQLITE_OMIT_AUTOVACUUM
  56303. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56304. if( rc ){
  56305. return rc;
  56306. }
  56307. #else
  56308. if( pBt->autoVacuum ){
  56309. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  56310. MemPage *pPageMove; /* The page to move to. */
  56311. /* Creating a new table may probably require moving an existing database
  56312. ** to make room for the new tables root page. In case this page turns
  56313. ** out to be an overflow page, delete all overflow page-map caches
  56314. ** held by open cursors.
  56315. */
  56316. invalidateAllOverflowCache(pBt);
  56317. /* Read the value of meta[3] from the database to determine where the
  56318. ** root page of the new table should go. meta[3] is the largest root-page
  56319. ** created so far, so the new root-page is (meta[3]+1).
  56320. */
  56321. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  56322. pgnoRoot++;
  56323. /* The new root-page may not be allocated on a pointer-map page, or the
  56324. ** PENDING_BYTE page.
  56325. */
  56326. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  56327. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  56328. pgnoRoot++;
  56329. }
  56330. assert( pgnoRoot>=3 );
  56331. /* Allocate a page. The page that currently resides at pgnoRoot will
  56332. ** be moved to the allocated page (unless the allocated page happens
  56333. ** to reside at pgnoRoot).
  56334. */
  56335. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  56336. if( rc!=SQLITE_OK ){
  56337. return rc;
  56338. }
  56339. if( pgnoMove!=pgnoRoot ){
  56340. /* pgnoRoot is the page that will be used for the root-page of
  56341. ** the new table (assuming an error did not occur). But we were
  56342. ** allocated pgnoMove. If required (i.e. if it was not allocated
  56343. ** by extending the file), the current page at position pgnoMove
  56344. ** is already journaled.
  56345. */
  56346. u8 eType = 0;
  56347. Pgno iPtrPage = 0;
  56348. /* Save the positions of any open cursors. This is required in
  56349. ** case they are holding a reference to an xFetch reference
  56350. ** corresponding to page pgnoRoot. */
  56351. rc = saveAllCursors(pBt, 0, 0);
  56352. releasePage(pPageMove);
  56353. if( rc!=SQLITE_OK ){
  56354. return rc;
  56355. }
  56356. /* Move the page currently at pgnoRoot to pgnoMove. */
  56357. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56358. if( rc!=SQLITE_OK ){
  56359. return rc;
  56360. }
  56361. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  56362. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  56363. rc = SQLITE_CORRUPT_BKPT;
  56364. }
  56365. if( rc!=SQLITE_OK ){
  56366. releasePage(pRoot);
  56367. return rc;
  56368. }
  56369. assert( eType!=PTRMAP_ROOTPAGE );
  56370. assert( eType!=PTRMAP_FREEPAGE );
  56371. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  56372. releasePage(pRoot);
  56373. /* Obtain the page at pgnoRoot */
  56374. if( rc!=SQLITE_OK ){
  56375. return rc;
  56376. }
  56377. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56378. if( rc!=SQLITE_OK ){
  56379. return rc;
  56380. }
  56381. rc = sqlite3PagerWrite(pRoot->pDbPage);
  56382. if( rc!=SQLITE_OK ){
  56383. releasePage(pRoot);
  56384. return rc;
  56385. }
  56386. }else{
  56387. pRoot = pPageMove;
  56388. }
  56389. /* Update the pointer-map and meta-data with the new root-page number. */
  56390. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  56391. if( rc ){
  56392. releasePage(pRoot);
  56393. return rc;
  56394. }
  56395. /* When the new root page was allocated, page 1 was made writable in
  56396. ** order either to increase the database filesize, or to decrement the
  56397. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  56398. */
  56399. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  56400. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  56401. if( NEVER(rc) ){
  56402. releasePage(pRoot);
  56403. return rc;
  56404. }
  56405. }else{
  56406. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56407. if( rc ) return rc;
  56408. }
  56409. #endif
  56410. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  56411. if( createTabFlags & BTREE_INTKEY ){
  56412. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  56413. }else{
  56414. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  56415. }
  56416. zeroPage(pRoot, ptfFlags);
  56417. sqlite3PagerUnref(pRoot->pDbPage);
  56418. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  56419. *piTable = (int)pgnoRoot;
  56420. return SQLITE_OK;
  56421. }
  56422. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  56423. int rc;
  56424. sqlite3BtreeEnter(p);
  56425. rc = btreeCreateTable(p, piTable, flags);
  56426. sqlite3BtreeLeave(p);
  56427. return rc;
  56428. }
  56429. /*
  56430. ** Erase the given database page and all its children. Return
  56431. ** the page to the freelist.
  56432. */
  56433. static int clearDatabasePage(
  56434. BtShared *pBt, /* The BTree that contains the table */
  56435. Pgno pgno, /* Page number to clear */
  56436. int freePageFlag, /* Deallocate page if true */
  56437. int *pnChange /* Add number of Cells freed to this counter */
  56438. ){
  56439. MemPage *pPage;
  56440. int rc;
  56441. unsigned char *pCell;
  56442. int i;
  56443. assert( sqlite3_mutex_held(pBt->mutex) );
  56444. if( pgno>btreePagecount(pBt) ){
  56445. return SQLITE_CORRUPT_BKPT;
  56446. }
  56447. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  56448. if( rc ) return rc;
  56449. for(i=0; i<pPage->nCell; i++){
  56450. pCell = findCell(pPage, i);
  56451. if( !pPage->leaf ){
  56452. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  56453. if( rc ) goto cleardatabasepage_out;
  56454. }
  56455. rc = clearCell(pPage, pCell);
  56456. if( rc ) goto cleardatabasepage_out;
  56457. }
  56458. if( !pPage->leaf ){
  56459. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  56460. if( rc ) goto cleardatabasepage_out;
  56461. }else if( pnChange ){
  56462. assert( pPage->intKey );
  56463. *pnChange += pPage->nCell;
  56464. }
  56465. if( freePageFlag ){
  56466. freePage(pPage, &rc);
  56467. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  56468. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  56469. }
  56470. cleardatabasepage_out:
  56471. releasePage(pPage);
  56472. return rc;
  56473. }
  56474. /*
  56475. ** Delete all information from a single table in the database. iTable is
  56476. ** the page number of the root of the table. After this routine returns,
  56477. ** the root page is empty, but still exists.
  56478. **
  56479. ** This routine will fail with SQLITE_LOCKED if there are any open
  56480. ** read cursors on the table. Open write cursors are moved to the
  56481. ** root of the table.
  56482. **
  56483. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  56484. ** integer value pointed to by pnChange is incremented by the number of
  56485. ** entries in the table.
  56486. */
  56487. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  56488. int rc;
  56489. BtShared *pBt = p->pBt;
  56490. sqlite3BtreeEnter(p);
  56491. assert( p->inTrans==TRANS_WRITE );
  56492. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  56493. if( SQLITE_OK==rc ){
  56494. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  56495. ** is the root of a table b-tree - if it is not, the following call is
  56496. ** a no-op). */
  56497. invalidateIncrblobCursors(p, 0, 1);
  56498. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  56499. }
  56500. sqlite3BtreeLeave(p);
  56501. return rc;
  56502. }
  56503. /*
  56504. ** Erase all information in a table and add the root of the table to
  56505. ** the freelist. Except, the root of the principle table (the one on
  56506. ** page 1) is never added to the freelist.
  56507. **
  56508. ** This routine will fail with SQLITE_LOCKED if there are any open
  56509. ** cursors on the table.
  56510. **
  56511. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  56512. ** root page in the database file, then the last root page
  56513. ** in the database file is moved into the slot formerly occupied by
  56514. ** iTable and that last slot formerly occupied by the last root page
  56515. ** is added to the freelist instead of iTable. In this say, all
  56516. ** root pages are kept at the beginning of the database file, which
  56517. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  56518. ** page number that used to be the last root page in the file before
  56519. ** the move. If no page gets moved, *piMoved is set to 0.
  56520. ** The last root page is recorded in meta[3] and the value of
  56521. ** meta[3] is updated by this procedure.
  56522. */
  56523. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  56524. int rc;
  56525. MemPage *pPage = 0;
  56526. BtShared *pBt = p->pBt;
  56527. assert( sqlite3BtreeHoldsMutex(p) );
  56528. assert( p->inTrans==TRANS_WRITE );
  56529. /* It is illegal to drop a table if any cursors are open on the
  56530. ** database. This is because in auto-vacuum mode the backend may
  56531. ** need to move another root-page to fill a gap left by the deleted
  56532. ** root page. If an open cursor was using this page a problem would
  56533. ** occur.
  56534. **
  56535. ** This error is caught long before control reaches this point.
  56536. */
  56537. if( NEVER(pBt->pCursor) ){
  56538. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  56539. return SQLITE_LOCKED_SHAREDCACHE;
  56540. }
  56541. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  56542. if( rc ) return rc;
  56543. rc = sqlite3BtreeClearTable(p, iTable, 0);
  56544. if( rc ){
  56545. releasePage(pPage);
  56546. return rc;
  56547. }
  56548. *piMoved = 0;
  56549. if( iTable>1 ){
  56550. #ifdef SQLITE_OMIT_AUTOVACUUM
  56551. freePage(pPage, &rc);
  56552. releasePage(pPage);
  56553. #else
  56554. if( pBt->autoVacuum ){
  56555. Pgno maxRootPgno;
  56556. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  56557. if( iTable==maxRootPgno ){
  56558. /* If the table being dropped is the table with the largest root-page
  56559. ** number in the database, put the root page on the free list.
  56560. */
  56561. freePage(pPage, &rc);
  56562. releasePage(pPage);
  56563. if( rc!=SQLITE_OK ){
  56564. return rc;
  56565. }
  56566. }else{
  56567. /* The table being dropped does not have the largest root-page
  56568. ** number in the database. So move the page that does into the
  56569. ** gap left by the deleted root-page.
  56570. */
  56571. MemPage *pMove;
  56572. releasePage(pPage);
  56573. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56574. if( rc!=SQLITE_OK ){
  56575. return rc;
  56576. }
  56577. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  56578. releasePage(pMove);
  56579. if( rc!=SQLITE_OK ){
  56580. return rc;
  56581. }
  56582. pMove = 0;
  56583. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56584. freePage(pMove, &rc);
  56585. releasePage(pMove);
  56586. if( rc!=SQLITE_OK ){
  56587. return rc;
  56588. }
  56589. *piMoved = maxRootPgno;
  56590. }
  56591. /* Set the new 'max-root-page' value in the database header. This
  56592. ** is the old value less one, less one more if that happens to
  56593. ** be a root-page number, less one again if that is the
  56594. ** PENDING_BYTE_PAGE.
  56595. */
  56596. maxRootPgno--;
  56597. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  56598. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  56599. maxRootPgno--;
  56600. }
  56601. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  56602. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  56603. }else{
  56604. freePage(pPage, &rc);
  56605. releasePage(pPage);
  56606. }
  56607. #endif
  56608. }else{
  56609. /* If sqlite3BtreeDropTable was called on page 1.
  56610. ** This really never should happen except in a corrupt
  56611. ** database.
  56612. */
  56613. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  56614. releasePage(pPage);
  56615. }
  56616. return rc;
  56617. }
  56618. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  56619. int rc;
  56620. sqlite3BtreeEnter(p);
  56621. rc = btreeDropTable(p, iTable, piMoved);
  56622. sqlite3BtreeLeave(p);
  56623. return rc;
  56624. }
  56625. /*
  56626. ** This function may only be called if the b-tree connection already
  56627. ** has a read or write transaction open on the database.
  56628. **
  56629. ** Read the meta-information out of a database file. Meta[0]
  56630. ** is the number of free pages currently in the database. Meta[1]
  56631. ** through meta[15] are available for use by higher layers. Meta[0]
  56632. ** is read-only, the others are read/write.
  56633. **
  56634. ** The schema layer numbers meta values differently. At the schema
  56635. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  56636. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  56637. */
  56638. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  56639. BtShared *pBt = p->pBt;
  56640. sqlite3BtreeEnter(p);
  56641. assert( p->inTrans>TRANS_NONE );
  56642. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  56643. assert( pBt->pPage1 );
  56644. assert( idx>=0 && idx<=15 );
  56645. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  56646. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  56647. ** database, mark the database as read-only. */
  56648. #ifdef SQLITE_OMIT_AUTOVACUUM
  56649. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  56650. pBt->btsFlags |= BTS_READ_ONLY;
  56651. }
  56652. #endif
  56653. sqlite3BtreeLeave(p);
  56654. }
  56655. /*
  56656. ** Write meta-information back into the database. Meta[0] is
  56657. ** read-only and may not be written.
  56658. */
  56659. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  56660. BtShared *pBt = p->pBt;
  56661. unsigned char *pP1;
  56662. int rc;
  56663. assert( idx>=1 && idx<=15 );
  56664. sqlite3BtreeEnter(p);
  56665. assert( p->inTrans==TRANS_WRITE );
  56666. assert( pBt->pPage1!=0 );
  56667. pP1 = pBt->pPage1->aData;
  56668. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56669. if( rc==SQLITE_OK ){
  56670. put4byte(&pP1[36 + idx*4], iMeta);
  56671. #ifndef SQLITE_OMIT_AUTOVACUUM
  56672. if( idx==BTREE_INCR_VACUUM ){
  56673. assert( pBt->autoVacuum || iMeta==0 );
  56674. assert( iMeta==0 || iMeta==1 );
  56675. pBt->incrVacuum = (u8)iMeta;
  56676. }
  56677. #endif
  56678. }
  56679. sqlite3BtreeLeave(p);
  56680. return rc;
  56681. }
  56682. #ifndef SQLITE_OMIT_BTREECOUNT
  56683. /*
  56684. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  56685. ** number of entries in the b-tree and write the result to *pnEntry.
  56686. **
  56687. ** SQLITE_OK is returned if the operation is successfully executed.
  56688. ** Otherwise, if an error is encountered (i.e. an IO error or database
  56689. ** corruption) an SQLite error code is returned.
  56690. */
  56691. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  56692. i64 nEntry = 0; /* Value to return in *pnEntry */
  56693. int rc; /* Return code */
  56694. if( pCur->pgnoRoot==0 ){
  56695. *pnEntry = 0;
  56696. return SQLITE_OK;
  56697. }
  56698. rc = moveToRoot(pCur);
  56699. /* Unless an error occurs, the following loop runs one iteration for each
  56700. ** page in the B-Tree structure (not including overflow pages).
  56701. */
  56702. while( rc==SQLITE_OK ){
  56703. int iIdx; /* Index of child node in parent */
  56704. MemPage *pPage; /* Current page of the b-tree */
  56705. /* If this is a leaf page or the tree is not an int-key tree, then
  56706. ** this page contains countable entries. Increment the entry counter
  56707. ** accordingly.
  56708. */
  56709. pPage = pCur->apPage[pCur->iPage];
  56710. if( pPage->leaf || !pPage->intKey ){
  56711. nEntry += pPage->nCell;
  56712. }
  56713. /* pPage is a leaf node. This loop navigates the cursor so that it
  56714. ** points to the first interior cell that it points to the parent of
  56715. ** the next page in the tree that has not yet been visited. The
  56716. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  56717. ** of the page, or to the number of cells in the page if the next page
  56718. ** to visit is the right-child of its parent.
  56719. **
  56720. ** If all pages in the tree have been visited, return SQLITE_OK to the
  56721. ** caller.
  56722. */
  56723. if( pPage->leaf ){
  56724. do {
  56725. if( pCur->iPage==0 ){
  56726. /* All pages of the b-tree have been visited. Return successfully. */
  56727. *pnEntry = nEntry;
  56728. return SQLITE_OK;
  56729. }
  56730. moveToParent(pCur);
  56731. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  56732. pCur->aiIdx[pCur->iPage]++;
  56733. pPage = pCur->apPage[pCur->iPage];
  56734. }
  56735. /* Descend to the child node of the cell that the cursor currently
  56736. ** points at. This is the right-child if (iIdx==pPage->nCell).
  56737. */
  56738. iIdx = pCur->aiIdx[pCur->iPage];
  56739. if( iIdx==pPage->nCell ){
  56740. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  56741. }else{
  56742. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  56743. }
  56744. }
  56745. /* An error has occurred. Return an error code. */
  56746. return rc;
  56747. }
  56748. #endif
  56749. /*
  56750. ** Return the pager associated with a BTree. This routine is used for
  56751. ** testing and debugging only.
  56752. */
  56753. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  56754. return p->pBt->pPager;
  56755. }
  56756. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56757. /*
  56758. ** Append a message to the error message string.
  56759. */
  56760. static void checkAppendMsg(
  56761. IntegrityCk *pCheck,
  56762. char *zMsg1,
  56763. const char *zFormat,
  56764. ...
  56765. ){
  56766. va_list ap;
  56767. if( !pCheck->mxErr ) return;
  56768. pCheck->mxErr--;
  56769. pCheck->nErr++;
  56770. va_start(ap, zFormat);
  56771. if( pCheck->errMsg.nChar ){
  56772. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  56773. }
  56774. if( zMsg1 ){
  56775. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  56776. }
  56777. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  56778. va_end(ap);
  56779. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  56780. pCheck->mallocFailed = 1;
  56781. }
  56782. }
  56783. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56784. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56785. /*
  56786. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  56787. ** corresponds to page iPg is already set.
  56788. */
  56789. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56790. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56791. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  56792. }
  56793. /*
  56794. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  56795. */
  56796. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56797. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56798. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  56799. }
  56800. /*
  56801. ** Add 1 to the reference count for page iPage. If this is the second
  56802. ** reference to the page, add an error message to pCheck->zErrMsg.
  56803. ** Return 1 if there are 2 ore more references to the page and 0 if
  56804. ** if this is the first reference to the page.
  56805. **
  56806. ** Also check that the page number is in bounds.
  56807. */
  56808. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  56809. if( iPage==0 ) return 1;
  56810. if( iPage>pCheck->nPage ){
  56811. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  56812. return 1;
  56813. }
  56814. if( getPageReferenced(pCheck, iPage) ){
  56815. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  56816. return 1;
  56817. }
  56818. setPageReferenced(pCheck, iPage);
  56819. return 0;
  56820. }
  56821. #ifndef SQLITE_OMIT_AUTOVACUUM
  56822. /*
  56823. ** Check that the entry in the pointer-map for page iChild maps to
  56824. ** page iParent, pointer type ptrType. If not, append an error message
  56825. ** to pCheck.
  56826. */
  56827. static void checkPtrmap(
  56828. IntegrityCk *pCheck, /* Integrity check context */
  56829. Pgno iChild, /* Child page number */
  56830. u8 eType, /* Expected pointer map type */
  56831. Pgno iParent, /* Expected pointer map parent page number */
  56832. char *zContext /* Context description (used for error msg) */
  56833. ){
  56834. int rc;
  56835. u8 ePtrmapType;
  56836. Pgno iPtrmapParent;
  56837. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  56838. if( rc!=SQLITE_OK ){
  56839. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  56840. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  56841. return;
  56842. }
  56843. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  56844. checkAppendMsg(pCheck, zContext,
  56845. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  56846. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  56847. }
  56848. }
  56849. #endif
  56850. /*
  56851. ** Check the integrity of the freelist or of an overflow page list.
  56852. ** Verify that the number of pages on the list is N.
  56853. */
  56854. static void checkList(
  56855. IntegrityCk *pCheck, /* Integrity checking context */
  56856. int isFreeList, /* True for a freelist. False for overflow page list */
  56857. int iPage, /* Page number for first page in the list */
  56858. int N, /* Expected number of pages in the list */
  56859. char *zContext /* Context for error messages */
  56860. ){
  56861. int i;
  56862. int expected = N;
  56863. int iFirst = iPage;
  56864. while( N-- > 0 && pCheck->mxErr ){
  56865. DbPage *pOvflPage;
  56866. unsigned char *pOvflData;
  56867. if( iPage<1 ){
  56868. checkAppendMsg(pCheck, zContext,
  56869. "%d of %d pages missing from overflow list starting at %d",
  56870. N+1, expected, iFirst);
  56871. break;
  56872. }
  56873. if( checkRef(pCheck, iPage, zContext) ) break;
  56874. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  56875. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  56876. break;
  56877. }
  56878. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  56879. if( isFreeList ){
  56880. int n = get4byte(&pOvflData[4]);
  56881. #ifndef SQLITE_OMIT_AUTOVACUUM
  56882. if( pCheck->pBt->autoVacuum ){
  56883. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  56884. }
  56885. #endif
  56886. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  56887. checkAppendMsg(pCheck, zContext,
  56888. "freelist leaf count too big on page %d", iPage);
  56889. N--;
  56890. }else{
  56891. for(i=0; i<n; i++){
  56892. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  56893. #ifndef SQLITE_OMIT_AUTOVACUUM
  56894. if( pCheck->pBt->autoVacuum ){
  56895. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  56896. }
  56897. #endif
  56898. checkRef(pCheck, iFreePage, zContext);
  56899. }
  56900. N -= n;
  56901. }
  56902. }
  56903. #ifndef SQLITE_OMIT_AUTOVACUUM
  56904. else{
  56905. /* If this database supports auto-vacuum and iPage is not the last
  56906. ** page in this overflow list, check that the pointer-map entry for
  56907. ** the following page matches iPage.
  56908. */
  56909. if( pCheck->pBt->autoVacuum && N>0 ){
  56910. i = get4byte(pOvflData);
  56911. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  56912. }
  56913. }
  56914. #endif
  56915. iPage = get4byte(pOvflData);
  56916. sqlite3PagerUnref(pOvflPage);
  56917. }
  56918. }
  56919. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56920. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56921. /*
  56922. ** Do various sanity checks on a single page of a tree. Return
  56923. ** the tree depth. Root pages return 0. Parents of root pages
  56924. ** return 1, and so forth.
  56925. **
  56926. ** These checks are done:
  56927. **
  56928. ** 1. Make sure that cells and freeblocks do not overlap
  56929. ** but combine to completely cover the page.
  56930. ** NO 2. Make sure cell keys are in order.
  56931. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  56932. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  56933. ** 5. Check the integrity of overflow pages.
  56934. ** 6. Recursively call checkTreePage on all children.
  56935. ** 7. Verify that the depth of all children is the same.
  56936. ** 8. Make sure this page is at least 33% full or else it is
  56937. ** the root of the tree.
  56938. */
  56939. static int checkTreePage(
  56940. IntegrityCk *pCheck, /* Context for the sanity check */
  56941. int iPage, /* Page number of the page to check */
  56942. char *zParentContext, /* Parent context */
  56943. i64 *pnParentMinKey,
  56944. i64 *pnParentMaxKey
  56945. ){
  56946. MemPage *pPage;
  56947. int i, rc, depth, d2, pgno, cnt;
  56948. int hdr, cellStart;
  56949. int nCell;
  56950. u8 *data;
  56951. BtShared *pBt;
  56952. int usableSize;
  56953. char zContext[100];
  56954. char *hit = 0;
  56955. i64 nMinKey = 0;
  56956. i64 nMaxKey = 0;
  56957. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  56958. /* Check that the page exists
  56959. */
  56960. pBt = pCheck->pBt;
  56961. usableSize = pBt->usableSize;
  56962. if( iPage==0 ) return 0;
  56963. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  56964. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  56965. checkAppendMsg(pCheck, zContext,
  56966. "unable to get the page. error code=%d", rc);
  56967. return 0;
  56968. }
  56969. /* Clear MemPage.isInit to make sure the corruption detection code in
  56970. ** btreeInitPage() is executed. */
  56971. pPage->isInit = 0;
  56972. if( (rc = btreeInitPage(pPage))!=0 ){
  56973. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  56974. checkAppendMsg(pCheck, zContext,
  56975. "btreeInitPage() returns error code %d", rc);
  56976. releasePage(pPage);
  56977. return 0;
  56978. }
  56979. /* Check out all the cells.
  56980. */
  56981. depth = 0;
  56982. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  56983. u8 *pCell;
  56984. u32 sz;
  56985. CellInfo info;
  56986. /* Check payload overflow pages
  56987. */
  56988. sqlite3_snprintf(sizeof(zContext), zContext,
  56989. "On tree page %d cell %d: ", iPage, i);
  56990. pCell = findCell(pPage,i);
  56991. btreeParseCellPtr(pPage, pCell, &info);
  56992. sz = info.nData;
  56993. if( !pPage->intKey ) sz += (int)info.nKey;
  56994. /* For intKey pages, check that the keys are in order.
  56995. */
  56996. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  56997. else{
  56998. if( info.nKey <= nMaxKey ){
  56999. checkAppendMsg(pCheck, zContext,
  57000. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  57001. }
  57002. nMaxKey = info.nKey;
  57003. }
  57004. assert( sz==info.nPayload );
  57005. if( (sz>info.nLocal)
  57006. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  57007. ){
  57008. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  57009. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  57010. #ifndef SQLITE_OMIT_AUTOVACUUM
  57011. if( pBt->autoVacuum ){
  57012. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  57013. }
  57014. #endif
  57015. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  57016. }
  57017. /* Check sanity of left child page.
  57018. */
  57019. if( !pPage->leaf ){
  57020. pgno = get4byte(pCell);
  57021. #ifndef SQLITE_OMIT_AUTOVACUUM
  57022. if( pBt->autoVacuum ){
  57023. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  57024. }
  57025. #endif
  57026. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  57027. if( i>0 && d2!=depth ){
  57028. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  57029. }
  57030. depth = d2;
  57031. }
  57032. }
  57033. if( !pPage->leaf ){
  57034. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57035. sqlite3_snprintf(sizeof(zContext), zContext,
  57036. "On page %d at right child: ", iPage);
  57037. #ifndef SQLITE_OMIT_AUTOVACUUM
  57038. if( pBt->autoVacuum ){
  57039. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  57040. }
  57041. #endif
  57042. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  57043. }
  57044. /* For intKey leaf pages, check that the min/max keys are in order
  57045. ** with any left/parent/right pages.
  57046. */
  57047. if( pPage->leaf && pPage->intKey ){
  57048. /* if we are a left child page */
  57049. if( pnParentMinKey ){
  57050. /* if we are the left most child page */
  57051. if( !pnParentMaxKey ){
  57052. if( nMaxKey > *pnParentMinKey ){
  57053. checkAppendMsg(pCheck, zContext,
  57054. "Rowid %lld out of order (max larger than parent min of %lld)",
  57055. nMaxKey, *pnParentMinKey);
  57056. }
  57057. }else{
  57058. if( nMinKey <= *pnParentMinKey ){
  57059. checkAppendMsg(pCheck, zContext,
  57060. "Rowid %lld out of order (min less than parent min of %lld)",
  57061. nMinKey, *pnParentMinKey);
  57062. }
  57063. if( nMaxKey > *pnParentMaxKey ){
  57064. checkAppendMsg(pCheck, zContext,
  57065. "Rowid %lld out of order (max larger than parent max of %lld)",
  57066. nMaxKey, *pnParentMaxKey);
  57067. }
  57068. *pnParentMinKey = nMaxKey;
  57069. }
  57070. /* else if we're a right child page */
  57071. } else if( pnParentMaxKey ){
  57072. if( nMinKey <= *pnParentMaxKey ){
  57073. checkAppendMsg(pCheck, zContext,
  57074. "Rowid %lld out of order (min less than parent max of %lld)",
  57075. nMinKey, *pnParentMaxKey);
  57076. }
  57077. }
  57078. }
  57079. /* Check for complete coverage of the page
  57080. */
  57081. data = pPage->aData;
  57082. hdr = pPage->hdrOffset;
  57083. hit = sqlite3PageMalloc( pBt->pageSize );
  57084. if( hit==0 ){
  57085. pCheck->mallocFailed = 1;
  57086. }else{
  57087. int contentOffset = get2byteNotZero(&data[hdr+5]);
  57088. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  57089. memset(hit+contentOffset, 0, usableSize-contentOffset);
  57090. memset(hit, 1, contentOffset);
  57091. nCell = get2byte(&data[hdr+3]);
  57092. cellStart = hdr + 12 - 4*pPage->leaf;
  57093. for(i=0; i<nCell; i++){
  57094. int pc = get2byte(&data[cellStart+i*2]);
  57095. u32 size = 65536;
  57096. int j;
  57097. if( pc<=usableSize-4 ){
  57098. size = cellSizePtr(pPage, &data[pc]);
  57099. }
  57100. if( (int)(pc+size-1)>=usableSize ){
  57101. checkAppendMsg(pCheck, 0,
  57102. "Corruption detected in cell %d on page %d",i,iPage);
  57103. }else{
  57104. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  57105. }
  57106. }
  57107. i = get2byte(&data[hdr+1]);
  57108. while( i>0 ){
  57109. int size, j;
  57110. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57111. size = get2byte(&data[i+2]);
  57112. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  57113. for(j=i+size-1; j>=i; j--) hit[j]++;
  57114. j = get2byte(&data[i]);
  57115. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  57116. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57117. i = j;
  57118. }
  57119. for(i=cnt=0; i<usableSize; i++){
  57120. if( hit[i]==0 ){
  57121. cnt++;
  57122. }else if( hit[i]>1 ){
  57123. checkAppendMsg(pCheck, 0,
  57124. "Multiple uses for byte %d of page %d", i, iPage);
  57125. break;
  57126. }
  57127. }
  57128. if( cnt!=data[hdr+7] ){
  57129. checkAppendMsg(pCheck, 0,
  57130. "Fragmentation of %d bytes reported as %d on page %d",
  57131. cnt, data[hdr+7], iPage);
  57132. }
  57133. }
  57134. sqlite3PageFree(hit);
  57135. releasePage(pPage);
  57136. return depth+1;
  57137. }
  57138. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57139. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57140. /*
  57141. ** This routine does a complete check of the given BTree file. aRoot[] is
  57142. ** an array of pages numbers were each page number is the root page of
  57143. ** a table. nRoot is the number of entries in aRoot.
  57144. **
  57145. ** A read-only or read-write transaction must be opened before calling
  57146. ** this function.
  57147. **
  57148. ** Write the number of error seen in *pnErr. Except for some memory
  57149. ** allocation errors, an error message held in memory obtained from
  57150. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  57151. ** returned. If a memory allocation error occurs, NULL is returned.
  57152. */
  57153. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  57154. Btree *p, /* The btree to be checked */
  57155. int *aRoot, /* An array of root pages numbers for individual trees */
  57156. int nRoot, /* Number of entries in aRoot[] */
  57157. int mxErr, /* Stop reporting errors after this many */
  57158. int *pnErr /* Write number of errors seen to this variable */
  57159. ){
  57160. Pgno i;
  57161. int nRef;
  57162. IntegrityCk sCheck;
  57163. BtShared *pBt = p->pBt;
  57164. char zErr[100];
  57165. sqlite3BtreeEnter(p);
  57166. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  57167. nRef = sqlite3PagerRefcount(pBt->pPager);
  57168. sCheck.pBt = pBt;
  57169. sCheck.pPager = pBt->pPager;
  57170. sCheck.nPage = btreePagecount(sCheck.pBt);
  57171. sCheck.mxErr = mxErr;
  57172. sCheck.nErr = 0;
  57173. sCheck.mallocFailed = 0;
  57174. *pnErr = 0;
  57175. if( sCheck.nPage==0 ){
  57176. sqlite3BtreeLeave(p);
  57177. return 0;
  57178. }
  57179. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  57180. if( !sCheck.aPgRef ){
  57181. *pnErr = 1;
  57182. sqlite3BtreeLeave(p);
  57183. return 0;
  57184. }
  57185. i = PENDING_BYTE_PAGE(pBt);
  57186. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  57187. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  57188. sCheck.errMsg.useMalloc = 2;
  57189. /* Check the integrity of the freelist
  57190. */
  57191. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  57192. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  57193. /* Check all the tables.
  57194. */
  57195. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  57196. if( aRoot[i]==0 ) continue;
  57197. #ifndef SQLITE_OMIT_AUTOVACUUM
  57198. if( pBt->autoVacuum && aRoot[i]>1 ){
  57199. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  57200. }
  57201. #endif
  57202. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  57203. }
  57204. /* Make sure every page in the file is referenced
  57205. */
  57206. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  57207. #ifdef SQLITE_OMIT_AUTOVACUUM
  57208. if( getPageReferenced(&sCheck, i)==0 ){
  57209. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  57210. }
  57211. #else
  57212. /* If the database supports auto-vacuum, make sure no tables contain
  57213. ** references to pointer-map pages.
  57214. */
  57215. if( getPageReferenced(&sCheck, i)==0 &&
  57216. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  57217. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  57218. }
  57219. if( getPageReferenced(&sCheck, i)!=0 &&
  57220. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  57221. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  57222. }
  57223. #endif
  57224. }
  57225. /* Make sure this analysis did not leave any unref() pages.
  57226. ** This is an internal consistency check; an integrity check
  57227. ** of the integrity check.
  57228. */
  57229. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  57230. checkAppendMsg(&sCheck, 0,
  57231. "Outstanding page count goes from %d to %d during this analysis",
  57232. nRef, sqlite3PagerRefcount(pBt->pPager)
  57233. );
  57234. }
  57235. /* Clean up and report errors.
  57236. */
  57237. sqlite3BtreeLeave(p);
  57238. sqlite3_free(sCheck.aPgRef);
  57239. if( sCheck.mallocFailed ){
  57240. sqlite3StrAccumReset(&sCheck.errMsg);
  57241. *pnErr = sCheck.nErr+1;
  57242. return 0;
  57243. }
  57244. *pnErr = sCheck.nErr;
  57245. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  57246. return sqlite3StrAccumFinish(&sCheck.errMsg);
  57247. }
  57248. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57249. /*
  57250. ** Return the full pathname of the underlying database file. Return
  57251. ** an empty string if the database is in-memory or a TEMP database.
  57252. **
  57253. ** The pager filename is invariant as long as the pager is
  57254. ** open so it is safe to access without the BtShared mutex.
  57255. */
  57256. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  57257. assert( p->pBt->pPager!=0 );
  57258. return sqlite3PagerFilename(p->pBt->pPager, 1);
  57259. }
  57260. /*
  57261. ** Return the pathname of the journal file for this database. The return
  57262. ** value of this routine is the same regardless of whether the journal file
  57263. ** has been created or not.
  57264. **
  57265. ** The pager journal filename is invariant as long as the pager is
  57266. ** open so it is safe to access without the BtShared mutex.
  57267. */
  57268. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  57269. assert( p->pBt->pPager!=0 );
  57270. return sqlite3PagerJournalname(p->pBt->pPager);
  57271. }
  57272. /*
  57273. ** Return non-zero if a transaction is active.
  57274. */
  57275. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  57276. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  57277. return (p && (p->inTrans==TRANS_WRITE));
  57278. }
  57279. #ifndef SQLITE_OMIT_WAL
  57280. /*
  57281. ** Run a checkpoint on the Btree passed as the first argument.
  57282. **
  57283. ** Return SQLITE_LOCKED if this or any other connection has an open
  57284. ** transaction on the shared-cache the argument Btree is connected to.
  57285. **
  57286. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  57287. */
  57288. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  57289. int rc = SQLITE_OK;
  57290. if( p ){
  57291. BtShared *pBt = p->pBt;
  57292. sqlite3BtreeEnter(p);
  57293. if( pBt->inTransaction!=TRANS_NONE ){
  57294. rc = SQLITE_LOCKED;
  57295. }else{
  57296. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  57297. }
  57298. sqlite3BtreeLeave(p);
  57299. }
  57300. return rc;
  57301. }
  57302. #endif
  57303. /*
  57304. ** Return non-zero if a read (or write) transaction is active.
  57305. */
  57306. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  57307. assert( p );
  57308. assert( sqlite3_mutex_held(p->db->mutex) );
  57309. return p->inTrans!=TRANS_NONE;
  57310. }
  57311. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  57312. assert( p );
  57313. assert( sqlite3_mutex_held(p->db->mutex) );
  57314. return p->nBackup!=0;
  57315. }
  57316. /*
  57317. ** This function returns a pointer to a blob of memory associated with
  57318. ** a single shared-btree. The memory is used by client code for its own
  57319. ** purposes (for example, to store a high-level schema associated with
  57320. ** the shared-btree). The btree layer manages reference counting issues.
  57321. **
  57322. ** The first time this is called on a shared-btree, nBytes bytes of memory
  57323. ** are allocated, zeroed, and returned to the caller. For each subsequent
  57324. ** call the nBytes parameter is ignored and a pointer to the same blob
  57325. ** of memory returned.
  57326. **
  57327. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  57328. ** allocated, a null pointer is returned. If the blob has already been
  57329. ** allocated, it is returned as normal.
  57330. **
  57331. ** Just before the shared-btree is closed, the function passed as the
  57332. ** xFree argument when the memory allocation was made is invoked on the
  57333. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  57334. ** on the memory, the btree layer does that.
  57335. */
  57336. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  57337. BtShared *pBt = p->pBt;
  57338. sqlite3BtreeEnter(p);
  57339. if( !pBt->pSchema && nBytes ){
  57340. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  57341. pBt->xFreeSchema = xFree;
  57342. }
  57343. sqlite3BtreeLeave(p);
  57344. return pBt->pSchema;
  57345. }
  57346. /*
  57347. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  57348. ** btree as the argument handle holds an exclusive lock on the
  57349. ** sqlite_master table. Otherwise SQLITE_OK.
  57350. */
  57351. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  57352. int rc;
  57353. assert( sqlite3_mutex_held(p->db->mutex) );
  57354. sqlite3BtreeEnter(p);
  57355. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  57356. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  57357. sqlite3BtreeLeave(p);
  57358. return rc;
  57359. }
  57360. #ifndef SQLITE_OMIT_SHARED_CACHE
  57361. /*
  57362. ** Obtain a lock on the table whose root page is iTab. The
  57363. ** lock is a write lock if isWritelock is true or a read lock
  57364. ** if it is false.
  57365. */
  57366. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  57367. int rc = SQLITE_OK;
  57368. assert( p->inTrans!=TRANS_NONE );
  57369. if( p->sharable ){
  57370. u8 lockType = READ_LOCK + isWriteLock;
  57371. assert( READ_LOCK+1==WRITE_LOCK );
  57372. assert( isWriteLock==0 || isWriteLock==1 );
  57373. sqlite3BtreeEnter(p);
  57374. rc = querySharedCacheTableLock(p, iTab, lockType);
  57375. if( rc==SQLITE_OK ){
  57376. rc = setSharedCacheTableLock(p, iTab, lockType);
  57377. }
  57378. sqlite3BtreeLeave(p);
  57379. }
  57380. return rc;
  57381. }
  57382. #endif
  57383. #ifndef SQLITE_OMIT_INCRBLOB
  57384. /*
  57385. ** Argument pCsr must be a cursor opened for writing on an
  57386. ** INTKEY table currently pointing at a valid table entry.
  57387. ** This function modifies the data stored as part of that entry.
  57388. **
  57389. ** Only the data content may only be modified, it is not possible to
  57390. ** change the length of the data stored. If this function is called with
  57391. ** parameters that attempt to write past the end of the existing data,
  57392. ** no modifications are made and SQLITE_CORRUPT is returned.
  57393. */
  57394. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  57395. int rc;
  57396. assert( cursorHoldsMutex(pCsr) );
  57397. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  57398. assert( pCsr->isIncrblobHandle );
  57399. rc = restoreCursorPosition(pCsr);
  57400. if( rc!=SQLITE_OK ){
  57401. return rc;
  57402. }
  57403. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  57404. if( pCsr->eState!=CURSOR_VALID ){
  57405. return SQLITE_ABORT;
  57406. }
  57407. /* Save the positions of all other cursors open on this table. This is
  57408. ** required in case any of them are holding references to an xFetch
  57409. ** version of the b-tree page modified by the accessPayload call below.
  57410. **
  57411. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  57412. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  57413. ** saveAllCursors can only return SQLITE_OK.
  57414. */
  57415. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  57416. assert( rc==SQLITE_OK );
  57417. /* Check some assumptions:
  57418. ** (a) the cursor is open for writing,
  57419. ** (b) there is a read/write transaction open,
  57420. ** (c) the connection holds a write-lock on the table (if required),
  57421. ** (d) there are no conflicting read-locks, and
  57422. ** (e) the cursor points at a valid row of an intKey table.
  57423. */
  57424. if( !pCsr->wrFlag ){
  57425. return SQLITE_READONLY;
  57426. }
  57427. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  57428. && pCsr->pBt->inTransaction==TRANS_WRITE );
  57429. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  57430. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  57431. assert( pCsr->apPage[pCsr->iPage]->intKey );
  57432. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  57433. }
  57434. /*
  57435. ** Set a flag on this cursor to cache the locations of pages from the
  57436. ** overflow list for the current row. This is used by cursors opened
  57437. ** for incremental blob IO only.
  57438. **
  57439. ** This function sets a flag only. The actual page location cache
  57440. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  57441. ** accessPayload() (the worker function for sqlite3BtreeData() and
  57442. ** sqlite3BtreePutData()).
  57443. */
  57444. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  57445. assert( cursorHoldsMutex(pCur) );
  57446. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  57447. invalidateOverflowCache(pCur);
  57448. pCur->isIncrblobHandle = 1;
  57449. }
  57450. #endif
  57451. /*
  57452. ** Set both the "read version" (single byte at byte offset 18) and
  57453. ** "write version" (single byte at byte offset 19) fields in the database
  57454. ** header to iVersion.
  57455. */
  57456. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  57457. BtShared *pBt = pBtree->pBt;
  57458. int rc; /* Return code */
  57459. assert( iVersion==1 || iVersion==2 );
  57460. /* If setting the version fields to 1, do not automatically open the
  57461. ** WAL connection, even if the version fields are currently set to 2.
  57462. */
  57463. pBt->btsFlags &= ~BTS_NO_WAL;
  57464. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  57465. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  57466. if( rc==SQLITE_OK ){
  57467. u8 *aData = pBt->pPage1->aData;
  57468. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  57469. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  57470. if( rc==SQLITE_OK ){
  57471. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  57472. if( rc==SQLITE_OK ){
  57473. aData[18] = (u8)iVersion;
  57474. aData[19] = (u8)iVersion;
  57475. }
  57476. }
  57477. }
  57478. }
  57479. pBt->btsFlags &= ~BTS_NO_WAL;
  57480. return rc;
  57481. }
  57482. /*
  57483. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  57484. ** values are 0 and BTREE_BULKLOAD.
  57485. */
  57486. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  57487. assert( mask==BTREE_BULKLOAD || mask==0 );
  57488. pCsr->hints = mask;
  57489. }
  57490. /************** End of btree.c ***********************************************/
  57491. /************** Begin file backup.c ******************************************/
  57492. /*
  57493. ** 2009 January 28
  57494. **
  57495. ** The author disclaims copyright to this source code. In place of
  57496. ** a legal notice, here is a blessing:
  57497. **
  57498. ** May you do good and not evil.
  57499. ** May you find forgiveness for yourself and forgive others.
  57500. ** May you share freely, never taking more than you give.
  57501. **
  57502. *************************************************************************
  57503. ** This file contains the implementation of the sqlite3_backup_XXX()
  57504. ** API functions and the related features.
  57505. */
  57506. /*
  57507. ** Structure allocated for each backup operation.
  57508. */
  57509. struct sqlite3_backup {
  57510. sqlite3* pDestDb; /* Destination database handle */
  57511. Btree *pDest; /* Destination b-tree file */
  57512. u32 iDestSchema; /* Original schema cookie in destination */
  57513. int bDestLocked; /* True once a write-transaction is open on pDest */
  57514. Pgno iNext; /* Page number of the next source page to copy */
  57515. sqlite3* pSrcDb; /* Source database handle */
  57516. Btree *pSrc; /* Source b-tree file */
  57517. int rc; /* Backup process error code */
  57518. /* These two variables are set by every call to backup_step(). They are
  57519. ** read by calls to backup_remaining() and backup_pagecount().
  57520. */
  57521. Pgno nRemaining; /* Number of pages left to copy */
  57522. Pgno nPagecount; /* Total number of pages to copy */
  57523. int isAttached; /* True once backup has been registered with pager */
  57524. sqlite3_backup *pNext; /* Next backup associated with source pager */
  57525. };
  57526. /*
  57527. ** THREAD SAFETY NOTES:
  57528. **
  57529. ** Once it has been created using backup_init(), a single sqlite3_backup
  57530. ** structure may be accessed via two groups of thread-safe entry points:
  57531. **
  57532. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  57533. ** backup_finish(). Both these functions obtain the source database
  57534. ** handle mutex and the mutex associated with the source BtShared
  57535. ** structure, in that order.
  57536. **
  57537. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  57538. ** invoked by the pager layer to report various state changes in
  57539. ** the page cache associated with the source database. The mutex
  57540. ** associated with the source database BtShared structure will always
  57541. ** be held when either of these functions are invoked.
  57542. **
  57543. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  57544. ** backup_pagecount() are not thread-safe functions. If they are called
  57545. ** while some other thread is calling backup_step() or backup_finish(),
  57546. ** the values returned may be invalid. There is no way for a call to
  57547. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  57548. ** or backup_pagecount().
  57549. **
  57550. ** Depending on the SQLite configuration, the database handles and/or
  57551. ** the Btree objects may have their own mutexes that require locking.
  57552. ** Non-sharable Btrees (in-memory databases for example), do not have
  57553. ** associated mutexes.
  57554. */
  57555. /*
  57556. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  57557. ** in connection handle pDb. If such a database cannot be found, return
  57558. ** a NULL pointer and write an error message to pErrorDb.
  57559. **
  57560. ** If the "temp" database is requested, it may need to be opened by this
  57561. ** function. If an error occurs while doing so, return 0 and write an
  57562. ** error message to pErrorDb.
  57563. */
  57564. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  57565. int i = sqlite3FindDbName(pDb, zDb);
  57566. if( i==1 ){
  57567. Parse *pParse;
  57568. int rc = 0;
  57569. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  57570. if( pParse==0 ){
  57571. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  57572. rc = SQLITE_NOMEM;
  57573. }else{
  57574. pParse->db = pDb;
  57575. if( sqlite3OpenTempDatabase(pParse) ){
  57576. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  57577. rc = SQLITE_ERROR;
  57578. }
  57579. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  57580. sqlite3StackFree(pErrorDb, pParse);
  57581. }
  57582. if( rc ){
  57583. return 0;
  57584. }
  57585. }
  57586. if( i<0 ){
  57587. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  57588. return 0;
  57589. }
  57590. return pDb->aDb[i].pBt;
  57591. }
  57592. /*
  57593. ** Attempt to set the page size of the destination to match the page size
  57594. ** of the source.
  57595. */
  57596. static int setDestPgsz(sqlite3_backup *p){
  57597. int rc;
  57598. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  57599. return rc;
  57600. }
  57601. /*
  57602. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  57603. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  57604. ** a pointer to the new sqlite3_backup object.
  57605. **
  57606. ** If an error occurs, NULL is returned and an error code and error message
  57607. ** stored in database handle pDestDb.
  57608. */
  57609. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  57610. sqlite3* pDestDb, /* Database to write to */
  57611. const char *zDestDb, /* Name of database within pDestDb */
  57612. sqlite3* pSrcDb, /* Database connection to read from */
  57613. const char *zSrcDb /* Name of database within pSrcDb */
  57614. ){
  57615. sqlite3_backup *p; /* Value to return */
  57616. /* Lock the source database handle. The destination database
  57617. ** handle is not locked in this routine, but it is locked in
  57618. ** sqlite3_backup_step(). The user is required to ensure that no
  57619. ** other thread accesses the destination handle for the duration
  57620. ** of the backup operation. Any attempt to use the destination
  57621. ** database connection while a backup is in progress may cause
  57622. ** a malfunction or a deadlock.
  57623. */
  57624. sqlite3_mutex_enter(pSrcDb->mutex);
  57625. sqlite3_mutex_enter(pDestDb->mutex);
  57626. if( pSrcDb==pDestDb ){
  57627. sqlite3Error(
  57628. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  57629. );
  57630. p = 0;
  57631. }else {
  57632. /* Allocate space for a new sqlite3_backup object...
  57633. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  57634. ** call to sqlite3_backup_init() and is destroyed by a call to
  57635. ** sqlite3_backup_finish(). */
  57636. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  57637. if( !p ){
  57638. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  57639. }
  57640. }
  57641. /* If the allocation succeeded, populate the new object. */
  57642. if( p ){
  57643. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  57644. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  57645. p->pDestDb = pDestDb;
  57646. p->pSrcDb = pSrcDb;
  57647. p->iNext = 1;
  57648. p->isAttached = 0;
  57649. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  57650. /* One (or both) of the named databases did not exist or an OOM
  57651. ** error was hit. The error has already been written into the
  57652. ** pDestDb handle. All that is left to do here is free the
  57653. ** sqlite3_backup structure.
  57654. */
  57655. sqlite3_free(p);
  57656. p = 0;
  57657. }
  57658. }
  57659. if( p ){
  57660. p->pSrc->nBackup++;
  57661. }
  57662. sqlite3_mutex_leave(pDestDb->mutex);
  57663. sqlite3_mutex_leave(pSrcDb->mutex);
  57664. return p;
  57665. }
  57666. /*
  57667. ** Argument rc is an SQLite error code. Return true if this error is
  57668. ** considered fatal if encountered during a backup operation. All errors
  57669. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  57670. */
  57671. static int isFatalError(int rc){
  57672. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  57673. }
  57674. /*
  57675. ** Parameter zSrcData points to a buffer containing the data for
  57676. ** page iSrcPg from the source database. Copy this data into the
  57677. ** destination database.
  57678. */
  57679. static int backupOnePage(
  57680. sqlite3_backup *p, /* Backup handle */
  57681. Pgno iSrcPg, /* Source database page to backup */
  57682. const u8 *zSrcData, /* Source database page data */
  57683. int bUpdate /* True for an update, false otherwise */
  57684. ){
  57685. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  57686. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  57687. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  57688. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  57689. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  57690. #ifdef SQLITE_HAS_CODEC
  57691. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  57692. ** guaranteed that the shared-mutex is held by this thread, handle
  57693. ** p->pSrc may not actually be the owner. */
  57694. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  57695. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  57696. #endif
  57697. int rc = SQLITE_OK;
  57698. i64 iOff;
  57699. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  57700. assert( p->bDestLocked );
  57701. assert( !isFatalError(p->rc) );
  57702. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  57703. assert( zSrcData );
  57704. /* Catch the case where the destination is an in-memory database and the
  57705. ** page sizes of the source and destination differ.
  57706. */
  57707. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  57708. rc = SQLITE_READONLY;
  57709. }
  57710. #ifdef SQLITE_HAS_CODEC
  57711. /* Backup is not possible if the page size of the destination is changing
  57712. ** and a codec is in use.
  57713. */
  57714. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  57715. rc = SQLITE_READONLY;
  57716. }
  57717. /* Backup is not possible if the number of bytes of reserve space differ
  57718. ** between source and destination. If there is a difference, try to
  57719. ** fix the destination to agree with the source. If that is not possible,
  57720. ** then the backup cannot proceed.
  57721. */
  57722. if( nSrcReserve!=nDestReserve ){
  57723. u32 newPgsz = nSrcPgsz;
  57724. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  57725. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  57726. }
  57727. #endif
  57728. /* This loop runs once for each destination page spanned by the source
  57729. ** page. For each iteration, variable iOff is set to the byte offset
  57730. ** of the destination page.
  57731. */
  57732. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  57733. DbPage *pDestPg = 0;
  57734. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  57735. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  57736. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  57737. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  57738. ){
  57739. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  57740. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  57741. u8 *zOut = &zDestData[iOff%nDestPgsz];
  57742. /* Copy the data from the source page into the destination page.
  57743. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  57744. ** and the pager code use this trick (clearing the first byte
  57745. ** of the page 'extra' space to invalidate the Btree layers
  57746. ** cached parse of the page). MemPage.isInit is marked
  57747. ** "MUST BE FIRST" for this purpose.
  57748. */
  57749. memcpy(zOut, zIn, nCopy);
  57750. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  57751. if( iOff==0 && bUpdate==0 ){
  57752. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  57753. }
  57754. }
  57755. sqlite3PagerUnref(pDestPg);
  57756. }
  57757. return rc;
  57758. }
  57759. /*
  57760. ** If pFile is currently larger than iSize bytes, then truncate it to
  57761. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  57762. ** this function is a no-op.
  57763. **
  57764. ** Return SQLITE_OK if everything is successful, or an SQLite error
  57765. ** code if an error occurs.
  57766. */
  57767. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  57768. i64 iCurrent;
  57769. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  57770. if( rc==SQLITE_OK && iCurrent>iSize ){
  57771. rc = sqlite3OsTruncate(pFile, iSize);
  57772. }
  57773. return rc;
  57774. }
  57775. /*
  57776. ** Register this backup object with the associated source pager for
  57777. ** callbacks when pages are changed or the cache invalidated.
  57778. */
  57779. static void attachBackupObject(sqlite3_backup *p){
  57780. sqlite3_backup **pp;
  57781. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  57782. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57783. p->pNext = *pp;
  57784. *pp = p;
  57785. p->isAttached = 1;
  57786. }
  57787. /*
  57788. ** Copy nPage pages from the source b-tree to the destination.
  57789. */
  57790. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  57791. int rc;
  57792. int destMode; /* Destination journal mode */
  57793. int pgszSrc = 0; /* Source page size */
  57794. int pgszDest = 0; /* Destination page size */
  57795. sqlite3_mutex_enter(p->pSrcDb->mutex);
  57796. sqlite3BtreeEnter(p->pSrc);
  57797. if( p->pDestDb ){
  57798. sqlite3_mutex_enter(p->pDestDb->mutex);
  57799. }
  57800. rc = p->rc;
  57801. if( !isFatalError(rc) ){
  57802. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  57803. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  57804. int ii; /* Iterator variable */
  57805. int nSrcPage = -1; /* Size of source db in pages */
  57806. int bCloseTrans = 0; /* True if src db requires unlocking */
  57807. /* If the source pager is currently in a write-transaction, return
  57808. ** SQLITE_BUSY immediately.
  57809. */
  57810. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  57811. rc = SQLITE_BUSY;
  57812. }else{
  57813. rc = SQLITE_OK;
  57814. }
  57815. /* Lock the destination database, if it is not locked already. */
  57816. if( SQLITE_OK==rc && p->bDestLocked==0
  57817. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  57818. ){
  57819. p->bDestLocked = 1;
  57820. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  57821. }
  57822. /* If there is no open read-transaction on the source database, open
  57823. ** one now. If a transaction is opened here, then it will be closed
  57824. ** before this function exits.
  57825. */
  57826. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  57827. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  57828. bCloseTrans = 1;
  57829. }
  57830. /* Do not allow backup if the destination database is in WAL mode
  57831. ** and the page sizes are different between source and destination */
  57832. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  57833. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  57834. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  57835. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  57836. rc = SQLITE_READONLY;
  57837. }
  57838. /* Now that there is a read-lock on the source database, query the
  57839. ** source pager for the number of pages in the database.
  57840. */
  57841. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  57842. assert( nSrcPage>=0 );
  57843. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  57844. const Pgno iSrcPg = p->iNext; /* Source page number */
  57845. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  57846. DbPage *pSrcPg; /* Source page object */
  57847. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  57848. PAGER_GET_READONLY);
  57849. if( rc==SQLITE_OK ){
  57850. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  57851. sqlite3PagerUnref(pSrcPg);
  57852. }
  57853. }
  57854. p->iNext++;
  57855. }
  57856. if( rc==SQLITE_OK ){
  57857. p->nPagecount = nSrcPage;
  57858. p->nRemaining = nSrcPage+1-p->iNext;
  57859. if( p->iNext>(Pgno)nSrcPage ){
  57860. rc = SQLITE_DONE;
  57861. }else if( !p->isAttached ){
  57862. attachBackupObject(p);
  57863. }
  57864. }
  57865. /* Update the schema version field in the destination database. This
  57866. ** is to make sure that the schema-version really does change in
  57867. ** the case where the source and destination databases have the
  57868. ** same schema version.
  57869. */
  57870. if( rc==SQLITE_DONE ){
  57871. if( nSrcPage==0 ){
  57872. rc = sqlite3BtreeNewDb(p->pDest);
  57873. nSrcPage = 1;
  57874. }
  57875. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  57876. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  57877. }
  57878. if( rc==SQLITE_OK ){
  57879. if( p->pDestDb ){
  57880. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  57881. }
  57882. if( destMode==PAGER_JOURNALMODE_WAL ){
  57883. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  57884. }
  57885. }
  57886. if( rc==SQLITE_OK ){
  57887. int nDestTruncate;
  57888. /* Set nDestTruncate to the final number of pages in the destination
  57889. ** database. The complication here is that the destination page
  57890. ** size may be different to the source page size.
  57891. **
  57892. ** If the source page size is smaller than the destination page size,
  57893. ** round up. In this case the call to sqlite3OsTruncate() below will
  57894. ** fix the size of the file. However it is important to call
  57895. ** sqlite3PagerTruncateImage() here so that any pages in the
  57896. ** destination file that lie beyond the nDestTruncate page mark are
  57897. ** journalled by PagerCommitPhaseOne() before they are destroyed
  57898. ** by the file truncation.
  57899. */
  57900. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  57901. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  57902. if( pgszSrc<pgszDest ){
  57903. int ratio = pgszDest/pgszSrc;
  57904. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  57905. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57906. nDestTruncate--;
  57907. }
  57908. }else{
  57909. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  57910. }
  57911. assert( nDestTruncate>0 );
  57912. if( pgszSrc<pgszDest ){
  57913. /* If the source page-size is smaller than the destination page-size,
  57914. ** two extra things may need to happen:
  57915. **
  57916. ** * The destination may need to be truncated, and
  57917. **
  57918. ** * Data stored on the pages immediately following the
  57919. ** pending-byte page in the source database may need to be
  57920. ** copied into the destination database.
  57921. */
  57922. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  57923. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  57924. Pgno iPg;
  57925. int nDstPage;
  57926. i64 iOff;
  57927. i64 iEnd;
  57928. assert( pFile );
  57929. assert( nDestTruncate==0
  57930. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  57931. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  57932. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  57933. ));
  57934. /* This block ensures that all data required to recreate the original
  57935. ** database has been stored in the journal for pDestPager and the
  57936. ** journal synced to disk. So at this point we may safely modify
  57937. ** the database file in any way, knowing that if a power failure
  57938. ** occurs, the original database will be reconstructed from the
  57939. ** journal file. */
  57940. sqlite3PagerPagecount(pDestPager, &nDstPage);
  57941. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  57942. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57943. DbPage *pPg;
  57944. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  57945. if( rc==SQLITE_OK ){
  57946. rc = sqlite3PagerWrite(pPg);
  57947. sqlite3PagerUnref(pPg);
  57948. }
  57949. }
  57950. }
  57951. if( rc==SQLITE_OK ){
  57952. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  57953. }
  57954. /* Write the extra pages and truncate the database file as required */
  57955. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  57956. for(
  57957. iOff=PENDING_BYTE+pgszSrc;
  57958. rc==SQLITE_OK && iOff<iEnd;
  57959. iOff+=pgszSrc
  57960. ){
  57961. PgHdr *pSrcPg = 0;
  57962. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  57963. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  57964. if( rc==SQLITE_OK ){
  57965. u8 *zData = sqlite3PagerGetData(pSrcPg);
  57966. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  57967. }
  57968. sqlite3PagerUnref(pSrcPg);
  57969. }
  57970. if( rc==SQLITE_OK ){
  57971. rc = backupTruncateFile(pFile, iSize);
  57972. }
  57973. /* Sync the database file to disk. */
  57974. if( rc==SQLITE_OK ){
  57975. rc = sqlite3PagerSync(pDestPager);
  57976. }
  57977. }else{
  57978. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  57979. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  57980. }
  57981. /* Finish committing the transaction to the destination database. */
  57982. if( SQLITE_OK==rc
  57983. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  57984. ){
  57985. rc = SQLITE_DONE;
  57986. }
  57987. }
  57988. }
  57989. /* If bCloseTrans is true, then this function opened a read transaction
  57990. ** on the source database. Close the read transaction here. There is
  57991. ** no need to check the return values of the btree methods here, as
  57992. ** "committing" a read-only transaction cannot fail.
  57993. */
  57994. if( bCloseTrans ){
  57995. TESTONLY( int rc2 );
  57996. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  57997. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  57998. assert( rc2==SQLITE_OK );
  57999. }
  58000. if( rc==SQLITE_IOERR_NOMEM ){
  58001. rc = SQLITE_NOMEM;
  58002. }
  58003. p->rc = rc;
  58004. }
  58005. if( p->pDestDb ){
  58006. sqlite3_mutex_leave(p->pDestDb->mutex);
  58007. }
  58008. sqlite3BtreeLeave(p->pSrc);
  58009. sqlite3_mutex_leave(p->pSrcDb->mutex);
  58010. return rc;
  58011. }
  58012. /*
  58013. ** Release all resources associated with an sqlite3_backup* handle.
  58014. */
  58015. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  58016. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  58017. sqlite3 *pSrcDb; /* Source database connection */
  58018. int rc; /* Value to return */
  58019. /* Enter the mutexes */
  58020. if( p==0 ) return SQLITE_OK;
  58021. pSrcDb = p->pSrcDb;
  58022. sqlite3_mutex_enter(pSrcDb->mutex);
  58023. sqlite3BtreeEnter(p->pSrc);
  58024. if( p->pDestDb ){
  58025. sqlite3_mutex_enter(p->pDestDb->mutex);
  58026. }
  58027. /* Detach this backup from the source pager. */
  58028. if( p->pDestDb ){
  58029. p->pSrc->nBackup--;
  58030. }
  58031. if( p->isAttached ){
  58032. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  58033. while( *pp!=p ){
  58034. pp = &(*pp)->pNext;
  58035. }
  58036. *pp = p->pNext;
  58037. }
  58038. /* If a transaction is still open on the Btree, roll it back. */
  58039. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  58040. /* Set the error code of the destination database handle. */
  58041. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  58042. sqlite3Error(p->pDestDb, rc, 0);
  58043. /* Exit the mutexes and free the backup context structure. */
  58044. if( p->pDestDb ){
  58045. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  58046. }
  58047. sqlite3BtreeLeave(p->pSrc);
  58048. if( p->pDestDb ){
  58049. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  58050. ** call to sqlite3_backup_init() and is destroyed by a call to
  58051. ** sqlite3_backup_finish(). */
  58052. sqlite3_free(p);
  58053. }
  58054. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  58055. return rc;
  58056. }
  58057. /*
  58058. ** Return the number of pages still to be backed up as of the most recent
  58059. ** call to sqlite3_backup_step().
  58060. */
  58061. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  58062. return p->nRemaining;
  58063. }
  58064. /*
  58065. ** Return the total number of pages in the source database as of the most
  58066. ** recent call to sqlite3_backup_step().
  58067. */
  58068. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  58069. return p->nPagecount;
  58070. }
  58071. /*
  58072. ** This function is called after the contents of page iPage of the
  58073. ** source database have been modified. If page iPage has already been
  58074. ** copied into the destination database, then the data written to the
  58075. ** destination is now invalidated. The destination copy of iPage needs
  58076. ** to be updated with the new data before the backup operation is
  58077. ** complete.
  58078. **
  58079. ** It is assumed that the mutex associated with the BtShared object
  58080. ** corresponding to the source database is held when this function is
  58081. ** called.
  58082. */
  58083. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  58084. sqlite3_backup *p; /* Iterator variable */
  58085. for(p=pBackup; p; p=p->pNext){
  58086. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58087. if( !isFatalError(p->rc) && iPage<p->iNext ){
  58088. /* The backup process p has already copied page iPage. But now it
  58089. ** has been modified by a transaction on the source pager. Copy
  58090. ** the new data into the backup.
  58091. */
  58092. int rc;
  58093. assert( p->pDestDb );
  58094. sqlite3_mutex_enter(p->pDestDb->mutex);
  58095. rc = backupOnePage(p, iPage, aData, 1);
  58096. sqlite3_mutex_leave(p->pDestDb->mutex);
  58097. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  58098. if( rc!=SQLITE_OK ){
  58099. p->rc = rc;
  58100. }
  58101. }
  58102. }
  58103. }
  58104. /*
  58105. ** Restart the backup process. This is called when the pager layer
  58106. ** detects that the database has been modified by an external database
  58107. ** connection. In this case there is no way of knowing which of the
  58108. ** pages that have been copied into the destination database are still
  58109. ** valid and which are not, so the entire process needs to be restarted.
  58110. **
  58111. ** It is assumed that the mutex associated with the BtShared object
  58112. ** corresponding to the source database is held when this function is
  58113. ** called.
  58114. */
  58115. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  58116. sqlite3_backup *p; /* Iterator variable */
  58117. for(p=pBackup; p; p=p->pNext){
  58118. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58119. p->iNext = 1;
  58120. }
  58121. }
  58122. #ifndef SQLITE_OMIT_VACUUM
  58123. /*
  58124. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  58125. ** must be active for both files.
  58126. **
  58127. ** The size of file pTo may be reduced by this operation. If anything
  58128. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  58129. ** transaction is committed before returning.
  58130. */
  58131. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  58132. int rc;
  58133. sqlite3_file *pFd; /* File descriptor for database pTo */
  58134. sqlite3_backup b;
  58135. sqlite3BtreeEnter(pTo);
  58136. sqlite3BtreeEnter(pFrom);
  58137. assert( sqlite3BtreeIsInTrans(pTo) );
  58138. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  58139. if( pFd->pMethods ){
  58140. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  58141. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  58142. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  58143. if( rc ) goto copy_finished;
  58144. }
  58145. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  58146. ** to 0. This is used by the implementations of sqlite3_backup_step()
  58147. ** and sqlite3_backup_finish() to detect that they are being called
  58148. ** from this function, not directly by the user.
  58149. */
  58150. memset(&b, 0, sizeof(b));
  58151. b.pSrcDb = pFrom->db;
  58152. b.pSrc = pFrom;
  58153. b.pDest = pTo;
  58154. b.iNext = 1;
  58155. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  58156. ** file. By passing this as the number of pages to copy to
  58157. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  58158. ** within a single call (unless an error occurs). The assert() statement
  58159. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  58160. ** or an error code.
  58161. */
  58162. sqlite3_backup_step(&b, 0x7FFFFFFF);
  58163. assert( b.rc!=SQLITE_OK );
  58164. rc = sqlite3_backup_finish(&b);
  58165. if( rc==SQLITE_OK ){
  58166. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  58167. }else{
  58168. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  58169. }
  58170. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  58171. copy_finished:
  58172. sqlite3BtreeLeave(pFrom);
  58173. sqlite3BtreeLeave(pTo);
  58174. return rc;
  58175. }
  58176. #endif /* SQLITE_OMIT_VACUUM */
  58177. /************** End of backup.c **********************************************/
  58178. /************** Begin file vdbemem.c *****************************************/
  58179. /*
  58180. ** 2004 May 26
  58181. **
  58182. ** The author disclaims copyright to this source code. In place of
  58183. ** a legal notice, here is a blessing:
  58184. **
  58185. ** May you do good and not evil.
  58186. ** May you find forgiveness for yourself and forgive others.
  58187. ** May you share freely, never taking more than you give.
  58188. **
  58189. *************************************************************************
  58190. **
  58191. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  58192. ** stores a single value in the VDBE. Mem is an opaque structure visible
  58193. ** only within the VDBE. Interface routines refer to a Mem using the
  58194. ** name sqlite_value
  58195. */
  58196. /*
  58197. ** If pMem is an object with a valid string representation, this routine
  58198. ** ensures the internal encoding for the string representation is
  58199. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  58200. **
  58201. ** If pMem is not a string object, or the encoding of the string
  58202. ** representation is already stored using the requested encoding, then this
  58203. ** routine is a no-op.
  58204. **
  58205. ** SQLITE_OK is returned if the conversion is successful (or not required).
  58206. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  58207. ** between formats.
  58208. */
  58209. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  58210. #ifndef SQLITE_OMIT_UTF16
  58211. int rc;
  58212. #endif
  58213. assert( (pMem->flags&MEM_RowSet)==0 );
  58214. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  58215. || desiredEnc==SQLITE_UTF16BE );
  58216. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  58217. return SQLITE_OK;
  58218. }
  58219. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58220. #ifdef SQLITE_OMIT_UTF16
  58221. return SQLITE_ERROR;
  58222. #else
  58223. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  58224. ** then the encoding of the value may not have changed.
  58225. */
  58226. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  58227. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  58228. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  58229. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  58230. return rc;
  58231. #endif
  58232. }
  58233. /*
  58234. ** Make sure pMem->z points to a writable allocation of at least
  58235. ** n bytes.
  58236. **
  58237. ** If the third argument passed to this function is true, then memory
  58238. ** cell pMem must contain a string or blob. In this case the content is
  58239. ** preserved. Otherwise, if the third parameter to this function is false,
  58240. ** any current string or blob value may be discarded.
  58241. **
  58242. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  58243. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  58244. ** not set, Mem.n is zeroed.
  58245. */
  58246. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  58247. assert( 1 >=
  58248. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  58249. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  58250. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  58251. ((pMem->flags&MEM_Static) ? 1 : 0)
  58252. );
  58253. assert( (pMem->flags&MEM_RowSet)==0 );
  58254. /* If the preserve flag is set to true, then the memory cell must already
  58255. ** contain a valid string or blob value. */
  58256. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  58257. if( n<32 ) n = 32;
  58258. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  58259. if( preserve && pMem->z==pMem->zMalloc ){
  58260. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  58261. preserve = 0;
  58262. }else{
  58263. sqlite3DbFree(pMem->db, pMem->zMalloc);
  58264. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  58265. }
  58266. }
  58267. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  58268. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  58269. }
  58270. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  58271. assert( pMem->xDel!=SQLITE_DYNAMIC );
  58272. pMem->xDel((void *)(pMem->z));
  58273. }
  58274. pMem->z = pMem->zMalloc;
  58275. if( pMem->z==0 ){
  58276. pMem->flags = MEM_Null;
  58277. }else{
  58278. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  58279. }
  58280. pMem->xDel = 0;
  58281. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  58282. }
  58283. /*
  58284. ** Make the given Mem object MEM_Dyn. In other words, make it so
  58285. ** that any TEXT or BLOB content is stored in memory obtained from
  58286. ** malloc(). In this way, we know that the memory is safe to be
  58287. ** overwritten or altered.
  58288. **
  58289. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  58290. */
  58291. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  58292. int f;
  58293. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58294. assert( (pMem->flags&MEM_RowSet)==0 );
  58295. ExpandBlob(pMem);
  58296. f = pMem->flags;
  58297. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  58298. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  58299. return SQLITE_NOMEM;
  58300. }
  58301. pMem->z[pMem->n] = 0;
  58302. pMem->z[pMem->n+1] = 0;
  58303. pMem->flags |= MEM_Term;
  58304. #ifdef SQLITE_DEBUG
  58305. pMem->pScopyFrom = 0;
  58306. #endif
  58307. }
  58308. return SQLITE_OK;
  58309. }
  58310. /*
  58311. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  58312. ** blob stored in dynamically allocated space.
  58313. */
  58314. #ifndef SQLITE_OMIT_INCRBLOB
  58315. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  58316. if( pMem->flags & MEM_Zero ){
  58317. int nByte;
  58318. assert( pMem->flags&MEM_Blob );
  58319. assert( (pMem->flags&MEM_RowSet)==0 );
  58320. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58321. /* Set nByte to the number of bytes required to store the expanded blob. */
  58322. nByte = pMem->n + pMem->u.nZero;
  58323. if( nByte<=0 ){
  58324. nByte = 1;
  58325. }
  58326. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  58327. return SQLITE_NOMEM;
  58328. }
  58329. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  58330. pMem->n += pMem->u.nZero;
  58331. pMem->flags &= ~(MEM_Zero|MEM_Term);
  58332. }
  58333. return SQLITE_OK;
  58334. }
  58335. #endif
  58336. /*
  58337. ** Make sure the given Mem is \u0000 terminated.
  58338. */
  58339. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  58340. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58341. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  58342. return SQLITE_OK; /* Nothing to do */
  58343. }
  58344. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  58345. return SQLITE_NOMEM;
  58346. }
  58347. pMem->z[pMem->n] = 0;
  58348. pMem->z[pMem->n+1] = 0;
  58349. pMem->flags |= MEM_Term;
  58350. return SQLITE_OK;
  58351. }
  58352. /*
  58353. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  58354. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  58355. ** is a no-op.
  58356. **
  58357. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  58358. **
  58359. ** A MEM_Null value will never be passed to this function. This function is
  58360. ** used for converting values to text for returning to the user (i.e. via
  58361. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  58362. ** keys are strings. In the former case a NULL pointer is returned the
  58363. ** user and the later is an internal programming error.
  58364. */
  58365. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  58366. int rc = SQLITE_OK;
  58367. int fg = pMem->flags;
  58368. const int nByte = 32;
  58369. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58370. assert( !(fg&MEM_Zero) );
  58371. assert( !(fg&(MEM_Str|MEM_Blob)) );
  58372. assert( fg&(MEM_Int|MEM_Real) );
  58373. assert( (pMem->flags&MEM_RowSet)==0 );
  58374. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58375. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  58376. return SQLITE_NOMEM;
  58377. }
  58378. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  58379. ** string representation of the value. Then, if the required encoding
  58380. ** is UTF-16le or UTF-16be do a translation.
  58381. **
  58382. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  58383. */
  58384. if( fg & MEM_Int ){
  58385. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  58386. }else{
  58387. assert( fg & MEM_Real );
  58388. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  58389. }
  58390. pMem->n = sqlite3Strlen30(pMem->z);
  58391. pMem->enc = SQLITE_UTF8;
  58392. pMem->flags |= MEM_Str|MEM_Term;
  58393. sqlite3VdbeChangeEncoding(pMem, enc);
  58394. return rc;
  58395. }
  58396. /*
  58397. ** Memory cell pMem contains the context of an aggregate function.
  58398. ** This routine calls the finalize method for that function. The
  58399. ** result of the aggregate is stored back into pMem.
  58400. **
  58401. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  58402. ** otherwise.
  58403. */
  58404. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  58405. int rc = SQLITE_OK;
  58406. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  58407. sqlite3_context ctx;
  58408. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  58409. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58410. memset(&ctx, 0, sizeof(ctx));
  58411. ctx.s.flags = MEM_Null;
  58412. ctx.s.db = pMem->db;
  58413. ctx.pMem = pMem;
  58414. ctx.pFunc = pFunc;
  58415. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  58416. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  58417. sqlite3DbFree(pMem->db, pMem->zMalloc);
  58418. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  58419. rc = ctx.isError;
  58420. }
  58421. return rc;
  58422. }
  58423. /*
  58424. ** If the memory cell contains a string value that must be freed by
  58425. ** invoking an external callback, free it now. Calling this function
  58426. ** does not free any Mem.zMalloc buffer.
  58427. */
  58428. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  58429. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  58430. if( p->flags&MEM_Agg ){
  58431. sqlite3VdbeMemFinalize(p, p->u.pDef);
  58432. assert( (p->flags & MEM_Agg)==0 );
  58433. sqlite3VdbeMemRelease(p);
  58434. }else if( p->flags&MEM_Dyn && p->xDel ){
  58435. assert( (p->flags&MEM_RowSet)==0 );
  58436. assert( p->xDel!=SQLITE_DYNAMIC );
  58437. p->xDel((void *)p->z);
  58438. p->xDel = 0;
  58439. }else if( p->flags&MEM_RowSet ){
  58440. sqlite3RowSetClear(p->u.pRowSet);
  58441. }else if( p->flags&MEM_Frame ){
  58442. sqlite3VdbeMemSetNull(p);
  58443. }
  58444. }
  58445. /*
  58446. ** Release any memory held by the Mem. This may leave the Mem in an
  58447. ** inconsistent state, for example with (Mem.z==0) and
  58448. ** (Mem.type==SQLITE_TEXT).
  58449. */
  58450. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  58451. VdbeMemRelease(p);
  58452. sqlite3DbFree(p->db, p->zMalloc);
  58453. p->z = 0;
  58454. p->zMalloc = 0;
  58455. p->xDel = 0;
  58456. }
  58457. /*
  58458. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  58459. ** If the double is too large, return 0x8000000000000000.
  58460. **
  58461. ** Most systems appear to do this simply by assigning
  58462. ** variables and without the extra range tests. But
  58463. ** there are reports that windows throws an expection
  58464. ** if the floating point value is out of range. (See ticket #2880.)
  58465. ** Because we do not completely understand the problem, we will
  58466. ** take the conservative approach and always do range tests
  58467. ** before attempting the conversion.
  58468. */
  58469. static i64 doubleToInt64(double r){
  58470. #ifdef SQLITE_OMIT_FLOATING_POINT
  58471. /* When floating-point is omitted, double and int64 are the same thing */
  58472. return r;
  58473. #else
  58474. /*
  58475. ** Many compilers we encounter do not define constants for the
  58476. ** minimum and maximum 64-bit integers, or they define them
  58477. ** inconsistently. And many do not understand the "LL" notation.
  58478. ** So we define our own static constants here using nothing
  58479. ** larger than a 32-bit integer constant.
  58480. */
  58481. static const i64 maxInt = LARGEST_INT64;
  58482. static const i64 minInt = SMALLEST_INT64;
  58483. if( r<(double)minInt ){
  58484. return minInt;
  58485. }else if( r>(double)maxInt ){
  58486. /* minInt is correct here - not maxInt. It turns out that assigning
  58487. ** a very large positive number to an integer results in a very large
  58488. ** negative integer. This makes no sense, but it is what x86 hardware
  58489. ** does so for compatibility we will do the same in software. */
  58490. return minInt;
  58491. }else{
  58492. return (i64)r;
  58493. }
  58494. #endif
  58495. }
  58496. /*
  58497. ** Return some kind of integer value which is the best we can do
  58498. ** at representing the value that *pMem describes as an integer.
  58499. ** If pMem is an integer, then the value is exact. If pMem is
  58500. ** a floating-point then the value returned is the integer part.
  58501. ** If pMem is a string or blob, then we make an attempt to convert
  58502. ** it into a integer and return that. If pMem represents an
  58503. ** an SQL-NULL value, return 0.
  58504. **
  58505. ** If pMem represents a string value, its encoding might be changed.
  58506. */
  58507. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  58508. int flags;
  58509. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58510. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58511. flags = pMem->flags;
  58512. if( flags & MEM_Int ){
  58513. return pMem->u.i;
  58514. }else if( flags & MEM_Real ){
  58515. return doubleToInt64(pMem->r);
  58516. }else if( flags & (MEM_Str|MEM_Blob) ){
  58517. i64 value = 0;
  58518. assert( pMem->z || pMem->n==0 );
  58519. testcase( pMem->z==0 );
  58520. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  58521. return value;
  58522. }else{
  58523. return 0;
  58524. }
  58525. }
  58526. /*
  58527. ** Return the best representation of pMem that we can get into a
  58528. ** double. If pMem is already a double or an integer, return its
  58529. ** value. If it is a string or blob, try to convert it to a double.
  58530. ** If it is a NULL, return 0.0.
  58531. */
  58532. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  58533. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58534. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58535. if( pMem->flags & MEM_Real ){
  58536. return pMem->r;
  58537. }else if( pMem->flags & MEM_Int ){
  58538. return (double)pMem->u.i;
  58539. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  58540. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58541. double val = (double)0;
  58542. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  58543. return val;
  58544. }else{
  58545. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58546. return (double)0;
  58547. }
  58548. }
  58549. /*
  58550. ** The MEM structure is already a MEM_Real. Try to also make it a
  58551. ** MEM_Int if we can.
  58552. */
  58553. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  58554. assert( pMem->flags & MEM_Real );
  58555. assert( (pMem->flags & MEM_RowSet)==0 );
  58556. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58557. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58558. pMem->u.i = doubleToInt64(pMem->r);
  58559. /* Only mark the value as an integer if
  58560. **
  58561. ** (1) the round-trip conversion real->int->real is a no-op, and
  58562. ** (2) The integer is neither the largest nor the smallest
  58563. ** possible integer (ticket #3922)
  58564. **
  58565. ** The second and third terms in the following conditional enforces
  58566. ** the second condition under the assumption that addition overflow causes
  58567. ** values to wrap around. On x86 hardware, the third term is always
  58568. ** true and could be omitted. But we leave it in because other
  58569. ** architectures might behave differently.
  58570. */
  58571. if( pMem->r==(double)pMem->u.i
  58572. && pMem->u.i>SMALLEST_INT64
  58573. #if defined(__i486__) || defined(__x86_64__)
  58574. && ALWAYS(pMem->u.i<LARGEST_INT64)
  58575. #else
  58576. && pMem->u.i<LARGEST_INT64
  58577. #endif
  58578. ){
  58579. pMem->flags |= MEM_Int;
  58580. }
  58581. }
  58582. /*
  58583. ** Convert pMem to type integer. Invalidate any prior representations.
  58584. */
  58585. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  58586. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58587. assert( (pMem->flags & MEM_RowSet)==0 );
  58588. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58589. pMem->u.i = sqlite3VdbeIntValue(pMem);
  58590. MemSetTypeFlag(pMem, MEM_Int);
  58591. return SQLITE_OK;
  58592. }
  58593. /*
  58594. ** Convert pMem so that it is of type MEM_Real.
  58595. ** Invalidate any prior representations.
  58596. */
  58597. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  58598. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58599. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58600. pMem->r = sqlite3VdbeRealValue(pMem);
  58601. MemSetTypeFlag(pMem, MEM_Real);
  58602. return SQLITE_OK;
  58603. }
  58604. /*
  58605. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  58606. ** Invalidate any prior representations.
  58607. **
  58608. ** Every effort is made to force the conversion, even if the input
  58609. ** is a string that does not look completely like a number. Convert
  58610. ** as much of the string as we can and ignore the rest.
  58611. */
  58612. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  58613. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  58614. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  58615. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58616. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  58617. MemSetTypeFlag(pMem, MEM_Int);
  58618. }else{
  58619. pMem->r = sqlite3VdbeRealValue(pMem);
  58620. MemSetTypeFlag(pMem, MEM_Real);
  58621. sqlite3VdbeIntegerAffinity(pMem);
  58622. }
  58623. }
  58624. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  58625. pMem->flags &= ~(MEM_Str|MEM_Blob);
  58626. return SQLITE_OK;
  58627. }
  58628. /*
  58629. ** Delete any previous value and set the value stored in *pMem to NULL.
  58630. */
  58631. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  58632. if( pMem->flags & MEM_Frame ){
  58633. VdbeFrame *pFrame = pMem->u.pFrame;
  58634. pFrame->pParent = pFrame->v->pDelFrame;
  58635. pFrame->v->pDelFrame = pFrame;
  58636. }
  58637. if( pMem->flags & MEM_RowSet ){
  58638. sqlite3RowSetClear(pMem->u.pRowSet);
  58639. }
  58640. MemSetTypeFlag(pMem, MEM_Null);
  58641. pMem->type = SQLITE_NULL;
  58642. }
  58643. /*
  58644. ** Delete any previous value and set the value to be a BLOB of length
  58645. ** n containing all zeros.
  58646. */
  58647. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  58648. sqlite3VdbeMemRelease(pMem);
  58649. pMem->flags = MEM_Blob|MEM_Zero;
  58650. pMem->type = SQLITE_BLOB;
  58651. pMem->n = 0;
  58652. if( n<0 ) n = 0;
  58653. pMem->u.nZero = n;
  58654. pMem->enc = SQLITE_UTF8;
  58655. #ifdef SQLITE_OMIT_INCRBLOB
  58656. sqlite3VdbeMemGrow(pMem, n, 0);
  58657. if( pMem->z ){
  58658. pMem->n = n;
  58659. memset(pMem->z, 0, n);
  58660. }
  58661. #endif
  58662. }
  58663. /*
  58664. ** Delete any previous value and set the value stored in *pMem to val,
  58665. ** manifest type INTEGER.
  58666. */
  58667. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  58668. sqlite3VdbeMemRelease(pMem);
  58669. pMem->u.i = val;
  58670. pMem->flags = MEM_Int;
  58671. pMem->type = SQLITE_INTEGER;
  58672. }
  58673. #ifndef SQLITE_OMIT_FLOATING_POINT
  58674. /*
  58675. ** Delete any previous value and set the value stored in *pMem to val,
  58676. ** manifest type REAL.
  58677. */
  58678. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  58679. if( sqlite3IsNaN(val) ){
  58680. sqlite3VdbeMemSetNull(pMem);
  58681. }else{
  58682. sqlite3VdbeMemRelease(pMem);
  58683. pMem->r = val;
  58684. pMem->flags = MEM_Real;
  58685. pMem->type = SQLITE_FLOAT;
  58686. }
  58687. }
  58688. #endif
  58689. /*
  58690. ** Delete any previous value and set the value of pMem to be an
  58691. ** empty boolean index.
  58692. */
  58693. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  58694. sqlite3 *db = pMem->db;
  58695. assert( db!=0 );
  58696. assert( (pMem->flags & MEM_RowSet)==0 );
  58697. sqlite3VdbeMemRelease(pMem);
  58698. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  58699. if( db->mallocFailed ){
  58700. pMem->flags = MEM_Null;
  58701. }else{
  58702. assert( pMem->zMalloc );
  58703. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  58704. sqlite3DbMallocSize(db, pMem->zMalloc));
  58705. assert( pMem->u.pRowSet!=0 );
  58706. pMem->flags = MEM_RowSet;
  58707. }
  58708. }
  58709. /*
  58710. ** Return true if the Mem object contains a TEXT or BLOB that is
  58711. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  58712. */
  58713. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  58714. assert( p->db!=0 );
  58715. if( p->flags & (MEM_Str|MEM_Blob) ){
  58716. int n = p->n;
  58717. if( p->flags & MEM_Zero ){
  58718. n += p->u.nZero;
  58719. }
  58720. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  58721. }
  58722. return 0;
  58723. }
  58724. #ifdef SQLITE_DEBUG
  58725. /*
  58726. ** This routine prepares a memory cell for modication by breaking
  58727. ** its link to a shallow copy and by marking any current shallow
  58728. ** copies of this cell as invalid.
  58729. **
  58730. ** This is used for testing and debugging only - to make sure shallow
  58731. ** copies are not misused.
  58732. */
  58733. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  58734. int i;
  58735. Mem *pX;
  58736. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  58737. if( pX->pScopyFrom==pMem ){
  58738. pX->flags |= MEM_Invalid;
  58739. pX->pScopyFrom = 0;
  58740. }
  58741. }
  58742. pMem->pScopyFrom = 0;
  58743. }
  58744. #endif /* SQLITE_DEBUG */
  58745. /*
  58746. ** Size of struct Mem not including the Mem.zMalloc member.
  58747. */
  58748. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  58749. /*
  58750. ** Make an shallow copy of pFrom into pTo. Prior contents of
  58751. ** pTo are freed. The pFrom->z field is not duplicated. If
  58752. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  58753. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  58754. */
  58755. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  58756. assert( (pFrom->flags & MEM_RowSet)==0 );
  58757. VdbeMemRelease(pTo);
  58758. memcpy(pTo, pFrom, MEMCELLSIZE);
  58759. pTo->xDel = 0;
  58760. if( (pFrom->flags&MEM_Static)==0 ){
  58761. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  58762. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  58763. pTo->flags |= srcType;
  58764. }
  58765. }
  58766. /*
  58767. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  58768. ** freed before the copy is made.
  58769. */
  58770. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  58771. int rc = SQLITE_OK;
  58772. assert( (pFrom->flags & MEM_RowSet)==0 );
  58773. VdbeMemRelease(pTo);
  58774. memcpy(pTo, pFrom, MEMCELLSIZE);
  58775. pTo->flags &= ~MEM_Dyn;
  58776. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  58777. if( 0==(pFrom->flags&MEM_Static) ){
  58778. pTo->flags |= MEM_Ephem;
  58779. rc = sqlite3VdbeMemMakeWriteable(pTo);
  58780. }
  58781. }
  58782. return rc;
  58783. }
  58784. /*
  58785. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  58786. ** freed. If pFrom contains ephemeral data, a copy is made.
  58787. **
  58788. ** pFrom contains an SQL NULL when this routine returns.
  58789. */
  58790. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  58791. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  58792. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  58793. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  58794. sqlite3VdbeMemRelease(pTo);
  58795. memcpy(pTo, pFrom, sizeof(Mem));
  58796. pFrom->flags = MEM_Null;
  58797. pFrom->xDel = 0;
  58798. pFrom->zMalloc = 0;
  58799. }
  58800. /*
  58801. ** Change the value of a Mem to be a string or a BLOB.
  58802. **
  58803. ** The memory management strategy depends on the value of the xDel
  58804. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  58805. ** string is copied into a (possibly existing) buffer managed by the
  58806. ** Mem structure. Otherwise, any existing buffer is freed and the
  58807. ** pointer copied.
  58808. **
  58809. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  58810. ** size limit) then no memory allocation occurs. If the string can be
  58811. ** stored without allocating memory, then it is. If a memory allocation
  58812. ** is required to store the string, then value of pMem is unchanged. In
  58813. ** either case, SQLITE_TOOBIG is returned.
  58814. */
  58815. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  58816. Mem *pMem, /* Memory cell to set to string value */
  58817. const char *z, /* String pointer */
  58818. int n, /* Bytes in string, or negative */
  58819. u8 enc, /* Encoding of z. 0 for BLOBs */
  58820. void (*xDel)(void*) /* Destructor function */
  58821. ){
  58822. int nByte = n; /* New value for pMem->n */
  58823. int iLimit; /* Maximum allowed string or blob size */
  58824. u16 flags = 0; /* New value for pMem->flags */
  58825. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58826. assert( (pMem->flags & MEM_RowSet)==0 );
  58827. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  58828. if( !z ){
  58829. sqlite3VdbeMemSetNull(pMem);
  58830. return SQLITE_OK;
  58831. }
  58832. if( pMem->db ){
  58833. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  58834. }else{
  58835. iLimit = SQLITE_MAX_LENGTH;
  58836. }
  58837. flags = (enc==0?MEM_Blob:MEM_Str);
  58838. if( nByte<0 ){
  58839. assert( enc!=0 );
  58840. if( enc==SQLITE_UTF8 ){
  58841. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  58842. }else{
  58843. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  58844. }
  58845. flags |= MEM_Term;
  58846. }
  58847. /* The following block sets the new values of Mem.z and Mem.xDel. It
  58848. ** also sets a flag in local variable "flags" to indicate the memory
  58849. ** management (one of MEM_Dyn or MEM_Static).
  58850. */
  58851. if( xDel==SQLITE_TRANSIENT ){
  58852. int nAlloc = nByte;
  58853. if( flags&MEM_Term ){
  58854. nAlloc += (enc==SQLITE_UTF8?1:2);
  58855. }
  58856. if( nByte>iLimit ){
  58857. return SQLITE_TOOBIG;
  58858. }
  58859. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  58860. return SQLITE_NOMEM;
  58861. }
  58862. memcpy(pMem->z, z, nAlloc);
  58863. }else if( xDel==SQLITE_DYNAMIC ){
  58864. sqlite3VdbeMemRelease(pMem);
  58865. pMem->zMalloc = pMem->z = (char *)z;
  58866. pMem->xDel = 0;
  58867. }else{
  58868. sqlite3VdbeMemRelease(pMem);
  58869. pMem->z = (char *)z;
  58870. pMem->xDel = xDel;
  58871. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  58872. }
  58873. pMem->n = nByte;
  58874. pMem->flags = flags;
  58875. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  58876. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  58877. #ifndef SQLITE_OMIT_UTF16
  58878. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  58879. return SQLITE_NOMEM;
  58880. }
  58881. #endif
  58882. if( nByte>iLimit ){
  58883. return SQLITE_TOOBIG;
  58884. }
  58885. return SQLITE_OK;
  58886. }
  58887. /*
  58888. ** Compare the values contained by the two memory cells, returning
  58889. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  58890. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  58891. ** and reals) sorted numerically, followed by text ordered by the collating
  58892. ** sequence pColl and finally blob's ordered by memcmp().
  58893. **
  58894. ** Two NULL values are considered equal by this function.
  58895. */
  58896. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  58897. int rc;
  58898. int f1, f2;
  58899. int combined_flags;
  58900. f1 = pMem1->flags;
  58901. f2 = pMem2->flags;
  58902. combined_flags = f1|f2;
  58903. assert( (combined_flags & MEM_RowSet)==0 );
  58904. /* If one value is NULL, it is less than the other. If both values
  58905. ** are NULL, return 0.
  58906. */
  58907. if( combined_flags&MEM_Null ){
  58908. return (f2&MEM_Null) - (f1&MEM_Null);
  58909. }
  58910. /* If one value is a number and the other is not, the number is less.
  58911. ** If both are numbers, compare as reals if one is a real, or as integers
  58912. ** if both values are integers.
  58913. */
  58914. if( combined_flags&(MEM_Int|MEM_Real) ){
  58915. double r1, r2;
  58916. if( (f1 & f2 & MEM_Int)!=0 ){
  58917. if( pMem1->u.i < pMem2->u.i ) return -1;
  58918. if( pMem1->u.i > pMem2->u.i ) return 1;
  58919. return 0;
  58920. }
  58921. if( (f1&MEM_Real)!=0 ){
  58922. r1 = pMem1->r;
  58923. }else if( (f1&MEM_Int)!=0 ){
  58924. r1 = (double)pMem1->u.i;
  58925. }else{
  58926. return 1;
  58927. }
  58928. if( (f2&MEM_Real)!=0 ){
  58929. r2 = pMem2->r;
  58930. }else if( (f2&MEM_Int)!=0 ){
  58931. r2 = (double)pMem2->u.i;
  58932. }else{
  58933. return -1;
  58934. }
  58935. if( r1<r2 ) return -1;
  58936. if( r1>r2 ) return 1;
  58937. return 0;
  58938. }
  58939. /* If one value is a string and the other is a blob, the string is less.
  58940. ** If both are strings, compare using the collating functions.
  58941. */
  58942. if( combined_flags&MEM_Str ){
  58943. if( (f1 & MEM_Str)==0 ){
  58944. return 1;
  58945. }
  58946. if( (f2 & MEM_Str)==0 ){
  58947. return -1;
  58948. }
  58949. assert( pMem1->enc==pMem2->enc );
  58950. assert( pMem1->enc==SQLITE_UTF8 ||
  58951. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  58952. /* The collation sequence must be defined at this point, even if
  58953. ** the user deletes the collation sequence after the vdbe program is
  58954. ** compiled (this was not always the case).
  58955. */
  58956. assert( !pColl || pColl->xCmp );
  58957. if( pColl ){
  58958. if( pMem1->enc==pColl->enc ){
  58959. /* The strings are already in the correct encoding. Call the
  58960. ** comparison function directly */
  58961. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  58962. }else{
  58963. const void *v1, *v2;
  58964. int n1, n2;
  58965. Mem c1;
  58966. Mem c2;
  58967. memset(&c1, 0, sizeof(c1));
  58968. memset(&c2, 0, sizeof(c2));
  58969. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  58970. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  58971. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  58972. n1 = v1==0 ? 0 : c1.n;
  58973. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  58974. n2 = v2==0 ? 0 : c2.n;
  58975. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  58976. sqlite3VdbeMemRelease(&c1);
  58977. sqlite3VdbeMemRelease(&c2);
  58978. return rc;
  58979. }
  58980. }
  58981. /* If a NULL pointer was passed as the collate function, fall through
  58982. ** to the blob case and use memcmp(). */
  58983. }
  58984. /* Both values must be blobs. Compare using memcmp(). */
  58985. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  58986. if( rc==0 ){
  58987. rc = pMem1->n - pMem2->n;
  58988. }
  58989. return rc;
  58990. }
  58991. /*
  58992. ** Move data out of a btree key or data field and into a Mem structure.
  58993. ** The data or key is taken from the entry that pCur is currently pointing
  58994. ** to. offset and amt determine what portion of the data or key to retrieve.
  58995. ** key is true to get the key or false to get data. The result is written
  58996. ** into the pMem element.
  58997. **
  58998. ** The pMem structure is assumed to be uninitialized. Any prior content
  58999. ** is overwritten without being freed.
  59000. **
  59001. ** If this routine fails for any reason (malloc returns NULL or unable
  59002. ** to read from the disk) then the pMem is left in an inconsistent state.
  59003. */
  59004. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  59005. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  59006. int offset, /* Offset from the start of data to return bytes from. */
  59007. int amt, /* Number of bytes to return. */
  59008. int key, /* If true, retrieve from the btree key, not data. */
  59009. Mem *pMem /* OUT: Return data in this Mem structure. */
  59010. ){
  59011. char *zData; /* Data from the btree layer */
  59012. int available = 0; /* Number of bytes available on the local btree page */
  59013. int rc = SQLITE_OK; /* Return code */
  59014. assert( sqlite3BtreeCursorIsValid(pCur) );
  59015. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  59016. ** that both the BtShared and database handle mutexes are held. */
  59017. assert( (pMem->flags & MEM_RowSet)==0 );
  59018. if( key ){
  59019. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  59020. }else{
  59021. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  59022. }
  59023. assert( zData!=0 );
  59024. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  59025. sqlite3VdbeMemRelease(pMem);
  59026. pMem->z = &zData[offset];
  59027. pMem->flags = MEM_Blob|MEM_Ephem;
  59028. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  59029. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  59030. pMem->enc = 0;
  59031. pMem->type = SQLITE_BLOB;
  59032. if( key ){
  59033. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  59034. }else{
  59035. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  59036. }
  59037. pMem->z[amt] = 0;
  59038. pMem->z[amt+1] = 0;
  59039. if( rc!=SQLITE_OK ){
  59040. sqlite3VdbeMemRelease(pMem);
  59041. }
  59042. }
  59043. pMem->n = amt;
  59044. return rc;
  59045. }
  59046. /* This function is only available internally, it is not part of the
  59047. ** external API. It works in a similar way to sqlite3_value_text(),
  59048. ** except the data returned is in the encoding specified by the second
  59049. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  59050. ** SQLITE_UTF8.
  59051. **
  59052. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  59053. ** If that is the case, then the result must be aligned on an even byte
  59054. ** boundary.
  59055. */
  59056. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  59057. if( !pVal ) return 0;
  59058. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  59059. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  59060. assert( (pVal->flags & MEM_RowSet)==0 );
  59061. if( pVal->flags&MEM_Null ){
  59062. return 0;
  59063. }
  59064. assert( (MEM_Blob>>3) == MEM_Str );
  59065. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  59066. ExpandBlob(pVal);
  59067. if( pVal->flags&MEM_Str ){
  59068. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  59069. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  59070. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  59071. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  59072. return 0;
  59073. }
  59074. }
  59075. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  59076. }else{
  59077. assert( (pVal->flags&MEM_Blob)==0 );
  59078. sqlite3VdbeMemStringify(pVal, enc);
  59079. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  59080. }
  59081. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  59082. || pVal->db->mallocFailed );
  59083. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  59084. return pVal->z;
  59085. }else{
  59086. return 0;
  59087. }
  59088. }
  59089. /*
  59090. ** Create a new sqlite3_value object.
  59091. */
  59092. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  59093. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  59094. if( p ){
  59095. p->flags = MEM_Null;
  59096. p->type = SQLITE_NULL;
  59097. p->db = db;
  59098. }
  59099. return p;
  59100. }
  59101. /*
  59102. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  59103. ** valueNew(). See comments above valueNew() for details.
  59104. */
  59105. struct ValueNewStat4Ctx {
  59106. Parse *pParse;
  59107. Index *pIdx;
  59108. UnpackedRecord **ppRec;
  59109. int iVal;
  59110. };
  59111. /*
  59112. ** Allocate and return a pointer to a new sqlite3_value object. If
  59113. ** the second argument to this function is NULL, the object is allocated
  59114. ** by calling sqlite3ValueNew().
  59115. **
  59116. ** Otherwise, if the second argument is non-zero, then this function is
  59117. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  59118. ** already been allocated, allocate the UnpackedRecord structure that
  59119. ** that function will return to its caller here. Then return a pointer
  59120. ** an sqlite3_value within the UnpackedRecord.a[] array.
  59121. */
  59122. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  59123. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59124. if( p ){
  59125. UnpackedRecord *pRec = p->ppRec[0];
  59126. if( pRec==0 ){
  59127. Index *pIdx = p->pIdx; /* Index being probed */
  59128. int nByte; /* Bytes of space to allocate */
  59129. int i; /* Counter variable */
  59130. int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */
  59131. nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord);
  59132. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  59133. if( pRec ){
  59134. pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx);
  59135. if( pRec->pKeyInfo ){
  59136. assert( pRec->pKeyInfo->nField+1==nCol );
  59137. pRec->pKeyInfo->enc = ENC(db);
  59138. pRec->flags = UNPACKED_PREFIX_MATCH;
  59139. pRec->aMem = (Mem *)&pRec[1];
  59140. for(i=0; i<nCol; i++){
  59141. pRec->aMem[i].flags = MEM_Null;
  59142. pRec->aMem[i].type = SQLITE_NULL;
  59143. pRec->aMem[i].db = db;
  59144. }
  59145. }else{
  59146. sqlite3DbFree(db, pRec);
  59147. pRec = 0;
  59148. }
  59149. }
  59150. if( pRec==0 ) return 0;
  59151. p->ppRec[0] = pRec;
  59152. }
  59153. pRec->nField = p->iVal+1;
  59154. return &pRec->aMem[p->iVal];
  59155. }
  59156. #else
  59157. UNUSED_PARAMETER(p);
  59158. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  59159. return sqlite3ValueNew(db);
  59160. }
  59161. /*
  59162. ** Extract a value from the supplied expression in the manner described
  59163. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  59164. ** using valueNew().
  59165. **
  59166. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  59167. ** has been allocated, it is freed before returning. Or, if pCtx is not
  59168. ** NULL, it is assumed that the caller will free any allocated object
  59169. ** in all cases.
  59170. */
  59171. static int valueFromExpr(
  59172. sqlite3 *db, /* The database connection */
  59173. Expr *pExpr, /* The expression to evaluate */
  59174. u8 enc, /* Encoding to use */
  59175. u8 affinity, /* Affinity to use */
  59176. sqlite3_value **ppVal, /* Write the new value here */
  59177. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  59178. ){
  59179. int op;
  59180. char *zVal = 0;
  59181. sqlite3_value *pVal = 0;
  59182. int negInt = 1;
  59183. const char *zNeg = "";
  59184. int rc = SQLITE_OK;
  59185. if( !pExpr ){
  59186. *ppVal = 0;
  59187. return SQLITE_OK;
  59188. }
  59189. op = pExpr->op;
  59190. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4.
  59191. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  59192. ** when SQLITE_ENABLE_STAT4 is omitted.
  59193. */
  59194. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59195. if( op==TK_REGISTER ) op = pExpr->op2;
  59196. #else
  59197. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  59198. #endif
  59199. /* Handle negative integers in a single step. This is needed in the
  59200. ** case when the value is -9223372036854775808.
  59201. */
  59202. if( op==TK_UMINUS
  59203. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  59204. pExpr = pExpr->pLeft;
  59205. op = pExpr->op;
  59206. negInt = -1;
  59207. zNeg = "-";
  59208. }
  59209. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  59210. pVal = valueNew(db, pCtx);
  59211. if( pVal==0 ) goto no_mem;
  59212. if( ExprHasProperty(pExpr, EP_IntValue) ){
  59213. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  59214. }else{
  59215. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  59216. if( zVal==0 ) goto no_mem;
  59217. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  59218. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  59219. }
  59220. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  59221. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  59222. }else{
  59223. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  59224. }
  59225. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  59226. if( enc!=SQLITE_UTF8 ){
  59227. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  59228. }
  59229. }else if( op==TK_UMINUS ) {
  59230. /* This branch happens for multiple negative signs. Ex: -(-5) */
  59231. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  59232. && pVal!=0
  59233. ){
  59234. sqlite3VdbeMemNumerify(pVal);
  59235. if( pVal->u.i==SMALLEST_INT64 ){
  59236. pVal->flags &= MEM_Int;
  59237. pVal->flags |= MEM_Real;
  59238. pVal->r = (double)LARGEST_INT64;
  59239. }else{
  59240. pVal->u.i = -pVal->u.i;
  59241. }
  59242. pVal->r = -pVal->r;
  59243. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  59244. }
  59245. }else if( op==TK_NULL ){
  59246. pVal = valueNew(db, pCtx);
  59247. if( pVal==0 ) goto no_mem;
  59248. }
  59249. #ifndef SQLITE_OMIT_BLOB_LITERAL
  59250. else if( op==TK_BLOB ){
  59251. int nVal;
  59252. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  59253. assert( pExpr->u.zToken[1]=='\'' );
  59254. pVal = valueNew(db, pCtx);
  59255. if( !pVal ) goto no_mem;
  59256. zVal = &pExpr->u.zToken[2];
  59257. nVal = sqlite3Strlen30(zVal)-1;
  59258. assert( zVal[nVal]=='\'' );
  59259. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  59260. 0, SQLITE_DYNAMIC);
  59261. }
  59262. #endif
  59263. if( pVal ){
  59264. sqlite3VdbeMemStoreType(pVal);
  59265. }
  59266. *ppVal = pVal;
  59267. return rc;
  59268. no_mem:
  59269. db->mallocFailed = 1;
  59270. sqlite3DbFree(db, zVal);
  59271. assert( *ppVal==0 );
  59272. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59273. if( pCtx==0 ) sqlite3ValueFree(pVal);
  59274. #else
  59275. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  59276. #endif
  59277. return SQLITE_NOMEM;
  59278. }
  59279. /*
  59280. ** Create a new sqlite3_value object, containing the value of pExpr.
  59281. **
  59282. ** This only works for very simple expressions that consist of one constant
  59283. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  59284. ** be converted directly into a value, then the value is allocated and
  59285. ** a pointer written to *ppVal. The caller is responsible for deallocating
  59286. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  59287. ** cannot be converted to a value, then *ppVal is set to NULL.
  59288. */
  59289. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  59290. sqlite3 *db, /* The database connection */
  59291. Expr *pExpr, /* The expression to evaluate */
  59292. u8 enc, /* Encoding to use */
  59293. u8 affinity, /* Affinity to use */
  59294. sqlite3_value **ppVal /* Write the new value here */
  59295. ){
  59296. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  59297. }
  59298. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59299. /*
  59300. ** The implementation of the sqlite_record() function. This function accepts
  59301. ** a single argument of any type. The return value is a formatted database
  59302. ** record (a blob) containing the argument value.
  59303. **
  59304. ** This is used to convert the value stored in the 'sample' column of the
  59305. ** sqlite_stat3 table to the record format SQLite uses internally.
  59306. */
  59307. static void recordFunc(
  59308. sqlite3_context *context,
  59309. int argc,
  59310. sqlite3_value **argv
  59311. ){
  59312. const int file_format = 1;
  59313. int iSerial; /* Serial type */
  59314. int nSerial; /* Bytes of space for iSerial as varint */
  59315. int nVal; /* Bytes of space required for argv[0] */
  59316. int nRet;
  59317. sqlite3 *db;
  59318. u8 *aRet;
  59319. UNUSED_PARAMETER( argc );
  59320. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  59321. nSerial = sqlite3VarintLen(iSerial);
  59322. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  59323. db = sqlite3_context_db_handle(context);
  59324. nRet = 1 + nSerial + nVal;
  59325. aRet = sqlite3DbMallocRaw(db, nRet);
  59326. if( aRet==0 ){
  59327. sqlite3_result_error_nomem(context);
  59328. }else{
  59329. aRet[0] = nSerial+1;
  59330. sqlite3PutVarint(&aRet[1], iSerial);
  59331. sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
  59332. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  59333. sqlite3DbFree(db, aRet);
  59334. }
  59335. }
  59336. /*
  59337. ** Register built-in functions used to help read ANALYZE data.
  59338. */
  59339. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  59340. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  59341. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  59342. };
  59343. int i;
  59344. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  59345. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  59346. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  59347. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  59348. }
  59349. }
  59350. /*
  59351. ** This function is used to allocate and populate UnpackedRecord
  59352. ** structures intended to be compared against sample index keys stored
  59353. ** in the sqlite_stat4 table.
  59354. **
  59355. ** A single call to this function attempts to populates field iVal (leftmost
  59356. ** is 0 etc.) of the unpacked record with a value extracted from expression
  59357. ** pExpr. Extraction of values is possible if:
  59358. **
  59359. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  59360. **
  59361. ** * The expression is a bound variable, and this is a reprepare, or
  59362. **
  59363. ** * The sqlite3ValueFromExpr() function is able to extract a value
  59364. ** from the expression (i.e. the expression is a literal value).
  59365. **
  59366. ** If a value can be extracted, the affinity passed as the 5th argument
  59367. ** is applied to it before it is copied into the UnpackedRecord. Output
  59368. ** parameter *pbOk is set to true if a value is extracted, or false
  59369. ** otherwise.
  59370. **
  59371. ** When this function is called, *ppRec must either point to an object
  59372. ** allocated by an earlier call to this function, or must be NULL. If it
  59373. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  59374. ** is allocated (and *ppRec set to point to it) before returning.
  59375. **
  59376. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  59377. ** error if a value cannot be extracted from pExpr. If an error does
  59378. ** occur, an SQLite error code is returned.
  59379. */
  59380. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  59381. Parse *pParse, /* Parse context */
  59382. Index *pIdx, /* Index being probed */
  59383. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  59384. Expr *pExpr, /* The expression to extract a value from */
  59385. u8 affinity, /* Affinity to use */
  59386. int iVal, /* Array element to populate */
  59387. int *pbOk /* OUT: True if value was extracted */
  59388. ){
  59389. int rc = SQLITE_OK;
  59390. sqlite3_value *pVal = 0;
  59391. sqlite3 *db = pParse->db;
  59392. struct ValueNewStat4Ctx alloc;
  59393. alloc.pParse = pParse;
  59394. alloc.pIdx = pIdx;
  59395. alloc.ppRec = ppRec;
  59396. alloc.iVal = iVal;
  59397. /* Skip over any TK_COLLATE nodes */
  59398. pExpr = sqlite3ExprSkipCollate(pExpr);
  59399. if( !pExpr ){
  59400. pVal = valueNew(db, &alloc);
  59401. if( pVal ){
  59402. sqlite3VdbeMemSetNull((Mem*)pVal);
  59403. *pbOk = 1;
  59404. }
  59405. }else if( pExpr->op==TK_VARIABLE
  59406. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  59407. ){
  59408. Vdbe *v;
  59409. int iBindVar = pExpr->iColumn;
  59410. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  59411. if( (v = pParse->pReprepare)!=0 ){
  59412. pVal = valueNew(db, &alloc);
  59413. if( pVal ){
  59414. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  59415. if( rc==SQLITE_OK ){
  59416. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  59417. }
  59418. pVal->db = pParse->db;
  59419. *pbOk = 1;
  59420. sqlite3VdbeMemStoreType((Mem*)pVal);
  59421. }
  59422. }else{
  59423. *pbOk = 0;
  59424. }
  59425. }else{
  59426. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
  59427. *pbOk = (pVal!=0);
  59428. }
  59429. assert( pVal==0 || pVal->db==db );
  59430. return rc;
  59431. }
  59432. /*
  59433. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  59434. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  59435. ** the object.
  59436. */
  59437. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  59438. if( pRec ){
  59439. int i;
  59440. int nCol = pRec->pKeyInfo->nField+1;
  59441. Mem *aMem = pRec->aMem;
  59442. sqlite3 *db = aMem[0].db;
  59443. for(i=0; i<nCol; i++){
  59444. sqlite3DbFree(db, aMem[i].zMalloc);
  59445. }
  59446. sqlite3DbFree(db, pRec->pKeyInfo);
  59447. sqlite3DbFree(db, pRec);
  59448. }
  59449. }
  59450. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  59451. /*
  59452. ** Change the string value of an sqlite3_value object
  59453. */
  59454. SQLITE_PRIVATE void sqlite3ValueSetStr(
  59455. sqlite3_value *v, /* Value to be set */
  59456. int n, /* Length of string z */
  59457. const void *z, /* Text of the new string */
  59458. u8 enc, /* Encoding to use */
  59459. void (*xDel)(void*) /* Destructor for the string */
  59460. ){
  59461. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  59462. }
  59463. /*
  59464. ** Free an sqlite3_value object
  59465. */
  59466. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  59467. if( !v ) return;
  59468. sqlite3VdbeMemRelease((Mem *)v);
  59469. sqlite3DbFree(((Mem*)v)->db, v);
  59470. }
  59471. /*
  59472. ** Return the number of bytes in the sqlite3_value object assuming
  59473. ** that it uses the encoding "enc"
  59474. */
  59475. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  59476. Mem *p = (Mem*)pVal;
  59477. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  59478. if( p->flags & MEM_Zero ){
  59479. return p->n + p->u.nZero;
  59480. }else{
  59481. return p->n;
  59482. }
  59483. }
  59484. return 0;
  59485. }
  59486. /************** End of vdbemem.c *********************************************/
  59487. /************** Begin file vdbeaux.c *****************************************/
  59488. /*
  59489. ** 2003 September 6
  59490. **
  59491. ** The author disclaims copyright to this source code. In place of
  59492. ** a legal notice, here is a blessing:
  59493. **
  59494. ** May you do good and not evil.
  59495. ** May you find forgiveness for yourself and forgive others.
  59496. ** May you share freely, never taking more than you give.
  59497. **
  59498. *************************************************************************
  59499. ** This file contains code used for creating, destroying, and populating
  59500. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  59501. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  59502. ** But that file was getting too big so this subroutines were split out.
  59503. */
  59504. /*
  59505. ** Create a new virtual database engine.
  59506. */
  59507. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  59508. Vdbe *p;
  59509. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  59510. if( p==0 ) return 0;
  59511. p->db = db;
  59512. if( db->pVdbe ){
  59513. db->pVdbe->pPrev = p;
  59514. }
  59515. p->pNext = db->pVdbe;
  59516. p->pPrev = 0;
  59517. db->pVdbe = p;
  59518. p->magic = VDBE_MAGIC_INIT;
  59519. return p;
  59520. }
  59521. /*
  59522. ** Remember the SQL string for a prepared statement.
  59523. */
  59524. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  59525. assert( isPrepareV2==1 || isPrepareV2==0 );
  59526. if( p==0 ) return;
  59527. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  59528. if( !isPrepareV2 ) return;
  59529. #endif
  59530. assert( p->zSql==0 );
  59531. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  59532. p->isPrepareV2 = (u8)isPrepareV2;
  59533. }
  59534. /*
  59535. ** Return the SQL associated with a prepared statement
  59536. */
  59537. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  59538. Vdbe *p = (Vdbe *)pStmt;
  59539. return (p && p->isPrepareV2) ? p->zSql : 0;
  59540. }
  59541. /*
  59542. ** Swap all content between two VDBE structures.
  59543. */
  59544. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  59545. Vdbe tmp, *pTmp;
  59546. char *zTmp;
  59547. tmp = *pA;
  59548. *pA = *pB;
  59549. *pB = tmp;
  59550. pTmp = pA->pNext;
  59551. pA->pNext = pB->pNext;
  59552. pB->pNext = pTmp;
  59553. pTmp = pA->pPrev;
  59554. pA->pPrev = pB->pPrev;
  59555. pB->pPrev = pTmp;
  59556. zTmp = pA->zSql;
  59557. pA->zSql = pB->zSql;
  59558. pB->zSql = zTmp;
  59559. pB->isPrepareV2 = pA->isPrepareV2;
  59560. }
  59561. #ifdef SQLITE_DEBUG
  59562. /*
  59563. ** Turn tracing on or off
  59564. */
  59565. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  59566. p->trace = trace;
  59567. }
  59568. #endif
  59569. /*
  59570. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  59571. ** it was.
  59572. **
  59573. ** If an out-of-memory error occurs while resizing the array, return
  59574. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  59575. ** unchanged (this is so that any opcodes already allocated can be
  59576. ** correctly deallocated along with the rest of the Vdbe).
  59577. */
  59578. static int growOpArray(Vdbe *p){
  59579. VdbeOp *pNew;
  59580. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  59581. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  59582. if( pNew ){
  59583. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  59584. p->aOp = pNew;
  59585. }
  59586. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  59587. }
  59588. /*
  59589. ** Add a new instruction to the list of instructions current in the
  59590. ** VDBE. Return the address of the new instruction.
  59591. **
  59592. ** Parameters:
  59593. **
  59594. ** p Pointer to the VDBE
  59595. **
  59596. ** op The opcode for this instruction
  59597. **
  59598. ** p1, p2, p3 Operands
  59599. **
  59600. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  59601. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  59602. ** operand.
  59603. */
  59604. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  59605. int i;
  59606. VdbeOp *pOp;
  59607. i = p->nOp;
  59608. assert( p->magic==VDBE_MAGIC_INIT );
  59609. assert( op>0 && op<0xff );
  59610. if( p->nOpAlloc<=i ){
  59611. if( growOpArray(p) ){
  59612. return 1;
  59613. }
  59614. }
  59615. p->nOp++;
  59616. pOp = &p->aOp[i];
  59617. pOp->opcode = (u8)op;
  59618. pOp->p5 = 0;
  59619. pOp->p1 = p1;
  59620. pOp->p2 = p2;
  59621. pOp->p3 = p3;
  59622. pOp->p4.p = 0;
  59623. pOp->p4type = P4_NOTUSED;
  59624. #ifdef SQLITE_DEBUG
  59625. pOp->zComment = 0;
  59626. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59627. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  59628. }
  59629. #endif
  59630. #ifdef VDBE_PROFILE
  59631. pOp->cycles = 0;
  59632. pOp->cnt = 0;
  59633. #endif
  59634. return i;
  59635. }
  59636. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  59637. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  59638. }
  59639. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  59640. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  59641. }
  59642. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  59643. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  59644. }
  59645. /*
  59646. ** Add an opcode that includes the p4 value as a pointer.
  59647. */
  59648. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  59649. Vdbe *p, /* Add the opcode to this VM */
  59650. int op, /* The new opcode */
  59651. int p1, /* The P1 operand */
  59652. int p2, /* The P2 operand */
  59653. int p3, /* The P3 operand */
  59654. const char *zP4, /* The P4 operand */
  59655. int p4type /* P4 operand type */
  59656. ){
  59657. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59658. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  59659. return addr;
  59660. }
  59661. /*
  59662. ** Add an OP_ParseSchema opcode. This routine is broken out from
  59663. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  59664. ** as having been used.
  59665. **
  59666. ** The zWhere string must have been obtained from sqlite3_malloc().
  59667. ** This routine will take ownership of the allocated memory.
  59668. */
  59669. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  59670. int j;
  59671. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  59672. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  59673. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  59674. }
  59675. /*
  59676. ** Add an opcode that includes the p4 value as an integer.
  59677. */
  59678. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  59679. Vdbe *p, /* Add the opcode to this VM */
  59680. int op, /* The new opcode */
  59681. int p1, /* The P1 operand */
  59682. int p2, /* The P2 operand */
  59683. int p3, /* The P3 operand */
  59684. int p4 /* The P4 operand as an integer */
  59685. ){
  59686. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59687. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  59688. return addr;
  59689. }
  59690. /*
  59691. ** Create a new symbolic label for an instruction that has yet to be
  59692. ** coded. The symbolic label is really just a negative number. The
  59693. ** label can be used as the P2 value of an operation. Later, when
  59694. ** the label is resolved to a specific address, the VDBE will scan
  59695. ** through its operation list and change all values of P2 which match
  59696. ** the label into the resolved address.
  59697. **
  59698. ** The VDBE knows that a P2 value is a label because labels are
  59699. ** always negative and P2 values are suppose to be non-negative.
  59700. ** Hence, a negative P2 value is a label that has yet to be resolved.
  59701. **
  59702. ** Zero is returned if a malloc() fails.
  59703. */
  59704. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  59705. int i = p->nLabel++;
  59706. assert( p->magic==VDBE_MAGIC_INIT );
  59707. if( (i & (i-1))==0 ){
  59708. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  59709. (i*2+1)*sizeof(p->aLabel[0]));
  59710. }
  59711. if( p->aLabel ){
  59712. p->aLabel[i] = -1;
  59713. }
  59714. return -1-i;
  59715. }
  59716. /*
  59717. ** Resolve label "x" to be the address of the next instruction to
  59718. ** be inserted. The parameter "x" must have been obtained from
  59719. ** a prior call to sqlite3VdbeMakeLabel().
  59720. */
  59721. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  59722. int j = -1-x;
  59723. assert( p->magic==VDBE_MAGIC_INIT );
  59724. assert( j<p->nLabel );
  59725. if( j>=0 && p->aLabel ){
  59726. p->aLabel[j] = p->nOp;
  59727. }
  59728. }
  59729. /*
  59730. ** Mark the VDBE as one that can only be run one time.
  59731. */
  59732. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  59733. p->runOnlyOnce = 1;
  59734. }
  59735. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  59736. /*
  59737. ** The following type and function are used to iterate through all opcodes
  59738. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  59739. ** invoke directly or indirectly. It should be used as follows:
  59740. **
  59741. ** Op *pOp;
  59742. ** VdbeOpIter sIter;
  59743. **
  59744. ** memset(&sIter, 0, sizeof(sIter));
  59745. ** sIter.v = v; // v is of type Vdbe*
  59746. ** while( (pOp = opIterNext(&sIter)) ){
  59747. ** // Do something with pOp
  59748. ** }
  59749. ** sqlite3DbFree(v->db, sIter.apSub);
  59750. **
  59751. */
  59752. typedef struct VdbeOpIter VdbeOpIter;
  59753. struct VdbeOpIter {
  59754. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  59755. SubProgram **apSub; /* Array of subprograms */
  59756. int nSub; /* Number of entries in apSub */
  59757. int iAddr; /* Address of next instruction to return */
  59758. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  59759. };
  59760. static Op *opIterNext(VdbeOpIter *p){
  59761. Vdbe *v = p->v;
  59762. Op *pRet = 0;
  59763. Op *aOp;
  59764. int nOp;
  59765. if( p->iSub<=p->nSub ){
  59766. if( p->iSub==0 ){
  59767. aOp = v->aOp;
  59768. nOp = v->nOp;
  59769. }else{
  59770. aOp = p->apSub[p->iSub-1]->aOp;
  59771. nOp = p->apSub[p->iSub-1]->nOp;
  59772. }
  59773. assert( p->iAddr<nOp );
  59774. pRet = &aOp[p->iAddr];
  59775. p->iAddr++;
  59776. if( p->iAddr==nOp ){
  59777. p->iSub++;
  59778. p->iAddr = 0;
  59779. }
  59780. if( pRet->p4type==P4_SUBPROGRAM ){
  59781. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  59782. int j;
  59783. for(j=0; j<p->nSub; j++){
  59784. if( p->apSub[j]==pRet->p4.pProgram ) break;
  59785. }
  59786. if( j==p->nSub ){
  59787. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  59788. if( !p->apSub ){
  59789. pRet = 0;
  59790. }else{
  59791. p->apSub[p->nSub++] = pRet->p4.pProgram;
  59792. }
  59793. }
  59794. }
  59795. }
  59796. return pRet;
  59797. }
  59798. /*
  59799. ** Check if the program stored in the VM associated with pParse may
  59800. ** throw an ABORT exception (causing the statement, but not entire transaction
  59801. ** to be rolled back). This condition is true if the main program or any
  59802. ** sub-programs contains any of the following:
  59803. **
  59804. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59805. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59806. ** * OP_Destroy
  59807. ** * OP_VUpdate
  59808. ** * OP_VRename
  59809. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  59810. **
  59811. ** Then check that the value of Parse.mayAbort is true if an
  59812. ** ABORT may be thrown, or false otherwise. Return true if it does
  59813. ** match, or false otherwise. This function is intended to be used as
  59814. ** part of an assert statement in the compiler. Similar to:
  59815. **
  59816. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  59817. */
  59818. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  59819. int hasAbort = 0;
  59820. Op *pOp;
  59821. VdbeOpIter sIter;
  59822. memset(&sIter, 0, sizeof(sIter));
  59823. sIter.v = v;
  59824. while( (pOp = opIterNext(&sIter))!=0 ){
  59825. int opcode = pOp->opcode;
  59826. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  59827. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59828. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  59829. #endif
  59830. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  59831. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  59832. ){
  59833. hasAbort = 1;
  59834. break;
  59835. }
  59836. }
  59837. sqlite3DbFree(v->db, sIter.apSub);
  59838. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  59839. ** If malloc failed, then the while() loop above may not have iterated
  59840. ** through all opcodes and hasAbort may be set incorrectly. Return
  59841. ** true for this case to prevent the assert() in the callers frame
  59842. ** from failing. */
  59843. return ( v->db->mallocFailed || hasAbort==mayAbort );
  59844. }
  59845. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  59846. /*
  59847. ** Loop through the program looking for P2 values that are negative
  59848. ** on jump instructions. Each such value is a label. Resolve the
  59849. ** label by setting the P2 value to its correct non-zero value.
  59850. **
  59851. ** This routine is called once after all opcodes have been inserted.
  59852. **
  59853. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  59854. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  59855. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  59856. **
  59857. ** The Op.opflags field is set on all opcodes.
  59858. */
  59859. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  59860. int i;
  59861. int nMaxArgs = *pMaxFuncArgs;
  59862. Op *pOp;
  59863. int *aLabel = p->aLabel;
  59864. p->readOnly = 1;
  59865. p->bIsReader = 0;
  59866. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  59867. u8 opcode = pOp->opcode;
  59868. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  59869. ** cases from this switch! */
  59870. switch( opcode ){
  59871. case OP_Function:
  59872. case OP_AggStep: {
  59873. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  59874. break;
  59875. }
  59876. case OP_Transaction: {
  59877. if( pOp->p2!=0 ) p->readOnly = 0;
  59878. /* fall thru */
  59879. }
  59880. case OP_AutoCommit:
  59881. case OP_Savepoint: {
  59882. p->bIsReader = 1;
  59883. break;
  59884. }
  59885. #ifndef SQLITE_OMIT_WAL
  59886. case OP_Checkpoint:
  59887. #endif
  59888. case OP_Vacuum:
  59889. case OP_JournalMode: {
  59890. p->readOnly = 0;
  59891. p->bIsReader = 1;
  59892. break;
  59893. }
  59894. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59895. case OP_VUpdate: {
  59896. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  59897. break;
  59898. }
  59899. case OP_VFilter: {
  59900. int n;
  59901. assert( p->nOp - i >= 3 );
  59902. assert( pOp[-1].opcode==OP_Integer );
  59903. n = pOp[-1].p1;
  59904. if( n>nMaxArgs ) nMaxArgs = n;
  59905. break;
  59906. }
  59907. #endif
  59908. case OP_Next:
  59909. case OP_SorterNext: {
  59910. pOp->p4.xAdvance = sqlite3BtreeNext;
  59911. pOp->p4type = P4_ADVANCE;
  59912. break;
  59913. }
  59914. case OP_Prev: {
  59915. pOp->p4.xAdvance = sqlite3BtreePrevious;
  59916. pOp->p4type = P4_ADVANCE;
  59917. break;
  59918. }
  59919. }
  59920. pOp->opflags = sqlite3OpcodeProperty[opcode];
  59921. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  59922. assert( -1-pOp->p2<p->nLabel );
  59923. pOp->p2 = aLabel[-1-pOp->p2];
  59924. }
  59925. }
  59926. sqlite3DbFree(p->db, p->aLabel);
  59927. p->aLabel = 0;
  59928. *pMaxFuncArgs = nMaxArgs;
  59929. assert( p->bIsReader!=0 || p->btreeMask==0 );
  59930. }
  59931. /*
  59932. ** Return the address of the next instruction to be inserted.
  59933. */
  59934. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  59935. assert( p->magic==VDBE_MAGIC_INIT );
  59936. return p->nOp;
  59937. }
  59938. /*
  59939. ** This function returns a pointer to the array of opcodes associated with
  59940. ** the Vdbe passed as the first argument. It is the callers responsibility
  59941. ** to arrange for the returned array to be eventually freed using the
  59942. ** vdbeFreeOpArray() function.
  59943. **
  59944. ** Before returning, *pnOp is set to the number of entries in the returned
  59945. ** array. Also, *pnMaxArg is set to the larger of its current value and
  59946. ** the number of entries in the Vdbe.apArg[] array required to execute the
  59947. ** returned program.
  59948. */
  59949. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  59950. VdbeOp *aOp = p->aOp;
  59951. assert( aOp && !p->db->mallocFailed );
  59952. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  59953. assert( p->btreeMask==0 );
  59954. resolveP2Values(p, pnMaxArg);
  59955. *pnOp = p->nOp;
  59956. p->aOp = 0;
  59957. return aOp;
  59958. }
  59959. /*
  59960. ** Add a whole list of operations to the operation stack. Return the
  59961. ** address of the first operation added.
  59962. */
  59963. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  59964. int addr;
  59965. assert( p->magic==VDBE_MAGIC_INIT );
  59966. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  59967. return 0;
  59968. }
  59969. addr = p->nOp;
  59970. if( ALWAYS(nOp>0) ){
  59971. int i;
  59972. VdbeOpList const *pIn = aOp;
  59973. for(i=0; i<nOp; i++, pIn++){
  59974. int p2 = pIn->p2;
  59975. VdbeOp *pOut = &p->aOp[i+addr];
  59976. pOut->opcode = pIn->opcode;
  59977. pOut->p1 = pIn->p1;
  59978. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  59979. pOut->p2 = addr + ADDR(p2);
  59980. }else{
  59981. pOut->p2 = p2;
  59982. }
  59983. pOut->p3 = pIn->p3;
  59984. pOut->p4type = P4_NOTUSED;
  59985. pOut->p4.p = 0;
  59986. pOut->p5 = 0;
  59987. #ifdef SQLITE_DEBUG
  59988. pOut->zComment = 0;
  59989. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59990. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  59991. }
  59992. #endif
  59993. }
  59994. p->nOp += nOp;
  59995. }
  59996. return addr;
  59997. }
  59998. /*
  59999. ** Change the value of the P1 operand for a specific instruction.
  60000. ** This routine is useful when a large program is loaded from a
  60001. ** static array using sqlite3VdbeAddOpList but we want to make a
  60002. ** few minor changes to the program.
  60003. */
  60004. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  60005. assert( p!=0 );
  60006. if( ((u32)p->nOp)>addr ){
  60007. p->aOp[addr].p1 = val;
  60008. }
  60009. }
  60010. /*
  60011. ** Change the value of the P2 operand for a specific instruction.
  60012. ** This routine is useful for setting a jump destination.
  60013. */
  60014. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  60015. assert( p!=0 );
  60016. if( ((u32)p->nOp)>addr ){
  60017. p->aOp[addr].p2 = val;
  60018. }
  60019. }
  60020. /*
  60021. ** Change the value of the P3 operand for a specific instruction.
  60022. */
  60023. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  60024. assert( p!=0 );
  60025. if( ((u32)p->nOp)>addr ){
  60026. p->aOp[addr].p3 = val;
  60027. }
  60028. }
  60029. /*
  60030. ** Change the value of the P5 operand for the most recently
  60031. ** added operation.
  60032. */
  60033. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  60034. assert( p!=0 );
  60035. if( p->aOp ){
  60036. assert( p->nOp>0 );
  60037. p->aOp[p->nOp-1].p5 = val;
  60038. }
  60039. }
  60040. /*
  60041. ** Change the P2 operand of instruction addr so that it points to
  60042. ** the address of the next instruction to be coded.
  60043. */
  60044. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  60045. if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  60046. }
  60047. /*
  60048. ** If the input FuncDef structure is ephemeral, then free it. If
  60049. ** the FuncDef is not ephermal, then do nothing.
  60050. */
  60051. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  60052. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  60053. sqlite3DbFree(db, pDef);
  60054. }
  60055. }
  60056. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  60057. /*
  60058. ** Delete a P4 value if necessary.
  60059. */
  60060. static void freeP4(sqlite3 *db, int p4type, void *p4){
  60061. if( p4 ){
  60062. assert( db );
  60063. switch( p4type ){
  60064. case P4_REAL:
  60065. case P4_INT64:
  60066. case P4_DYNAMIC:
  60067. case P4_KEYINFO:
  60068. case P4_INTARRAY:
  60069. case P4_KEYINFO_HANDOFF: {
  60070. sqlite3DbFree(db, p4);
  60071. break;
  60072. }
  60073. case P4_MPRINTF: {
  60074. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  60075. break;
  60076. }
  60077. case P4_FUNCDEF: {
  60078. freeEphemeralFunction(db, (FuncDef*)p4);
  60079. break;
  60080. }
  60081. case P4_MEM: {
  60082. if( db->pnBytesFreed==0 ){
  60083. sqlite3ValueFree((sqlite3_value*)p4);
  60084. }else{
  60085. Mem *p = (Mem*)p4;
  60086. sqlite3DbFree(db, p->zMalloc);
  60087. sqlite3DbFree(db, p);
  60088. }
  60089. break;
  60090. }
  60091. case P4_VTAB : {
  60092. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  60093. break;
  60094. }
  60095. }
  60096. }
  60097. }
  60098. /*
  60099. ** Free the space allocated for aOp and any p4 values allocated for the
  60100. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  60101. ** nOp entries.
  60102. */
  60103. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  60104. if( aOp ){
  60105. Op *pOp;
  60106. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  60107. freeP4(db, pOp->p4type, pOp->p4.p);
  60108. #ifdef SQLITE_DEBUG
  60109. sqlite3DbFree(db, pOp->zComment);
  60110. #endif
  60111. }
  60112. }
  60113. sqlite3DbFree(db, aOp);
  60114. }
  60115. /*
  60116. ** Link the SubProgram object passed as the second argument into the linked
  60117. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  60118. ** objects when the VM is no longer required.
  60119. */
  60120. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  60121. p->pNext = pVdbe->pProgram;
  60122. pVdbe->pProgram = p;
  60123. }
  60124. /*
  60125. ** Change the opcode at addr into OP_Noop
  60126. */
  60127. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  60128. if( p->aOp ){
  60129. VdbeOp *pOp = &p->aOp[addr];
  60130. sqlite3 *db = p->db;
  60131. freeP4(db, pOp->p4type, pOp->p4.p);
  60132. memset(pOp, 0, sizeof(pOp[0]));
  60133. pOp->opcode = OP_Noop;
  60134. }
  60135. }
  60136. /*
  60137. ** Change the value of the P4 operand for a specific instruction.
  60138. ** This routine is useful when a large program is loaded from a
  60139. ** static array using sqlite3VdbeAddOpList but we want to make a
  60140. ** few minor changes to the program.
  60141. **
  60142. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  60143. ** the string is made into memory obtained from sqlite3_malloc().
  60144. ** A value of n==0 means copy bytes of zP4 up to and including the
  60145. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  60146. **
  60147. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  60148. ** A copy is made of the KeyInfo structure into memory obtained from
  60149. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  60150. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  60151. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  60152. ** caller should not free the allocation, it will be freed when the Vdbe is
  60153. ** finalized.
  60154. **
  60155. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  60156. ** to a string or structure that is guaranteed to exist for the lifetime of
  60157. ** the Vdbe. In these cases we can just copy the pointer.
  60158. **
  60159. ** If addr<0 then change P4 on the most recently inserted instruction.
  60160. */
  60161. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  60162. Op *pOp;
  60163. sqlite3 *db;
  60164. assert( p!=0 );
  60165. db = p->db;
  60166. assert( p->magic==VDBE_MAGIC_INIT );
  60167. if( p->aOp==0 || db->mallocFailed ){
  60168. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  60169. freeP4(db, n, (void*)*(char**)&zP4);
  60170. }
  60171. return;
  60172. }
  60173. assert( p->nOp>0 );
  60174. assert( addr<p->nOp );
  60175. if( addr<0 ){
  60176. addr = p->nOp - 1;
  60177. }
  60178. pOp = &p->aOp[addr];
  60179. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  60180. freeP4(db, pOp->p4type, pOp->p4.p);
  60181. pOp->p4.p = 0;
  60182. if( n==P4_INT32 ){
  60183. /* Note: this cast is safe, because the origin data point was an int
  60184. ** that was cast to a (const char *). */
  60185. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  60186. pOp->p4type = P4_INT32;
  60187. }else if( zP4==0 ){
  60188. pOp->p4.p = 0;
  60189. pOp->p4type = P4_NOTUSED;
  60190. }else if( n==P4_KEYINFO ){
  60191. KeyInfo *pOrig, *pNew;
  60192. pOrig = (KeyInfo*)zP4;
  60193. pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
  60194. if( pNew ){
  60195. memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
  60196. memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
  60197. pOp->p4type = P4_KEYINFO;
  60198. }else{
  60199. p->db->mallocFailed = 1;
  60200. pOp->p4type = P4_NOTUSED;
  60201. }
  60202. }else if( n==P4_KEYINFO_HANDOFF ){
  60203. pOp->p4.p = (void*)zP4;
  60204. pOp->p4type = P4_KEYINFO;
  60205. }else if( n==P4_VTAB ){
  60206. pOp->p4.p = (void*)zP4;
  60207. pOp->p4type = P4_VTAB;
  60208. sqlite3VtabLock((VTable *)zP4);
  60209. assert( ((VTable *)zP4)->db==p->db );
  60210. }else if( n<0 ){
  60211. pOp->p4.p = (void*)zP4;
  60212. pOp->p4type = (signed char)n;
  60213. }else{
  60214. if( n==0 ) n = sqlite3Strlen30(zP4);
  60215. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  60216. pOp->p4type = P4_DYNAMIC;
  60217. }
  60218. }
  60219. #ifndef NDEBUG
  60220. /*
  60221. ** Change the comment on the most recently coded instruction. Or
  60222. ** insert a No-op and add the comment to that new instruction. This
  60223. ** makes the code easier to read during debugging. None of this happens
  60224. ** in a production build.
  60225. */
  60226. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  60227. assert( p->nOp>0 || p->aOp==0 );
  60228. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  60229. if( p->nOp ){
  60230. assert( p->aOp );
  60231. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  60232. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  60233. }
  60234. }
  60235. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  60236. va_list ap;
  60237. if( p ){
  60238. va_start(ap, zFormat);
  60239. vdbeVComment(p, zFormat, ap);
  60240. va_end(ap);
  60241. }
  60242. }
  60243. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  60244. va_list ap;
  60245. if( p ){
  60246. sqlite3VdbeAddOp0(p, OP_Noop);
  60247. va_start(ap, zFormat);
  60248. vdbeVComment(p, zFormat, ap);
  60249. va_end(ap);
  60250. }
  60251. }
  60252. #endif /* NDEBUG */
  60253. /*
  60254. ** Return the opcode for a given address. If the address is -1, then
  60255. ** return the most recently inserted opcode.
  60256. **
  60257. ** If a memory allocation error has occurred prior to the calling of this
  60258. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  60259. ** is readable but not writable, though it is cast to a writable value.
  60260. ** The return of a dummy opcode allows the call to continue functioning
  60261. ** after a OOM fault without having to check to see if the return from
  60262. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  60263. ** dummy will never be written to. This is verified by code inspection and
  60264. ** by running with Valgrind.
  60265. **
  60266. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  60267. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  60268. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  60269. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  60270. ** having to double-check to make sure that the result is non-negative. But
  60271. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  60272. ** check the value of p->nOp-1 before continuing.
  60273. */
  60274. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  60275. /* C89 specifies that the constant "dummy" will be initialized to all
  60276. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  60277. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  60278. assert( p->magic==VDBE_MAGIC_INIT );
  60279. if( addr<0 ){
  60280. #ifdef SQLITE_OMIT_TRACE
  60281. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  60282. #endif
  60283. addr = p->nOp - 1;
  60284. }
  60285. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  60286. if( p->db->mallocFailed ){
  60287. return (VdbeOp*)&dummy;
  60288. }else{
  60289. return &p->aOp[addr];
  60290. }
  60291. }
  60292. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  60293. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60294. /*
  60295. ** Compute a string that describes the P4 parameter for an opcode.
  60296. ** Use zTemp for any required temporary buffer space.
  60297. */
  60298. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  60299. char *zP4 = zTemp;
  60300. assert( nTemp>=20 );
  60301. switch( pOp->p4type ){
  60302. case P4_KEYINFO_STATIC:
  60303. case P4_KEYINFO: {
  60304. int i, j;
  60305. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  60306. assert( pKeyInfo->aSortOrder!=0 );
  60307. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  60308. i = sqlite3Strlen30(zTemp);
  60309. for(j=0; j<pKeyInfo->nField; j++){
  60310. CollSeq *pColl = pKeyInfo->aColl[j];
  60311. const char *zColl = pColl ? pColl->zName : "nil";
  60312. int n = sqlite3Strlen30(zColl);
  60313. if( i+n>nTemp-6 ){
  60314. memcpy(&zTemp[i],",...",4);
  60315. break;
  60316. }
  60317. zTemp[i++] = ',';
  60318. if( pKeyInfo->aSortOrder[j] ){
  60319. zTemp[i++] = '-';
  60320. }
  60321. memcpy(&zTemp[i], zColl, n+1);
  60322. i += n;
  60323. }
  60324. zTemp[i++] = ')';
  60325. zTemp[i] = 0;
  60326. assert( i<nTemp );
  60327. break;
  60328. }
  60329. case P4_COLLSEQ: {
  60330. CollSeq *pColl = pOp->p4.pColl;
  60331. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  60332. break;
  60333. }
  60334. case P4_FUNCDEF: {
  60335. FuncDef *pDef = pOp->p4.pFunc;
  60336. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  60337. break;
  60338. }
  60339. case P4_INT64: {
  60340. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  60341. break;
  60342. }
  60343. case P4_INT32: {
  60344. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  60345. break;
  60346. }
  60347. case P4_REAL: {
  60348. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  60349. break;
  60350. }
  60351. case P4_MEM: {
  60352. Mem *pMem = pOp->p4.pMem;
  60353. if( pMem->flags & MEM_Str ){
  60354. zP4 = pMem->z;
  60355. }else if( pMem->flags & MEM_Int ){
  60356. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  60357. }else if( pMem->flags & MEM_Real ){
  60358. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  60359. }else if( pMem->flags & MEM_Null ){
  60360. sqlite3_snprintf(nTemp, zTemp, "NULL");
  60361. }else{
  60362. assert( pMem->flags & MEM_Blob );
  60363. zP4 = "(blob)";
  60364. }
  60365. break;
  60366. }
  60367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60368. case P4_VTAB: {
  60369. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  60370. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  60371. break;
  60372. }
  60373. #endif
  60374. case P4_INTARRAY: {
  60375. sqlite3_snprintf(nTemp, zTemp, "intarray");
  60376. break;
  60377. }
  60378. case P4_SUBPROGRAM: {
  60379. sqlite3_snprintf(nTemp, zTemp, "program");
  60380. break;
  60381. }
  60382. case P4_ADVANCE: {
  60383. zTemp[0] = 0;
  60384. break;
  60385. }
  60386. default: {
  60387. zP4 = pOp->p4.z;
  60388. if( zP4==0 ){
  60389. zP4 = zTemp;
  60390. zTemp[0] = 0;
  60391. }
  60392. }
  60393. }
  60394. assert( zP4!=0 );
  60395. return zP4;
  60396. }
  60397. #endif
  60398. /*
  60399. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  60400. **
  60401. ** The prepared statements need to know in advance the complete set of
  60402. ** attached databases that will be use. A mask of these databases
  60403. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  60404. ** p->btreeMask of databases that will require a lock.
  60405. */
  60406. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  60407. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  60408. assert( i<(int)sizeof(p->btreeMask)*8 );
  60409. p->btreeMask |= ((yDbMask)1)<<i;
  60410. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  60411. p->lockMask |= ((yDbMask)1)<<i;
  60412. }
  60413. }
  60414. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60415. /*
  60416. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  60417. ** this routine obtains the mutex associated with each BtShared structure
  60418. ** that may be accessed by the VM passed as an argument. In doing so it also
  60419. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  60420. ** that the correct busy-handler callback is invoked if required.
  60421. **
  60422. ** If SQLite is not threadsafe but does support shared-cache mode, then
  60423. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  60424. ** of all of BtShared structures accessible via the database handle
  60425. ** associated with the VM.
  60426. **
  60427. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  60428. ** function is a no-op.
  60429. **
  60430. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  60431. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  60432. ** corresponding to btrees that use shared cache. Then the runtime of
  60433. ** this routine is N*N. But as N is rarely more than 1, this should not
  60434. ** be a problem.
  60435. */
  60436. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  60437. int i;
  60438. yDbMask mask;
  60439. sqlite3 *db;
  60440. Db *aDb;
  60441. int nDb;
  60442. if( p->lockMask==0 ) return; /* The common case */
  60443. db = p->db;
  60444. aDb = db->aDb;
  60445. nDb = db->nDb;
  60446. for(i=0, mask=1; i<nDb; i++, mask += mask){
  60447. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  60448. sqlite3BtreeEnter(aDb[i].pBt);
  60449. }
  60450. }
  60451. }
  60452. #endif
  60453. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60454. /*
  60455. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  60456. */
  60457. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  60458. int i;
  60459. yDbMask mask;
  60460. sqlite3 *db;
  60461. Db *aDb;
  60462. int nDb;
  60463. if( p->lockMask==0 ) return; /* The common case */
  60464. db = p->db;
  60465. aDb = db->aDb;
  60466. nDb = db->nDb;
  60467. for(i=0, mask=1; i<nDb; i++, mask += mask){
  60468. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  60469. sqlite3BtreeLeave(aDb[i].pBt);
  60470. }
  60471. }
  60472. }
  60473. #endif
  60474. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60475. /*
  60476. ** Print a single opcode. This routine is used for debugging only.
  60477. */
  60478. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  60479. char *zP4;
  60480. char zPtr[50];
  60481. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  60482. if( pOut==0 ) pOut = stdout;
  60483. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  60484. fprintf(pOut, zFormat1, pc,
  60485. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  60486. #ifdef SQLITE_DEBUG
  60487. pOp->zComment ? pOp->zComment : ""
  60488. #else
  60489. ""
  60490. #endif
  60491. );
  60492. fflush(pOut);
  60493. }
  60494. #endif
  60495. /*
  60496. ** Release an array of N Mem elements
  60497. */
  60498. static void releaseMemArray(Mem *p, int N){
  60499. if( p && N ){
  60500. Mem *pEnd;
  60501. sqlite3 *db = p->db;
  60502. u8 malloc_failed = db->mallocFailed;
  60503. if( db->pnBytesFreed ){
  60504. for(pEnd=&p[N]; p<pEnd; p++){
  60505. sqlite3DbFree(db, p->zMalloc);
  60506. }
  60507. return;
  60508. }
  60509. for(pEnd=&p[N]; p<pEnd; p++){
  60510. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  60511. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  60512. ** that takes advantage of the fact that the memory cell value is
  60513. ** being set to NULL after releasing any dynamic resources.
  60514. **
  60515. ** The justification for duplicating code is that according to
  60516. ** callgrind, this causes a certain test case to hit the CPU 4.7
  60517. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  60518. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  60519. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  60520. ** with no indexes using a single prepared INSERT statement, bind()
  60521. ** and reset(). Inserts are grouped into a transaction.
  60522. */
  60523. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  60524. sqlite3VdbeMemRelease(p);
  60525. }else if( p->zMalloc ){
  60526. sqlite3DbFree(db, p->zMalloc);
  60527. p->zMalloc = 0;
  60528. }
  60529. p->flags = MEM_Invalid;
  60530. }
  60531. db->mallocFailed = malloc_failed;
  60532. }
  60533. }
  60534. /*
  60535. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  60536. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  60537. */
  60538. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  60539. int i;
  60540. Mem *aMem = VdbeFrameMem(p);
  60541. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  60542. for(i=0; i<p->nChildCsr; i++){
  60543. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  60544. }
  60545. releaseMemArray(aMem, p->nChildMem);
  60546. sqlite3DbFree(p->v->db, p);
  60547. }
  60548. #ifndef SQLITE_OMIT_EXPLAIN
  60549. /*
  60550. ** Give a listing of the program in the virtual machine.
  60551. **
  60552. ** The interface is the same as sqlite3VdbeExec(). But instead of
  60553. ** running the code, it invokes the callback once for each instruction.
  60554. ** This feature is used to implement "EXPLAIN".
  60555. **
  60556. ** When p->explain==1, each instruction is listed. When
  60557. ** p->explain==2, only OP_Explain instructions are listed and these
  60558. ** are shown in a different format. p->explain==2 is used to implement
  60559. ** EXPLAIN QUERY PLAN.
  60560. **
  60561. ** When p->explain==1, first the main program is listed, then each of
  60562. ** the trigger subprograms are listed one by one.
  60563. */
  60564. SQLITE_PRIVATE int sqlite3VdbeList(
  60565. Vdbe *p /* The VDBE */
  60566. ){
  60567. int nRow; /* Stop when row count reaches this */
  60568. int nSub = 0; /* Number of sub-vdbes seen so far */
  60569. SubProgram **apSub = 0; /* Array of sub-vdbes */
  60570. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  60571. sqlite3 *db = p->db; /* The database connection */
  60572. int i; /* Loop counter */
  60573. int rc = SQLITE_OK; /* Return code */
  60574. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  60575. assert( p->explain );
  60576. assert( p->magic==VDBE_MAGIC_RUN );
  60577. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  60578. /* Even though this opcode does not use dynamic strings for
  60579. ** the result, result columns may become dynamic if the user calls
  60580. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  60581. */
  60582. releaseMemArray(pMem, 8);
  60583. p->pResultSet = 0;
  60584. if( p->rc==SQLITE_NOMEM ){
  60585. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  60586. ** sqlite3_column_text16() failed. */
  60587. db->mallocFailed = 1;
  60588. return SQLITE_ERROR;
  60589. }
  60590. /* When the number of output rows reaches nRow, that means the
  60591. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  60592. ** nRow is the sum of the number of rows in the main program, plus
  60593. ** the sum of the number of rows in all trigger subprograms encountered
  60594. ** so far. The nRow value will increase as new trigger subprograms are
  60595. ** encountered, but p->pc will eventually catch up to nRow.
  60596. */
  60597. nRow = p->nOp;
  60598. if( p->explain==1 ){
  60599. /* The first 8 memory cells are used for the result set. So we will
  60600. ** commandeer the 9th cell to use as storage for an array of pointers
  60601. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  60602. ** cells. */
  60603. assert( p->nMem>9 );
  60604. pSub = &p->aMem[9];
  60605. if( pSub->flags&MEM_Blob ){
  60606. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  60607. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  60608. nSub = pSub->n/sizeof(Vdbe*);
  60609. apSub = (SubProgram **)pSub->z;
  60610. }
  60611. for(i=0; i<nSub; i++){
  60612. nRow += apSub[i]->nOp;
  60613. }
  60614. }
  60615. do{
  60616. i = p->pc++;
  60617. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  60618. if( i>=nRow ){
  60619. p->rc = SQLITE_OK;
  60620. rc = SQLITE_DONE;
  60621. }else if( db->u1.isInterrupted ){
  60622. p->rc = SQLITE_INTERRUPT;
  60623. rc = SQLITE_ERROR;
  60624. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  60625. }else{
  60626. char *z;
  60627. Op *pOp;
  60628. if( i<p->nOp ){
  60629. /* The output line number is small enough that we are still in the
  60630. ** main program. */
  60631. pOp = &p->aOp[i];
  60632. }else{
  60633. /* We are currently listing subprograms. Figure out which one and
  60634. ** pick up the appropriate opcode. */
  60635. int j;
  60636. i -= p->nOp;
  60637. for(j=0; i>=apSub[j]->nOp; j++){
  60638. i -= apSub[j]->nOp;
  60639. }
  60640. pOp = &apSub[j]->aOp[i];
  60641. }
  60642. if( p->explain==1 ){
  60643. pMem->flags = MEM_Int;
  60644. pMem->type = SQLITE_INTEGER;
  60645. pMem->u.i = i; /* Program counter */
  60646. pMem++;
  60647. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  60648. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  60649. assert( pMem->z!=0 );
  60650. pMem->n = sqlite3Strlen30(pMem->z);
  60651. pMem->type = SQLITE_TEXT;
  60652. pMem->enc = SQLITE_UTF8;
  60653. pMem++;
  60654. /* When an OP_Program opcode is encounter (the only opcode that has
  60655. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  60656. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  60657. ** has not already been seen.
  60658. */
  60659. if( pOp->p4type==P4_SUBPROGRAM ){
  60660. int nByte = (nSub+1)*sizeof(SubProgram*);
  60661. int j;
  60662. for(j=0; j<nSub; j++){
  60663. if( apSub[j]==pOp->p4.pProgram ) break;
  60664. }
  60665. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  60666. apSub = (SubProgram **)pSub->z;
  60667. apSub[nSub++] = pOp->p4.pProgram;
  60668. pSub->flags |= MEM_Blob;
  60669. pSub->n = nSub*sizeof(SubProgram*);
  60670. }
  60671. }
  60672. }
  60673. pMem->flags = MEM_Int;
  60674. pMem->u.i = pOp->p1; /* P1 */
  60675. pMem->type = SQLITE_INTEGER;
  60676. pMem++;
  60677. pMem->flags = MEM_Int;
  60678. pMem->u.i = pOp->p2; /* P2 */
  60679. pMem->type = SQLITE_INTEGER;
  60680. pMem++;
  60681. pMem->flags = MEM_Int;
  60682. pMem->u.i = pOp->p3; /* P3 */
  60683. pMem->type = SQLITE_INTEGER;
  60684. pMem++;
  60685. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  60686. assert( p->db->mallocFailed );
  60687. return SQLITE_ERROR;
  60688. }
  60689. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  60690. z = displayP4(pOp, pMem->z, 32);
  60691. if( z!=pMem->z ){
  60692. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  60693. }else{
  60694. assert( pMem->z!=0 );
  60695. pMem->n = sqlite3Strlen30(pMem->z);
  60696. pMem->enc = SQLITE_UTF8;
  60697. }
  60698. pMem->type = SQLITE_TEXT;
  60699. pMem++;
  60700. if( p->explain==1 ){
  60701. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  60702. assert( p->db->mallocFailed );
  60703. return SQLITE_ERROR;
  60704. }
  60705. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  60706. pMem->n = 2;
  60707. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  60708. pMem->type = SQLITE_TEXT;
  60709. pMem->enc = SQLITE_UTF8;
  60710. pMem++;
  60711. #ifdef SQLITE_DEBUG
  60712. if( pOp->zComment ){
  60713. pMem->flags = MEM_Str|MEM_Term;
  60714. pMem->z = pOp->zComment;
  60715. pMem->n = sqlite3Strlen30(pMem->z);
  60716. pMem->enc = SQLITE_UTF8;
  60717. pMem->type = SQLITE_TEXT;
  60718. }else
  60719. #endif
  60720. {
  60721. pMem->flags = MEM_Null; /* Comment */
  60722. pMem->type = SQLITE_NULL;
  60723. }
  60724. }
  60725. p->nResColumn = 8 - 4*(p->explain-1);
  60726. p->pResultSet = &p->aMem[1];
  60727. p->rc = SQLITE_OK;
  60728. rc = SQLITE_ROW;
  60729. }
  60730. return rc;
  60731. }
  60732. #endif /* SQLITE_OMIT_EXPLAIN */
  60733. #ifdef SQLITE_DEBUG
  60734. /*
  60735. ** Print the SQL that was used to generate a VDBE program.
  60736. */
  60737. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  60738. int nOp = p->nOp;
  60739. VdbeOp *pOp;
  60740. if( nOp<1 ) return;
  60741. pOp = &p->aOp[0];
  60742. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  60743. const char *z = pOp->p4.z;
  60744. while( sqlite3Isspace(*z) ) z++;
  60745. printf("SQL: [%s]\n", z);
  60746. }
  60747. }
  60748. #endif
  60749. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  60750. /*
  60751. ** Print an IOTRACE message showing SQL content.
  60752. */
  60753. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  60754. int nOp = p->nOp;
  60755. VdbeOp *pOp;
  60756. if( sqlite3IoTrace==0 ) return;
  60757. if( nOp<1 ) return;
  60758. pOp = &p->aOp[0];
  60759. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  60760. int i, j;
  60761. char z[1000];
  60762. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  60763. for(i=0; sqlite3Isspace(z[i]); i++){}
  60764. for(j=0; z[i]; i++){
  60765. if( sqlite3Isspace(z[i]) ){
  60766. if( z[i-1]!=' ' ){
  60767. z[j++] = ' ';
  60768. }
  60769. }else{
  60770. z[j++] = z[i];
  60771. }
  60772. }
  60773. z[j] = 0;
  60774. sqlite3IoTrace("SQL %s\n", z);
  60775. }
  60776. }
  60777. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  60778. /*
  60779. ** Allocate space from a fixed size buffer and return a pointer to
  60780. ** that space. If insufficient space is available, return NULL.
  60781. **
  60782. ** The pBuf parameter is the initial value of a pointer which will
  60783. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  60784. ** NULL, it means that memory space has already been allocated and that
  60785. ** this routine should not allocate any new memory. When pBuf is not
  60786. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  60787. ** is NULL.
  60788. **
  60789. ** nByte is the number of bytes of space needed.
  60790. **
  60791. ** *ppFrom points to available space and pEnd points to the end of the
  60792. ** available space. When space is allocated, *ppFrom is advanced past
  60793. ** the end of the allocated space.
  60794. **
  60795. ** *pnByte is a counter of the number of bytes of space that have failed
  60796. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  60797. ** request, then increment *pnByte by the amount of the request.
  60798. */
  60799. static void *allocSpace(
  60800. void *pBuf, /* Where return pointer will be stored */
  60801. int nByte, /* Number of bytes to allocate */
  60802. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  60803. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  60804. int *pnByte /* If allocation cannot be made, increment *pnByte */
  60805. ){
  60806. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  60807. if( pBuf ) return pBuf;
  60808. nByte = ROUND8(nByte);
  60809. if( &(*ppFrom)[nByte] <= pEnd ){
  60810. pBuf = (void*)*ppFrom;
  60811. *ppFrom += nByte;
  60812. }else{
  60813. *pnByte += nByte;
  60814. }
  60815. return pBuf;
  60816. }
  60817. /*
  60818. ** Rewind the VDBE back to the beginning in preparation for
  60819. ** running it.
  60820. */
  60821. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  60822. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  60823. int i;
  60824. #endif
  60825. assert( p!=0 );
  60826. assert( p->magic==VDBE_MAGIC_INIT );
  60827. /* There should be at least one opcode.
  60828. */
  60829. assert( p->nOp>0 );
  60830. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  60831. p->magic = VDBE_MAGIC_RUN;
  60832. #ifdef SQLITE_DEBUG
  60833. for(i=1; i<p->nMem; i++){
  60834. assert( p->aMem[i].db==p->db );
  60835. }
  60836. #endif
  60837. p->pc = -1;
  60838. p->rc = SQLITE_OK;
  60839. p->errorAction = OE_Abort;
  60840. p->magic = VDBE_MAGIC_RUN;
  60841. p->nChange = 0;
  60842. p->cacheCtr = 1;
  60843. p->minWriteFileFormat = 255;
  60844. p->iStatement = 0;
  60845. p->nFkConstraint = 0;
  60846. #ifdef VDBE_PROFILE
  60847. for(i=0; i<p->nOp; i++){
  60848. p->aOp[i].cnt = 0;
  60849. p->aOp[i].cycles = 0;
  60850. }
  60851. #endif
  60852. }
  60853. /*
  60854. ** Prepare a virtual machine for execution for the first time after
  60855. ** creating the virtual machine. This involves things such
  60856. ** as allocating stack space and initializing the program counter.
  60857. ** After the VDBE has be prepped, it can be executed by one or more
  60858. ** calls to sqlite3VdbeExec().
  60859. **
  60860. ** This function may be called exact once on a each virtual machine.
  60861. ** After this routine is called the VM has been "packaged" and is ready
  60862. ** to run. After this routine is called, futher calls to
  60863. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  60864. ** the Vdbe from the Parse object that helped generate it so that the
  60865. ** the Vdbe becomes an independent entity and the Parse object can be
  60866. ** destroyed.
  60867. **
  60868. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  60869. ** to its initial state after it has been run.
  60870. */
  60871. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  60872. Vdbe *p, /* The VDBE */
  60873. Parse *pParse /* Parsing context */
  60874. ){
  60875. sqlite3 *db; /* The database connection */
  60876. int nVar; /* Number of parameters */
  60877. int nMem; /* Number of VM memory registers */
  60878. int nCursor; /* Number of cursors required */
  60879. int nArg; /* Number of arguments in subprograms */
  60880. int nOnce; /* Number of OP_Once instructions */
  60881. int n; /* Loop counter */
  60882. u8 *zCsr; /* Memory available for allocation */
  60883. u8 *zEnd; /* First byte past allocated memory */
  60884. int nByte; /* How much extra memory is needed */
  60885. assert( p!=0 );
  60886. assert( p->nOp>0 );
  60887. assert( pParse!=0 );
  60888. assert( p->magic==VDBE_MAGIC_INIT );
  60889. db = p->db;
  60890. assert( db->mallocFailed==0 );
  60891. nVar = pParse->nVar;
  60892. nMem = pParse->nMem;
  60893. nCursor = pParse->nTab;
  60894. nArg = pParse->nMaxArg;
  60895. nOnce = pParse->nOnce;
  60896. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  60897. /* For each cursor required, also allocate a memory cell. Memory
  60898. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  60899. ** the vdbe program. Instead they are used to allocate space for
  60900. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  60901. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  60902. ** stores the blob of memory associated with cursor 1, etc.
  60903. **
  60904. ** See also: allocateCursor().
  60905. */
  60906. nMem += nCursor;
  60907. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  60908. ** an array to marshal SQL function arguments in.
  60909. */
  60910. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  60911. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  60912. resolveP2Values(p, &nArg);
  60913. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  60914. if( pParse->explain && nMem<10 ){
  60915. nMem = 10;
  60916. }
  60917. memset(zCsr, 0, zEnd-zCsr);
  60918. zCsr += (zCsr - (u8*)0)&7;
  60919. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  60920. p->expired = 0;
  60921. /* Memory for registers, parameters, cursor, etc, is allocated in two
  60922. ** passes. On the first pass, we try to reuse unused space at the
  60923. ** end of the opcode array. If we are unable to satisfy all memory
  60924. ** requirements by reusing the opcode array tail, then the second
  60925. ** pass will fill in the rest using a fresh allocation.
  60926. **
  60927. ** This two-pass approach that reuses as much memory as possible from
  60928. ** the leftover space at the end of the opcode array can significantly
  60929. ** reduce the amount of memory held by a prepared statement.
  60930. */
  60931. do {
  60932. nByte = 0;
  60933. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  60934. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  60935. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  60936. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  60937. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  60938. &zCsr, zEnd, &nByte);
  60939. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  60940. if( nByte ){
  60941. p->pFree = sqlite3DbMallocZero(db, nByte);
  60942. }
  60943. zCsr = p->pFree;
  60944. zEnd = &zCsr[nByte];
  60945. }while( nByte && !db->mallocFailed );
  60946. p->nCursor = nCursor;
  60947. p->nOnceFlag = nOnce;
  60948. if( p->aVar ){
  60949. p->nVar = (ynVar)nVar;
  60950. for(n=0; n<nVar; n++){
  60951. p->aVar[n].flags = MEM_Null;
  60952. p->aVar[n].db = db;
  60953. }
  60954. }
  60955. if( p->azVar ){
  60956. p->nzVar = pParse->nzVar;
  60957. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  60958. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  60959. }
  60960. if( p->aMem ){
  60961. p->aMem--; /* aMem[] goes from 1..nMem */
  60962. p->nMem = nMem; /* not from 0..nMem-1 */
  60963. for(n=1; n<=nMem; n++){
  60964. p->aMem[n].flags = MEM_Invalid;
  60965. p->aMem[n].db = db;
  60966. }
  60967. }
  60968. p->explain = pParse->explain;
  60969. sqlite3VdbeRewind(p);
  60970. }
  60971. /*
  60972. ** Close a VDBE cursor and release all the resources that cursor
  60973. ** happens to hold.
  60974. */
  60975. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  60976. if( pCx==0 ){
  60977. return;
  60978. }
  60979. sqlite3VdbeSorterClose(p->db, pCx);
  60980. if( pCx->pBt ){
  60981. sqlite3BtreeClose(pCx->pBt);
  60982. /* The pCx->pCursor will be close automatically, if it exists, by
  60983. ** the call above. */
  60984. }else if( pCx->pCursor ){
  60985. sqlite3BtreeCloseCursor(pCx->pCursor);
  60986. }
  60987. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60988. if( pCx->pVtabCursor ){
  60989. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  60990. const sqlite3_module *pModule = pCx->pModule;
  60991. p->inVtabMethod = 1;
  60992. pModule->xClose(pVtabCursor);
  60993. p->inVtabMethod = 0;
  60994. }
  60995. #endif
  60996. }
  60997. /*
  60998. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  60999. ** is used, for example, when a trigger sub-program is halted to restore
  61000. ** control to the main program.
  61001. */
  61002. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  61003. Vdbe *v = pFrame->v;
  61004. v->aOnceFlag = pFrame->aOnceFlag;
  61005. v->nOnceFlag = pFrame->nOnceFlag;
  61006. v->aOp = pFrame->aOp;
  61007. v->nOp = pFrame->nOp;
  61008. v->aMem = pFrame->aMem;
  61009. v->nMem = pFrame->nMem;
  61010. v->apCsr = pFrame->apCsr;
  61011. v->nCursor = pFrame->nCursor;
  61012. v->db->lastRowid = pFrame->lastRowid;
  61013. v->nChange = pFrame->nChange;
  61014. return pFrame->pc;
  61015. }
  61016. /*
  61017. ** Close all cursors.
  61018. **
  61019. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  61020. ** cell array. This is necessary as the memory cell array may contain
  61021. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  61022. ** open cursors.
  61023. */
  61024. static void closeAllCursors(Vdbe *p){
  61025. if( p->pFrame ){
  61026. VdbeFrame *pFrame;
  61027. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  61028. sqlite3VdbeFrameRestore(pFrame);
  61029. }
  61030. p->pFrame = 0;
  61031. p->nFrame = 0;
  61032. if( p->apCsr ){
  61033. int i;
  61034. for(i=0; i<p->nCursor; i++){
  61035. VdbeCursor *pC = p->apCsr[i];
  61036. if( pC ){
  61037. sqlite3VdbeFreeCursor(p, pC);
  61038. p->apCsr[i] = 0;
  61039. }
  61040. }
  61041. }
  61042. if( p->aMem ){
  61043. releaseMemArray(&p->aMem[1], p->nMem);
  61044. }
  61045. while( p->pDelFrame ){
  61046. VdbeFrame *pDel = p->pDelFrame;
  61047. p->pDelFrame = pDel->pParent;
  61048. sqlite3VdbeFrameDelete(pDel);
  61049. }
  61050. /* Delete any auxdata allocations made by the VM */
  61051. sqlite3VdbeDeleteAuxData(p, -1, 0);
  61052. assert( p->pAuxData==0 );
  61053. }
  61054. /*
  61055. ** Clean up the VM after execution.
  61056. **
  61057. ** This routine will automatically close any cursors, lists, and/or
  61058. ** sorters that were left open. It also deletes the values of
  61059. ** variables in the aVar[] array.
  61060. */
  61061. static void Cleanup(Vdbe *p){
  61062. sqlite3 *db = p->db;
  61063. #ifdef SQLITE_DEBUG
  61064. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  61065. ** Vdbe.aMem[] arrays have already been cleaned up. */
  61066. int i;
  61067. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  61068. if( p->aMem ){
  61069. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  61070. }
  61071. #endif
  61072. sqlite3DbFree(db, p->zErrMsg);
  61073. p->zErrMsg = 0;
  61074. p->pResultSet = 0;
  61075. }
  61076. /*
  61077. ** Set the number of result columns that will be returned by this SQL
  61078. ** statement. This is now set at compile time, rather than during
  61079. ** execution of the vdbe program so that sqlite3_column_count() can
  61080. ** be called on an SQL statement before sqlite3_step().
  61081. */
  61082. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  61083. Mem *pColName;
  61084. int n;
  61085. sqlite3 *db = p->db;
  61086. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61087. sqlite3DbFree(db, p->aColName);
  61088. n = nResColumn*COLNAME_N;
  61089. p->nResColumn = (u16)nResColumn;
  61090. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  61091. if( p->aColName==0 ) return;
  61092. while( n-- > 0 ){
  61093. pColName->flags = MEM_Null;
  61094. pColName->db = p->db;
  61095. pColName++;
  61096. }
  61097. }
  61098. /*
  61099. ** Set the name of the idx'th column to be returned by the SQL statement.
  61100. ** zName must be a pointer to a nul terminated string.
  61101. **
  61102. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  61103. **
  61104. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  61105. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  61106. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  61107. */
  61108. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  61109. Vdbe *p, /* Vdbe being configured */
  61110. int idx, /* Index of column zName applies to */
  61111. int var, /* One of the COLNAME_* constants */
  61112. const char *zName, /* Pointer to buffer containing name */
  61113. void (*xDel)(void*) /* Memory management strategy for zName */
  61114. ){
  61115. int rc;
  61116. Mem *pColName;
  61117. assert( idx<p->nResColumn );
  61118. assert( var<COLNAME_N );
  61119. if( p->db->mallocFailed ){
  61120. assert( !zName || xDel!=SQLITE_DYNAMIC );
  61121. return SQLITE_NOMEM;
  61122. }
  61123. assert( p->aColName!=0 );
  61124. pColName = &(p->aColName[idx+var*p->nResColumn]);
  61125. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  61126. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  61127. return rc;
  61128. }
  61129. /*
  61130. ** A read or write transaction may or may not be active on database handle
  61131. ** db. If a transaction is active, commit it. If there is a
  61132. ** write-transaction spanning more than one database file, this routine
  61133. ** takes care of the master journal trickery.
  61134. */
  61135. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  61136. int i;
  61137. int nTrans = 0; /* Number of databases with an active write-transaction */
  61138. int rc = SQLITE_OK;
  61139. int needXcommit = 0;
  61140. #ifdef SQLITE_OMIT_VIRTUALTABLE
  61141. /* With this option, sqlite3VtabSync() is defined to be simply
  61142. ** SQLITE_OK so p is not used.
  61143. */
  61144. UNUSED_PARAMETER(p);
  61145. #endif
  61146. /* Before doing anything else, call the xSync() callback for any
  61147. ** virtual module tables written in this transaction. This has to
  61148. ** be done before determining whether a master journal file is
  61149. ** required, as an xSync() callback may add an attached database
  61150. ** to the transaction.
  61151. */
  61152. rc = sqlite3VtabSync(db, p);
  61153. /* This loop determines (a) if the commit hook should be invoked and
  61154. ** (b) how many database files have open write transactions, not
  61155. ** including the temp database. (b) is important because if more than
  61156. ** one database file has an open write transaction, a master journal
  61157. ** file is required for an atomic commit.
  61158. */
  61159. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61160. Btree *pBt = db->aDb[i].pBt;
  61161. if( sqlite3BtreeIsInTrans(pBt) ){
  61162. needXcommit = 1;
  61163. if( i!=1 ) nTrans++;
  61164. sqlite3BtreeEnter(pBt);
  61165. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  61166. sqlite3BtreeLeave(pBt);
  61167. }
  61168. }
  61169. if( rc!=SQLITE_OK ){
  61170. return rc;
  61171. }
  61172. /* If there are any write-transactions at all, invoke the commit hook */
  61173. if( needXcommit && db->xCommitCallback ){
  61174. rc = db->xCommitCallback(db->pCommitArg);
  61175. if( rc ){
  61176. return SQLITE_CONSTRAINT_COMMITHOOK;
  61177. }
  61178. }
  61179. /* The simple case - no more than one database file (not counting the
  61180. ** TEMP database) has a transaction active. There is no need for the
  61181. ** master-journal.
  61182. **
  61183. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  61184. ** string, it means the main database is :memory: or a temp file. In
  61185. ** that case we do not support atomic multi-file commits, so use the
  61186. ** simple case then too.
  61187. */
  61188. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  61189. || nTrans<=1
  61190. ){
  61191. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61192. Btree *pBt = db->aDb[i].pBt;
  61193. if( pBt ){
  61194. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  61195. }
  61196. }
  61197. /* Do the commit only if all databases successfully complete phase 1.
  61198. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  61199. ** IO error while deleting or truncating a journal file. It is unlikely,
  61200. ** but could happen. In this case abandon processing and return the error.
  61201. */
  61202. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61203. Btree *pBt = db->aDb[i].pBt;
  61204. if( pBt ){
  61205. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  61206. }
  61207. }
  61208. if( rc==SQLITE_OK ){
  61209. sqlite3VtabCommit(db);
  61210. }
  61211. }
  61212. /* The complex case - There is a multi-file write-transaction active.
  61213. ** This requires a master journal file to ensure the transaction is
  61214. ** committed atomicly.
  61215. */
  61216. #ifndef SQLITE_OMIT_DISKIO
  61217. else{
  61218. sqlite3_vfs *pVfs = db->pVfs;
  61219. int needSync = 0;
  61220. char *zMaster = 0; /* File-name for the master journal */
  61221. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  61222. sqlite3_file *pMaster = 0;
  61223. i64 offset = 0;
  61224. int res;
  61225. int retryCount = 0;
  61226. int nMainFile;
  61227. /* Select a master journal file name */
  61228. nMainFile = sqlite3Strlen30(zMainFile);
  61229. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  61230. if( zMaster==0 ) return SQLITE_NOMEM;
  61231. do {
  61232. u32 iRandom;
  61233. if( retryCount ){
  61234. if( retryCount>100 ){
  61235. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  61236. sqlite3OsDelete(pVfs, zMaster, 0);
  61237. break;
  61238. }else if( retryCount==1 ){
  61239. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  61240. }
  61241. }
  61242. retryCount++;
  61243. sqlite3_randomness(sizeof(iRandom), &iRandom);
  61244. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  61245. (iRandom>>8)&0xffffff, iRandom&0xff);
  61246. /* The antipenultimate character of the master journal name must
  61247. ** be "9" to avoid name collisions when using 8+3 filenames. */
  61248. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  61249. sqlite3FileSuffix3(zMainFile, zMaster);
  61250. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  61251. }while( rc==SQLITE_OK && res );
  61252. if( rc==SQLITE_OK ){
  61253. /* Open the master journal. */
  61254. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  61255. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  61256. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  61257. );
  61258. }
  61259. if( rc!=SQLITE_OK ){
  61260. sqlite3DbFree(db, zMaster);
  61261. return rc;
  61262. }
  61263. /* Write the name of each database file in the transaction into the new
  61264. ** master journal file. If an error occurs at this point close
  61265. ** and delete the master journal file. All the individual journal files
  61266. ** still have 'null' as the master journal pointer, so they will roll
  61267. ** back independently if a failure occurs.
  61268. */
  61269. for(i=0; i<db->nDb; i++){
  61270. Btree *pBt = db->aDb[i].pBt;
  61271. if( sqlite3BtreeIsInTrans(pBt) ){
  61272. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  61273. if( zFile==0 ){
  61274. continue; /* Ignore TEMP and :memory: databases */
  61275. }
  61276. assert( zFile[0]!=0 );
  61277. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  61278. needSync = 1;
  61279. }
  61280. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  61281. offset += sqlite3Strlen30(zFile)+1;
  61282. if( rc!=SQLITE_OK ){
  61283. sqlite3OsCloseFree(pMaster);
  61284. sqlite3OsDelete(pVfs, zMaster, 0);
  61285. sqlite3DbFree(db, zMaster);
  61286. return rc;
  61287. }
  61288. }
  61289. }
  61290. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  61291. ** flag is set this is not required.
  61292. */
  61293. if( needSync
  61294. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  61295. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  61296. ){
  61297. sqlite3OsCloseFree(pMaster);
  61298. sqlite3OsDelete(pVfs, zMaster, 0);
  61299. sqlite3DbFree(db, zMaster);
  61300. return rc;
  61301. }
  61302. /* Sync all the db files involved in the transaction. The same call
  61303. ** sets the master journal pointer in each individual journal. If
  61304. ** an error occurs here, do not delete the master journal file.
  61305. **
  61306. ** If the error occurs during the first call to
  61307. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  61308. ** master journal file will be orphaned. But we cannot delete it,
  61309. ** in case the master journal file name was written into the journal
  61310. ** file before the failure occurred.
  61311. */
  61312. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61313. Btree *pBt = db->aDb[i].pBt;
  61314. if( pBt ){
  61315. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  61316. }
  61317. }
  61318. sqlite3OsCloseFree(pMaster);
  61319. assert( rc!=SQLITE_BUSY );
  61320. if( rc!=SQLITE_OK ){
  61321. sqlite3DbFree(db, zMaster);
  61322. return rc;
  61323. }
  61324. /* Delete the master journal file. This commits the transaction. After
  61325. ** doing this the directory is synced again before any individual
  61326. ** transaction files are deleted.
  61327. */
  61328. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  61329. sqlite3DbFree(db, zMaster);
  61330. zMaster = 0;
  61331. if( rc ){
  61332. return rc;
  61333. }
  61334. /* All files and directories have already been synced, so the following
  61335. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  61336. ** deleting or truncating journals. If something goes wrong while
  61337. ** this is happening we don't really care. The integrity of the
  61338. ** transaction is already guaranteed, but some stray 'cold' journals
  61339. ** may be lying around. Returning an error code won't help matters.
  61340. */
  61341. disable_simulated_io_errors();
  61342. sqlite3BeginBenignMalloc();
  61343. for(i=0; i<db->nDb; i++){
  61344. Btree *pBt = db->aDb[i].pBt;
  61345. if( pBt ){
  61346. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  61347. }
  61348. }
  61349. sqlite3EndBenignMalloc();
  61350. enable_simulated_io_errors();
  61351. sqlite3VtabCommit(db);
  61352. }
  61353. #endif
  61354. return rc;
  61355. }
  61356. /*
  61357. ** This routine checks that the sqlite3.nVdbeActive count variable
  61358. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  61359. ** currently active. An assertion fails if the two counts do not match.
  61360. ** This is an internal self-check only - it is not an essential processing
  61361. ** step.
  61362. **
  61363. ** This is a no-op if NDEBUG is defined.
  61364. */
  61365. #ifndef NDEBUG
  61366. static void checkActiveVdbeCnt(sqlite3 *db){
  61367. Vdbe *p;
  61368. int cnt = 0;
  61369. int nWrite = 0;
  61370. int nRead = 0;
  61371. p = db->pVdbe;
  61372. while( p ){
  61373. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  61374. cnt++;
  61375. if( p->readOnly==0 ) nWrite++;
  61376. if( p->bIsReader ) nRead++;
  61377. }
  61378. p = p->pNext;
  61379. }
  61380. assert( cnt==db->nVdbeActive );
  61381. assert( nWrite==db->nVdbeWrite );
  61382. assert( nRead==db->nVdbeRead );
  61383. }
  61384. #else
  61385. #define checkActiveVdbeCnt(x)
  61386. #endif
  61387. /*
  61388. ** If the Vdbe passed as the first argument opened a statement-transaction,
  61389. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  61390. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  61391. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  61392. ** statement transaction is committed.
  61393. **
  61394. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  61395. ** Otherwise SQLITE_OK.
  61396. */
  61397. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  61398. sqlite3 *const db = p->db;
  61399. int rc = SQLITE_OK;
  61400. /* If p->iStatement is greater than zero, then this Vdbe opened a
  61401. ** statement transaction that should be closed here. The only exception
  61402. ** is that an IO error may have occurred, causing an emergency rollback.
  61403. ** In this case (db->nStatement==0), and there is nothing to do.
  61404. */
  61405. if( db->nStatement && p->iStatement ){
  61406. int i;
  61407. const int iSavepoint = p->iStatement-1;
  61408. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  61409. assert( db->nStatement>0 );
  61410. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  61411. for(i=0; i<db->nDb; i++){
  61412. int rc2 = SQLITE_OK;
  61413. Btree *pBt = db->aDb[i].pBt;
  61414. if( pBt ){
  61415. if( eOp==SAVEPOINT_ROLLBACK ){
  61416. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  61417. }
  61418. if( rc2==SQLITE_OK ){
  61419. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  61420. }
  61421. if( rc==SQLITE_OK ){
  61422. rc = rc2;
  61423. }
  61424. }
  61425. }
  61426. db->nStatement--;
  61427. p->iStatement = 0;
  61428. if( rc==SQLITE_OK ){
  61429. if( eOp==SAVEPOINT_ROLLBACK ){
  61430. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  61431. }
  61432. if( rc==SQLITE_OK ){
  61433. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  61434. }
  61435. }
  61436. /* If the statement transaction is being rolled back, also restore the
  61437. ** database handles deferred constraint counter to the value it had when
  61438. ** the statement transaction was opened. */
  61439. if( eOp==SAVEPOINT_ROLLBACK ){
  61440. db->nDeferredCons = p->nStmtDefCons;
  61441. db->nDeferredImmCons = p->nStmtDefImmCons;
  61442. }
  61443. }
  61444. return rc;
  61445. }
  61446. /*
  61447. ** This function is called when a transaction opened by the database
  61448. ** handle associated with the VM passed as an argument is about to be
  61449. ** committed. If there are outstanding deferred foreign key constraint
  61450. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  61451. **
  61452. ** If there are outstanding FK violations and this function returns
  61453. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  61454. ** and write an error message to it. Then return SQLITE_ERROR.
  61455. */
  61456. #ifndef SQLITE_OMIT_FOREIGN_KEY
  61457. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  61458. sqlite3 *db = p->db;
  61459. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  61460. || (!deferred && p->nFkConstraint>0)
  61461. ){
  61462. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61463. p->errorAction = OE_Abort;
  61464. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  61465. return SQLITE_ERROR;
  61466. }
  61467. return SQLITE_OK;
  61468. }
  61469. #endif
  61470. /*
  61471. ** This routine is called the when a VDBE tries to halt. If the VDBE
  61472. ** has made changes and is in autocommit mode, then commit those
  61473. ** changes. If a rollback is needed, then do the rollback.
  61474. **
  61475. ** This routine is the only way to move the state of a VM from
  61476. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  61477. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  61478. **
  61479. ** Return an error code. If the commit could not complete because of
  61480. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  61481. ** means the close did not happen and needs to be repeated.
  61482. */
  61483. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  61484. int rc; /* Used to store transient return codes */
  61485. sqlite3 *db = p->db;
  61486. /* This function contains the logic that determines if a statement or
  61487. ** transaction will be committed or rolled back as a result of the
  61488. ** execution of this virtual machine.
  61489. **
  61490. ** If any of the following errors occur:
  61491. **
  61492. ** SQLITE_NOMEM
  61493. ** SQLITE_IOERR
  61494. ** SQLITE_FULL
  61495. ** SQLITE_INTERRUPT
  61496. **
  61497. ** Then the internal cache might have been left in an inconsistent
  61498. ** state. We need to rollback the statement transaction, if there is
  61499. ** one, or the complete transaction if there is no statement transaction.
  61500. */
  61501. if( p->db->mallocFailed ){
  61502. p->rc = SQLITE_NOMEM;
  61503. }
  61504. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  61505. closeAllCursors(p);
  61506. if( p->magic!=VDBE_MAGIC_RUN ){
  61507. return SQLITE_OK;
  61508. }
  61509. checkActiveVdbeCnt(db);
  61510. /* No commit or rollback needed if the program never started or if the
  61511. ** SQL statement does not read or write a database file. */
  61512. if( p->pc>=0 && p->bIsReader ){
  61513. int mrc; /* Primary error code from p->rc */
  61514. int eStatementOp = 0;
  61515. int isSpecialError; /* Set to true if a 'special' error */
  61516. /* Lock all btrees used by the statement */
  61517. sqlite3VdbeEnter(p);
  61518. /* Check for one of the special errors */
  61519. mrc = p->rc & 0xff;
  61520. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  61521. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  61522. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  61523. if( isSpecialError ){
  61524. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  61525. ** no rollback is necessary. Otherwise, at least a savepoint
  61526. ** transaction must be rolled back to restore the database to a
  61527. ** consistent state.
  61528. **
  61529. ** Even if the statement is read-only, it is important to perform
  61530. ** a statement or transaction rollback operation. If the error
  61531. ** occurred while writing to the journal, sub-journal or database
  61532. ** file as part of an effort to free up cache space (see function
  61533. ** pagerStress() in pager.c), the rollback is required to restore
  61534. ** the pager to a consistent state.
  61535. */
  61536. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  61537. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  61538. eStatementOp = SAVEPOINT_ROLLBACK;
  61539. }else{
  61540. /* We are forced to roll back the active transaction. Before doing
  61541. ** so, abort any other statements this handle currently has active.
  61542. */
  61543. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61544. sqlite3CloseSavepoints(db);
  61545. db->autoCommit = 1;
  61546. }
  61547. }
  61548. }
  61549. /* Check for immediate foreign key violations. */
  61550. if( p->rc==SQLITE_OK ){
  61551. sqlite3VdbeCheckFk(p, 0);
  61552. }
  61553. /* If the auto-commit flag is set and this is the only active writer
  61554. ** VM, then we do either a commit or rollback of the current transaction.
  61555. **
  61556. ** Note: This block also runs if one of the special errors handled
  61557. ** above has occurred.
  61558. */
  61559. if( !sqlite3VtabInSync(db)
  61560. && db->autoCommit
  61561. && db->nVdbeWrite==(p->readOnly==0)
  61562. ){
  61563. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  61564. rc = sqlite3VdbeCheckFk(p, 1);
  61565. if( rc!=SQLITE_OK ){
  61566. if( NEVER(p->readOnly) ){
  61567. sqlite3VdbeLeave(p);
  61568. return SQLITE_ERROR;
  61569. }
  61570. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61571. }else{
  61572. /* The auto-commit flag is true, the vdbe program was successful
  61573. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  61574. ** key constraints to hold up the transaction. This means a commit
  61575. ** is required. */
  61576. rc = vdbeCommit(db, p);
  61577. }
  61578. if( rc==SQLITE_BUSY && p->readOnly ){
  61579. sqlite3VdbeLeave(p);
  61580. return SQLITE_BUSY;
  61581. }else if( rc!=SQLITE_OK ){
  61582. p->rc = rc;
  61583. sqlite3RollbackAll(db, SQLITE_OK);
  61584. }else{
  61585. db->nDeferredCons = 0;
  61586. db->nDeferredImmCons = 0;
  61587. db->flags &= ~SQLITE_DeferFKs;
  61588. sqlite3CommitInternalChanges(db);
  61589. }
  61590. }else{
  61591. sqlite3RollbackAll(db, SQLITE_OK);
  61592. }
  61593. db->nStatement = 0;
  61594. }else if( eStatementOp==0 ){
  61595. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  61596. eStatementOp = SAVEPOINT_RELEASE;
  61597. }else if( p->errorAction==OE_Abort ){
  61598. eStatementOp = SAVEPOINT_ROLLBACK;
  61599. }else{
  61600. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61601. sqlite3CloseSavepoints(db);
  61602. db->autoCommit = 1;
  61603. }
  61604. }
  61605. /* If eStatementOp is non-zero, then a statement transaction needs to
  61606. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  61607. ** do so. If this operation returns an error, and the current statement
  61608. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  61609. ** current statement error code.
  61610. */
  61611. if( eStatementOp ){
  61612. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  61613. if( rc ){
  61614. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  61615. p->rc = rc;
  61616. sqlite3DbFree(db, p->zErrMsg);
  61617. p->zErrMsg = 0;
  61618. }
  61619. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61620. sqlite3CloseSavepoints(db);
  61621. db->autoCommit = 1;
  61622. }
  61623. }
  61624. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  61625. ** has been rolled back, update the database connection change-counter.
  61626. */
  61627. if( p->changeCntOn ){
  61628. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  61629. sqlite3VdbeSetChanges(db, p->nChange);
  61630. }else{
  61631. sqlite3VdbeSetChanges(db, 0);
  61632. }
  61633. p->nChange = 0;
  61634. }
  61635. /* Release the locks */
  61636. sqlite3VdbeLeave(p);
  61637. }
  61638. /* We have successfully halted and closed the VM. Record this fact. */
  61639. if( p->pc>=0 ){
  61640. db->nVdbeActive--;
  61641. if( !p->readOnly ) db->nVdbeWrite--;
  61642. if( p->bIsReader ) db->nVdbeRead--;
  61643. assert( db->nVdbeActive>=db->nVdbeRead );
  61644. assert( db->nVdbeRead>=db->nVdbeWrite );
  61645. assert( db->nVdbeWrite>=0 );
  61646. }
  61647. p->magic = VDBE_MAGIC_HALT;
  61648. checkActiveVdbeCnt(db);
  61649. if( p->db->mallocFailed ){
  61650. p->rc = SQLITE_NOMEM;
  61651. }
  61652. /* If the auto-commit flag is set to true, then any locks that were held
  61653. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  61654. ** to invoke any required unlock-notify callbacks.
  61655. */
  61656. if( db->autoCommit ){
  61657. sqlite3ConnectionUnlocked(db);
  61658. }
  61659. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  61660. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  61661. }
  61662. /*
  61663. ** Each VDBE holds the result of the most recent sqlite3_step() call
  61664. ** in p->rc. This routine sets that result back to SQLITE_OK.
  61665. */
  61666. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  61667. p->rc = SQLITE_OK;
  61668. }
  61669. /*
  61670. ** Copy the error code and error message belonging to the VDBE passed
  61671. ** as the first argument to its database handle (so that they will be
  61672. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  61673. **
  61674. ** This function does not clear the VDBE error code or message, just
  61675. ** copies them to the database handle.
  61676. */
  61677. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  61678. sqlite3 *db = p->db;
  61679. int rc = p->rc;
  61680. if( p->zErrMsg ){
  61681. u8 mallocFailed = db->mallocFailed;
  61682. sqlite3BeginBenignMalloc();
  61683. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61684. sqlite3EndBenignMalloc();
  61685. db->mallocFailed = mallocFailed;
  61686. db->errCode = rc;
  61687. }else{
  61688. sqlite3Error(db, rc, 0);
  61689. }
  61690. return rc;
  61691. }
  61692. #ifdef SQLITE_ENABLE_SQLLOG
  61693. /*
  61694. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  61695. ** invoke it.
  61696. */
  61697. static void vdbeInvokeSqllog(Vdbe *v){
  61698. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  61699. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  61700. assert( v->db->init.busy==0 );
  61701. if( zExpanded ){
  61702. sqlite3GlobalConfig.xSqllog(
  61703. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  61704. );
  61705. sqlite3DbFree(v->db, zExpanded);
  61706. }
  61707. }
  61708. }
  61709. #else
  61710. # define vdbeInvokeSqllog(x)
  61711. #endif
  61712. /*
  61713. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  61714. ** Write any error messages into *pzErrMsg. Return the result code.
  61715. **
  61716. ** After this routine is run, the VDBE should be ready to be executed
  61717. ** again.
  61718. **
  61719. ** To look at it another way, this routine resets the state of the
  61720. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  61721. ** VDBE_MAGIC_INIT.
  61722. */
  61723. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  61724. sqlite3 *db;
  61725. db = p->db;
  61726. /* If the VM did not run to completion or if it encountered an
  61727. ** error, then it might not have been halted properly. So halt
  61728. ** it now.
  61729. */
  61730. sqlite3VdbeHalt(p);
  61731. /* If the VDBE has be run even partially, then transfer the error code
  61732. ** and error message from the VDBE into the main database structure. But
  61733. ** if the VDBE has just been set to run but has not actually executed any
  61734. ** instructions yet, leave the main database error information unchanged.
  61735. */
  61736. if( p->pc>=0 ){
  61737. vdbeInvokeSqllog(p);
  61738. sqlite3VdbeTransferError(p);
  61739. sqlite3DbFree(db, p->zErrMsg);
  61740. p->zErrMsg = 0;
  61741. if( p->runOnlyOnce ) p->expired = 1;
  61742. }else if( p->rc && p->expired ){
  61743. /* The expired flag was set on the VDBE before the first call
  61744. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  61745. ** called), set the database error in this case as well.
  61746. */
  61747. sqlite3Error(db, p->rc, 0);
  61748. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61749. sqlite3DbFree(db, p->zErrMsg);
  61750. p->zErrMsg = 0;
  61751. }
  61752. /* Reclaim all memory used by the VDBE
  61753. */
  61754. Cleanup(p);
  61755. /* Save profiling information from this VDBE run.
  61756. */
  61757. #ifdef VDBE_PROFILE
  61758. {
  61759. FILE *out = fopen("vdbe_profile.out", "a");
  61760. if( out ){
  61761. int i;
  61762. fprintf(out, "---- ");
  61763. for(i=0; i<p->nOp; i++){
  61764. fprintf(out, "%02x", p->aOp[i].opcode);
  61765. }
  61766. fprintf(out, "\n");
  61767. for(i=0; i<p->nOp; i++){
  61768. fprintf(out, "%6d %10lld %8lld ",
  61769. p->aOp[i].cnt,
  61770. p->aOp[i].cycles,
  61771. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  61772. );
  61773. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  61774. }
  61775. fclose(out);
  61776. }
  61777. }
  61778. #endif
  61779. p->iCurrentTime = 0;
  61780. p->magic = VDBE_MAGIC_INIT;
  61781. return p->rc & db->errMask;
  61782. }
  61783. /*
  61784. ** Clean up and delete a VDBE after execution. Return an integer which is
  61785. ** the result code. Write any error message text into *pzErrMsg.
  61786. */
  61787. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  61788. int rc = SQLITE_OK;
  61789. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  61790. rc = sqlite3VdbeReset(p);
  61791. assert( (rc & p->db->errMask)==rc );
  61792. }
  61793. sqlite3VdbeDelete(p);
  61794. return rc;
  61795. }
  61796. /*
  61797. ** If parameter iOp is less than zero, then invoke the destructor for
  61798. ** all auxiliary data pointers currently cached by the VM passed as
  61799. ** the first argument.
  61800. **
  61801. ** Or, if iOp is greater than or equal to zero, then the destructor is
  61802. ** only invoked for those auxiliary data pointers created by the user
  61803. ** function invoked by the OP_Function opcode at instruction iOp of
  61804. ** VM pVdbe, and only then if:
  61805. **
  61806. ** * the associated function parameter is the 32nd or later (counting
  61807. ** from left to right), or
  61808. **
  61809. ** * the corresponding bit in argument mask is clear (where the first
  61810. ** function parameter corrsponds to bit 0 etc.).
  61811. */
  61812. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  61813. AuxData **pp = &pVdbe->pAuxData;
  61814. while( *pp ){
  61815. AuxData *pAux = *pp;
  61816. if( (iOp<0)
  61817. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
  61818. ){
  61819. if( pAux->xDelete ){
  61820. pAux->xDelete(pAux->pAux);
  61821. }
  61822. *pp = pAux->pNext;
  61823. sqlite3DbFree(pVdbe->db, pAux);
  61824. }else{
  61825. pp= &pAux->pNext;
  61826. }
  61827. }
  61828. }
  61829. /*
  61830. ** Free all memory associated with the Vdbe passed as the second argument,
  61831. ** except for object itself, which is preserved.
  61832. **
  61833. ** The difference between this function and sqlite3VdbeDelete() is that
  61834. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  61835. ** the database connection and frees the object itself.
  61836. */
  61837. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  61838. SubProgram *pSub, *pNext;
  61839. int i;
  61840. assert( p->db==0 || p->db==db );
  61841. releaseMemArray(p->aVar, p->nVar);
  61842. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61843. for(pSub=p->pProgram; pSub; pSub=pNext){
  61844. pNext = pSub->pNext;
  61845. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  61846. sqlite3DbFree(db, pSub);
  61847. }
  61848. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  61849. vdbeFreeOpArray(db, p->aOp, p->nOp);
  61850. sqlite3DbFree(db, p->aLabel);
  61851. sqlite3DbFree(db, p->aColName);
  61852. sqlite3DbFree(db, p->zSql);
  61853. sqlite3DbFree(db, p->pFree);
  61854. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  61855. sqlite3DbFree(db, p->zExplain);
  61856. sqlite3DbFree(db, p->pExplain);
  61857. #endif
  61858. }
  61859. /*
  61860. ** Delete an entire VDBE.
  61861. */
  61862. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  61863. sqlite3 *db;
  61864. if( NEVER(p==0) ) return;
  61865. db = p->db;
  61866. assert( sqlite3_mutex_held(db->mutex) );
  61867. sqlite3VdbeClearObject(db, p);
  61868. if( p->pPrev ){
  61869. p->pPrev->pNext = p->pNext;
  61870. }else{
  61871. assert( db->pVdbe==p );
  61872. db->pVdbe = p->pNext;
  61873. }
  61874. if( p->pNext ){
  61875. p->pNext->pPrev = p->pPrev;
  61876. }
  61877. p->magic = VDBE_MAGIC_DEAD;
  61878. p->db = 0;
  61879. sqlite3DbFree(db, p);
  61880. }
  61881. /*
  61882. ** Make sure the cursor p is ready to read or write the row to which it
  61883. ** was last positioned. Return an error code if an OOM fault or I/O error
  61884. ** prevents us from positioning the cursor to its correct position.
  61885. **
  61886. ** If a MoveTo operation is pending on the given cursor, then do that
  61887. ** MoveTo now. If no move is pending, check to see if the row has been
  61888. ** deleted out from under the cursor and if it has, mark the row as
  61889. ** a NULL row.
  61890. **
  61891. ** If the cursor is already pointing to the correct row and that row has
  61892. ** not been deleted out from under the cursor, then this routine is a no-op.
  61893. */
  61894. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  61895. if( p->deferredMoveto ){
  61896. int res, rc;
  61897. #ifdef SQLITE_TEST
  61898. extern int sqlite3_search_count;
  61899. #endif
  61900. assert( p->isTable );
  61901. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  61902. if( rc ) return rc;
  61903. p->lastRowid = p->movetoTarget;
  61904. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  61905. p->rowidIsValid = 1;
  61906. #ifdef SQLITE_TEST
  61907. sqlite3_search_count++;
  61908. #endif
  61909. p->deferredMoveto = 0;
  61910. p->cacheStatus = CACHE_STALE;
  61911. }else if( ALWAYS(p->pCursor) ){
  61912. int hasMoved;
  61913. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  61914. if( rc ) return rc;
  61915. if( hasMoved ){
  61916. p->cacheStatus = CACHE_STALE;
  61917. p->nullRow = 1;
  61918. }
  61919. }
  61920. return SQLITE_OK;
  61921. }
  61922. /*
  61923. ** The following functions:
  61924. **
  61925. ** sqlite3VdbeSerialType()
  61926. ** sqlite3VdbeSerialTypeLen()
  61927. ** sqlite3VdbeSerialLen()
  61928. ** sqlite3VdbeSerialPut()
  61929. ** sqlite3VdbeSerialGet()
  61930. **
  61931. ** encapsulate the code that serializes values for storage in SQLite
  61932. ** data and index records. Each serialized value consists of a
  61933. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  61934. ** integer, stored as a varint.
  61935. **
  61936. ** In an SQLite index record, the serial type is stored directly before
  61937. ** the blob of data that it corresponds to. In a table record, all serial
  61938. ** types are stored at the start of the record, and the blobs of data at
  61939. ** the end. Hence these functions allow the caller to handle the
  61940. ** serial-type and data blob separately.
  61941. **
  61942. ** The following table describes the various storage classes for data:
  61943. **
  61944. ** serial type bytes of data type
  61945. ** -------------- --------------- ---------------
  61946. ** 0 0 NULL
  61947. ** 1 1 signed integer
  61948. ** 2 2 signed integer
  61949. ** 3 3 signed integer
  61950. ** 4 4 signed integer
  61951. ** 5 6 signed integer
  61952. ** 6 8 signed integer
  61953. ** 7 8 IEEE float
  61954. ** 8 0 Integer constant 0
  61955. ** 9 0 Integer constant 1
  61956. ** 10,11 reserved for expansion
  61957. ** N>=12 and even (N-12)/2 BLOB
  61958. ** N>=13 and odd (N-13)/2 text
  61959. **
  61960. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  61961. ** of SQLite will not understand those serial types.
  61962. */
  61963. /*
  61964. ** Return the serial-type for the value stored in pMem.
  61965. */
  61966. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  61967. int flags = pMem->flags;
  61968. int n;
  61969. if( flags&MEM_Null ){
  61970. return 0;
  61971. }
  61972. if( flags&MEM_Int ){
  61973. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  61974. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  61975. i64 i = pMem->u.i;
  61976. u64 u;
  61977. if( i<0 ){
  61978. if( i<(-MAX_6BYTE) ) return 6;
  61979. /* Previous test prevents: u = -(-9223372036854775808) */
  61980. u = -i;
  61981. }else{
  61982. u = i;
  61983. }
  61984. if( u<=127 ){
  61985. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  61986. }
  61987. if( u<=32767 ) return 2;
  61988. if( u<=8388607 ) return 3;
  61989. if( u<=2147483647 ) return 4;
  61990. if( u<=MAX_6BYTE ) return 5;
  61991. return 6;
  61992. }
  61993. if( flags&MEM_Real ){
  61994. return 7;
  61995. }
  61996. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  61997. n = pMem->n;
  61998. if( flags & MEM_Zero ){
  61999. n += pMem->u.nZero;
  62000. }
  62001. assert( n>=0 );
  62002. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  62003. }
  62004. /*
  62005. ** Return the length of the data corresponding to the supplied serial-type.
  62006. */
  62007. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  62008. if( serial_type>=12 ){
  62009. return (serial_type-12)/2;
  62010. }else{
  62011. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  62012. return aSize[serial_type];
  62013. }
  62014. }
  62015. /*
  62016. ** If we are on an architecture with mixed-endian floating
  62017. ** points (ex: ARM7) then swap the lower 4 bytes with the
  62018. ** upper 4 bytes. Return the result.
  62019. **
  62020. ** For most architectures, this is a no-op.
  62021. **
  62022. ** (later): It is reported to me that the mixed-endian problem
  62023. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  62024. ** that early versions of GCC stored the two words of a 64-bit
  62025. ** float in the wrong order. And that error has been propagated
  62026. ** ever since. The blame is not necessarily with GCC, though.
  62027. ** GCC might have just copying the problem from a prior compiler.
  62028. ** I am also told that newer versions of GCC that follow a different
  62029. ** ABI get the byte order right.
  62030. **
  62031. ** Developers using SQLite on an ARM7 should compile and run their
  62032. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  62033. ** enabled, some asserts below will ensure that the byte order of
  62034. ** floating point values is correct.
  62035. **
  62036. ** (2007-08-30) Frank van Vugt has studied this problem closely
  62037. ** and has send his findings to the SQLite developers. Frank
  62038. ** writes that some Linux kernels offer floating point hardware
  62039. ** emulation that uses only 32-bit mantissas instead of a full
  62040. ** 48-bits as required by the IEEE standard. (This is the
  62041. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  62042. ** byte swapping becomes very complicated. To avoid problems,
  62043. ** the necessary byte swapping is carried out using a 64-bit integer
  62044. ** rather than a 64-bit float. Frank assures us that the code here
  62045. ** works for him. We, the developers, have no way to independently
  62046. ** verify this, but Frank seems to know what he is talking about
  62047. ** so we trust him.
  62048. */
  62049. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  62050. static u64 floatSwap(u64 in){
  62051. union {
  62052. u64 r;
  62053. u32 i[2];
  62054. } u;
  62055. u32 t;
  62056. u.r = in;
  62057. t = u.i[0];
  62058. u.i[0] = u.i[1];
  62059. u.i[1] = t;
  62060. return u.r;
  62061. }
  62062. # define swapMixedEndianFloat(X) X = floatSwap(X)
  62063. #else
  62064. # define swapMixedEndianFloat(X)
  62065. #endif
  62066. /*
  62067. ** Write the serialized data blob for the value stored in pMem into
  62068. ** buf. It is assumed that the caller has allocated sufficient space.
  62069. ** Return the number of bytes written.
  62070. **
  62071. ** nBuf is the amount of space left in buf[]. nBuf must always be
  62072. ** large enough to hold the entire field. Except, if the field is
  62073. ** a blob with a zero-filled tail, then buf[] might be just the right
  62074. ** size to hold everything except for the zero-filled tail. If buf[]
  62075. ** is only big enough to hold the non-zero prefix, then only write that
  62076. ** prefix into buf[]. But if buf[] is large enough to hold both the
  62077. ** prefix and the tail then write the prefix and set the tail to all
  62078. ** zeros.
  62079. **
  62080. ** Return the number of bytes actually written into buf[]. The number
  62081. ** of bytes in the zero-filled tail is included in the return value only
  62082. ** if those bytes were zeroed in buf[].
  62083. */
  62084. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  62085. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  62086. u32 len;
  62087. /* Integer and Real */
  62088. if( serial_type<=7 && serial_type>0 ){
  62089. u64 v;
  62090. u32 i;
  62091. if( serial_type==7 ){
  62092. assert( sizeof(v)==sizeof(pMem->r) );
  62093. memcpy(&v, &pMem->r, sizeof(v));
  62094. swapMixedEndianFloat(v);
  62095. }else{
  62096. v = pMem->u.i;
  62097. }
  62098. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  62099. assert( len<=(u32)nBuf );
  62100. while( i-- ){
  62101. buf[i] = (u8)(v&0xFF);
  62102. v >>= 8;
  62103. }
  62104. return len;
  62105. }
  62106. /* String or blob */
  62107. if( serial_type>=12 ){
  62108. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  62109. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  62110. assert( pMem->n<=nBuf );
  62111. len = pMem->n;
  62112. memcpy(buf, pMem->z, len);
  62113. if( pMem->flags & MEM_Zero ){
  62114. len += pMem->u.nZero;
  62115. assert( nBuf>=0 );
  62116. if( len > (u32)nBuf ){
  62117. len = (u32)nBuf;
  62118. }
  62119. memset(&buf[pMem->n], 0, len-pMem->n);
  62120. }
  62121. return len;
  62122. }
  62123. /* NULL or constants 0 or 1 */
  62124. return 0;
  62125. }
  62126. /*
  62127. ** Deserialize the data blob pointed to by buf as serial type serial_type
  62128. ** and store the result in pMem. Return the number of bytes read.
  62129. */
  62130. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  62131. const unsigned char *buf, /* Buffer to deserialize from */
  62132. u32 serial_type, /* Serial type to deserialize */
  62133. Mem *pMem /* Memory cell to write value into */
  62134. ){
  62135. switch( serial_type ){
  62136. case 10: /* Reserved for future use */
  62137. case 11: /* Reserved for future use */
  62138. case 0: { /* NULL */
  62139. pMem->flags = MEM_Null;
  62140. break;
  62141. }
  62142. case 1: { /* 1-byte signed integer */
  62143. pMem->u.i = (signed char)buf[0];
  62144. pMem->flags = MEM_Int;
  62145. return 1;
  62146. }
  62147. case 2: { /* 2-byte signed integer */
  62148. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  62149. pMem->flags = MEM_Int;
  62150. return 2;
  62151. }
  62152. case 3: { /* 3-byte signed integer */
  62153. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  62154. pMem->flags = MEM_Int;
  62155. return 3;
  62156. }
  62157. case 4: { /* 4-byte signed integer */
  62158. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  62159. pMem->flags = MEM_Int;
  62160. return 4;
  62161. }
  62162. case 5: { /* 6-byte signed integer */
  62163. u64 x = (((signed char)buf[0])<<8) | buf[1];
  62164. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  62165. x = (x<<32) | y;
  62166. pMem->u.i = *(i64*)&x;
  62167. pMem->flags = MEM_Int;
  62168. return 6;
  62169. }
  62170. case 6: /* 8-byte signed integer */
  62171. case 7: { /* IEEE floating point */
  62172. u64 x;
  62173. u32 y;
  62174. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  62175. /* Verify that integers and floating point values use the same
  62176. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  62177. ** defined that 64-bit floating point values really are mixed
  62178. ** endian.
  62179. */
  62180. static const u64 t1 = ((u64)0x3ff00000)<<32;
  62181. static const double r1 = 1.0;
  62182. u64 t2 = t1;
  62183. swapMixedEndianFloat(t2);
  62184. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  62185. #endif
  62186. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  62187. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  62188. x = (x<<32) | y;
  62189. if( serial_type==6 ){
  62190. pMem->u.i = *(i64*)&x;
  62191. pMem->flags = MEM_Int;
  62192. }else{
  62193. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  62194. swapMixedEndianFloat(x);
  62195. memcpy(&pMem->r, &x, sizeof(x));
  62196. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  62197. }
  62198. return 8;
  62199. }
  62200. case 8: /* Integer 0 */
  62201. case 9: { /* Integer 1 */
  62202. pMem->u.i = serial_type-8;
  62203. pMem->flags = MEM_Int;
  62204. return 0;
  62205. }
  62206. default: {
  62207. u32 len = (serial_type-12)/2;
  62208. pMem->z = (char *)buf;
  62209. pMem->n = len;
  62210. pMem->xDel = 0;
  62211. if( serial_type&0x01 ){
  62212. pMem->flags = MEM_Str | MEM_Ephem;
  62213. }else{
  62214. pMem->flags = MEM_Blob | MEM_Ephem;
  62215. }
  62216. return len;
  62217. }
  62218. }
  62219. return 0;
  62220. }
  62221. /*
  62222. ** This routine is used to allocate sufficient space for an UnpackedRecord
  62223. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  62224. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  62225. **
  62226. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  62227. ** the unaligned buffer passed via the second and third arguments (presumably
  62228. ** stack space). If the former, then *ppFree is set to a pointer that should
  62229. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  62230. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  62231. ** before returning.
  62232. **
  62233. ** If an OOM error occurs, NULL is returned.
  62234. */
  62235. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  62236. KeyInfo *pKeyInfo, /* Description of the record */
  62237. char *pSpace, /* Unaligned space available */
  62238. int szSpace, /* Size of pSpace[] in bytes */
  62239. char **ppFree /* OUT: Caller should free this pointer */
  62240. ){
  62241. UnpackedRecord *p; /* Unpacked record to return */
  62242. int nOff; /* Increment pSpace by nOff to align it */
  62243. int nByte; /* Number of bytes required for *p */
  62244. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  62245. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  62246. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  62247. */
  62248. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  62249. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  62250. if( nByte>szSpace+nOff ){
  62251. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  62252. *ppFree = (char *)p;
  62253. if( !p ) return 0;
  62254. }else{
  62255. p = (UnpackedRecord*)&pSpace[nOff];
  62256. *ppFree = 0;
  62257. }
  62258. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  62259. assert( pKeyInfo->aSortOrder!=0 );
  62260. p->pKeyInfo = pKeyInfo;
  62261. p->nField = pKeyInfo->nField + 1;
  62262. return p;
  62263. }
  62264. /*
  62265. ** Given the nKey-byte encoding of a record in pKey[], populate the
  62266. ** UnpackedRecord structure indicated by the fourth argument with the
  62267. ** contents of the decoded record.
  62268. */
  62269. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  62270. KeyInfo *pKeyInfo, /* Information about the record format */
  62271. int nKey, /* Size of the binary record */
  62272. const void *pKey, /* The binary record */
  62273. UnpackedRecord *p /* Populate this structure before returning. */
  62274. ){
  62275. const unsigned char *aKey = (const unsigned char *)pKey;
  62276. int d;
  62277. u32 idx; /* Offset in aKey[] to read from */
  62278. u16 u; /* Unsigned loop counter */
  62279. u32 szHdr;
  62280. Mem *pMem = p->aMem;
  62281. p->flags = 0;
  62282. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62283. idx = getVarint32(aKey, szHdr);
  62284. d = szHdr;
  62285. u = 0;
  62286. while( idx<szHdr && u<p->nField && d<=nKey ){
  62287. u32 serial_type;
  62288. idx += getVarint32(&aKey[idx], serial_type);
  62289. pMem->enc = pKeyInfo->enc;
  62290. pMem->db = pKeyInfo->db;
  62291. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  62292. pMem->zMalloc = 0;
  62293. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  62294. pMem++;
  62295. u++;
  62296. }
  62297. assert( u<=pKeyInfo->nField + 1 );
  62298. p->nField = u;
  62299. }
  62300. /*
  62301. ** This function compares the two table rows or index records
  62302. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  62303. ** or positive integer if key1 is less than, equal to or
  62304. ** greater than key2. The {nKey1, pKey1} key must be a blob
  62305. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  62306. ** key must be a parsed key such as obtained from
  62307. ** sqlite3VdbeParseRecord.
  62308. **
  62309. ** Key1 and Key2 do not have to contain the same number of fields.
  62310. ** The key with fewer fields is usually compares less than the
  62311. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  62312. ** and the common prefixes are equal, then key1 is less than key2.
  62313. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  62314. ** equal, then the keys are considered to be equal and
  62315. ** the parts beyond the common prefix are ignored.
  62316. */
  62317. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  62318. int nKey1, const void *pKey1, /* Left key */
  62319. UnpackedRecord *pPKey2 /* Right key */
  62320. ){
  62321. u32 d1; /* Offset into aKey[] of next data element */
  62322. u32 idx1; /* Offset into aKey[] of next header element */
  62323. u32 szHdr1; /* Number of bytes in header */
  62324. int i = 0;
  62325. int rc = 0;
  62326. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  62327. KeyInfo *pKeyInfo;
  62328. Mem mem1;
  62329. pKeyInfo = pPKey2->pKeyInfo;
  62330. mem1.enc = pKeyInfo->enc;
  62331. mem1.db = pKeyInfo->db;
  62332. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  62333. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  62334. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  62335. ** We could initialize it, as shown here, to silence those complaints.
  62336. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  62337. ** the unnecessary initialization has a measurable negative performance
  62338. ** impact, since this routine is a very high runner. And so, we choose
  62339. ** to ignore the compiler warnings and leave this variable uninitialized.
  62340. */
  62341. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  62342. idx1 = getVarint32(aKey1, szHdr1);
  62343. d1 = szHdr1;
  62344. assert( pKeyInfo->nField+1>=pPKey2->nField );
  62345. assert( pKeyInfo->aSortOrder!=0 );
  62346. while( idx1<szHdr1 && i<pPKey2->nField ){
  62347. u32 serial_type1;
  62348. /* Read the serial types for the next element in each key. */
  62349. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  62350. /* Verify that there is enough key space remaining to avoid
  62351. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  62352. ** always be greater than or equal to the amount of required key space.
  62353. ** Use that approximation to avoid the more expensive call to
  62354. ** sqlite3VdbeSerialTypeLen() in the common case.
  62355. */
  62356. if( d1+serial_type1+2>(u32)nKey1
  62357. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  62358. ){
  62359. break;
  62360. }
  62361. /* Extract the values to be compared.
  62362. */
  62363. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  62364. /* Do the comparison
  62365. */
  62366. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  62367. if( rc!=0 ){
  62368. assert( mem1.zMalloc==0 ); /* See comment below */
  62369. /* Invert the result if we are using DESC sort order. */
  62370. if( pKeyInfo->aSortOrder[i] ){
  62371. rc = -rc;
  62372. }
  62373. /* If the PREFIX_SEARCH flag is set and all fields except the final
  62374. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  62375. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  62376. ** This is used by the OP_IsUnique opcode.
  62377. */
  62378. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  62379. assert( idx1==szHdr1 && rc );
  62380. assert( mem1.flags & MEM_Int );
  62381. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  62382. pPKey2->rowid = mem1.u.i;
  62383. }
  62384. return rc;
  62385. }
  62386. i++;
  62387. }
  62388. /* No memory allocation is ever used on mem1. Prove this using
  62389. ** the following assert(). If the assert() fails, it indicates a
  62390. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  62391. */
  62392. assert( mem1.zMalloc==0 );
  62393. /* rc==0 here means that one of the keys ran out of fields and
  62394. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  62395. ** flag is set, then break the tie by treating key2 as larger.
  62396. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  62397. ** are considered to be equal. Otherwise, the longer key is the
  62398. ** larger. As it happens, the pPKey2 will always be the longer
  62399. ** if there is a difference.
  62400. */
  62401. assert( rc==0 );
  62402. if( pPKey2->flags & UNPACKED_INCRKEY ){
  62403. rc = -1;
  62404. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  62405. /* Leave rc==0 */
  62406. }else if( idx1<szHdr1 ){
  62407. rc = 1;
  62408. }
  62409. return rc;
  62410. }
  62411. /*
  62412. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  62413. ** Read the rowid (the last field in the record) and store it in *rowid.
  62414. ** Return SQLITE_OK if everything works, or an error code otherwise.
  62415. **
  62416. ** pCur might be pointing to text obtained from a corrupt database file.
  62417. ** So the content cannot be trusted. Do appropriate checks on the content.
  62418. */
  62419. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  62420. i64 nCellKey = 0;
  62421. int rc;
  62422. u32 szHdr; /* Size of the header */
  62423. u32 typeRowid; /* Serial type of the rowid */
  62424. u32 lenRowid; /* Size of the rowid */
  62425. Mem m, v;
  62426. UNUSED_PARAMETER(db);
  62427. /* Get the size of the index entry. Only indices entries of less
  62428. ** than 2GiB are support - anything large must be database corruption.
  62429. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  62430. ** this code can safely assume that nCellKey is 32-bits
  62431. */
  62432. assert( sqlite3BtreeCursorIsValid(pCur) );
  62433. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62434. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62435. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  62436. /* Read in the complete content of the index entry */
  62437. memset(&m, 0, sizeof(m));
  62438. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  62439. if( rc ){
  62440. return rc;
  62441. }
  62442. /* The index entry must begin with a header size */
  62443. (void)getVarint32((u8*)m.z, szHdr);
  62444. testcase( szHdr==3 );
  62445. testcase( szHdr==m.n );
  62446. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  62447. goto idx_rowid_corruption;
  62448. }
  62449. /* The last field of the index should be an integer - the ROWID.
  62450. ** Verify that the last entry really is an integer. */
  62451. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  62452. testcase( typeRowid==1 );
  62453. testcase( typeRowid==2 );
  62454. testcase( typeRowid==3 );
  62455. testcase( typeRowid==4 );
  62456. testcase( typeRowid==5 );
  62457. testcase( typeRowid==6 );
  62458. testcase( typeRowid==8 );
  62459. testcase( typeRowid==9 );
  62460. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  62461. goto idx_rowid_corruption;
  62462. }
  62463. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  62464. testcase( (u32)m.n==szHdr+lenRowid );
  62465. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  62466. goto idx_rowid_corruption;
  62467. }
  62468. /* Fetch the integer off the end of the index record */
  62469. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  62470. *rowid = v.u.i;
  62471. sqlite3VdbeMemRelease(&m);
  62472. return SQLITE_OK;
  62473. /* Jump here if database corruption is detected after m has been
  62474. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  62475. idx_rowid_corruption:
  62476. testcase( m.zMalloc!=0 );
  62477. sqlite3VdbeMemRelease(&m);
  62478. return SQLITE_CORRUPT_BKPT;
  62479. }
  62480. /*
  62481. ** Compare the key of the index entry that cursor pC is pointing to against
  62482. ** the key string in pUnpacked. Write into *pRes a number
  62483. ** that is negative, zero, or positive if pC is less than, equal to,
  62484. ** or greater than pUnpacked. Return SQLITE_OK on success.
  62485. **
  62486. ** pUnpacked is either created without a rowid or is truncated so that it
  62487. ** omits the rowid at the end. The rowid at the end of the index entry
  62488. ** is ignored as well. Hence, this routine only compares the prefixes
  62489. ** of the keys prior to the final rowid, not the entire key.
  62490. */
  62491. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  62492. VdbeCursor *pC, /* The cursor to compare against */
  62493. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  62494. int *res /* Write the comparison result here */
  62495. ){
  62496. i64 nCellKey = 0;
  62497. int rc;
  62498. BtCursor *pCur = pC->pCursor;
  62499. Mem m;
  62500. assert( sqlite3BtreeCursorIsValid(pCur) );
  62501. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62502. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62503. /* nCellKey will always be between 0 and 0xffffffff because of the say
  62504. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  62505. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  62506. *res = 0;
  62507. return SQLITE_CORRUPT_BKPT;
  62508. }
  62509. memset(&m, 0, sizeof(m));
  62510. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  62511. if( rc ){
  62512. return rc;
  62513. }
  62514. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  62515. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  62516. sqlite3VdbeMemRelease(&m);
  62517. return SQLITE_OK;
  62518. }
  62519. /*
  62520. ** This routine sets the value to be returned by subsequent calls to
  62521. ** sqlite3_changes() on the database handle 'db'.
  62522. */
  62523. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  62524. assert( sqlite3_mutex_held(db->mutex) );
  62525. db->nChange = nChange;
  62526. db->nTotalChange += nChange;
  62527. }
  62528. /*
  62529. ** Set a flag in the vdbe to update the change counter when it is finalised
  62530. ** or reset.
  62531. */
  62532. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  62533. v->changeCntOn = 1;
  62534. }
  62535. /*
  62536. ** Mark every prepared statement associated with a database connection
  62537. ** as expired.
  62538. **
  62539. ** An expired statement means that recompilation of the statement is
  62540. ** recommend. Statements expire when things happen that make their
  62541. ** programs obsolete. Removing user-defined functions or collating
  62542. ** sequences, or changing an authorization function are the types of
  62543. ** things that make prepared statements obsolete.
  62544. */
  62545. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  62546. Vdbe *p;
  62547. for(p = db->pVdbe; p; p=p->pNext){
  62548. p->expired = 1;
  62549. }
  62550. }
  62551. /*
  62552. ** Return the database associated with the Vdbe.
  62553. */
  62554. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  62555. return v->db;
  62556. }
  62557. /*
  62558. ** Return a pointer to an sqlite3_value structure containing the value bound
  62559. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  62560. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  62561. ** constants) to the value before returning it.
  62562. **
  62563. ** The returned value must be freed by the caller using sqlite3ValueFree().
  62564. */
  62565. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  62566. assert( iVar>0 );
  62567. if( v ){
  62568. Mem *pMem = &v->aVar[iVar-1];
  62569. if( 0==(pMem->flags & MEM_Null) ){
  62570. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  62571. if( pRet ){
  62572. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  62573. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  62574. sqlite3VdbeMemStoreType((Mem *)pRet);
  62575. }
  62576. return pRet;
  62577. }
  62578. }
  62579. return 0;
  62580. }
  62581. /*
  62582. ** Configure SQL variable iVar so that binding a new value to it signals
  62583. ** to sqlite3_reoptimize() that re-preparing the statement may result
  62584. ** in a better query plan.
  62585. */
  62586. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  62587. assert( iVar>0 );
  62588. if( iVar>32 ){
  62589. v->expmask = 0xffffffff;
  62590. }else{
  62591. v->expmask |= ((u32)1 << (iVar-1));
  62592. }
  62593. }
  62594. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62595. /*
  62596. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  62597. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  62598. ** in memory obtained from sqlite3DbMalloc).
  62599. */
  62600. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  62601. sqlite3 *db = p->db;
  62602. sqlite3DbFree(db, p->zErrMsg);
  62603. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  62604. sqlite3_free(pVtab->zErrMsg);
  62605. pVtab->zErrMsg = 0;
  62606. }
  62607. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  62608. /************** End of vdbeaux.c *********************************************/
  62609. /************** Begin file vdbeapi.c *****************************************/
  62610. /*
  62611. ** 2004 May 26
  62612. **
  62613. ** The author disclaims copyright to this source code. In place of
  62614. ** a legal notice, here is a blessing:
  62615. **
  62616. ** May you do good and not evil.
  62617. ** May you find forgiveness for yourself and forgive others.
  62618. ** May you share freely, never taking more than you give.
  62619. **
  62620. *************************************************************************
  62621. **
  62622. ** This file contains code use to implement APIs that are part of the
  62623. ** VDBE.
  62624. */
  62625. #ifndef SQLITE_OMIT_DEPRECATED
  62626. /*
  62627. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  62628. ** to be recompiled. A statement needs to be recompiled whenever the
  62629. ** execution environment changes in a way that would alter the program
  62630. ** that sqlite3_prepare() generates. For example, if new functions or
  62631. ** collating sequences are registered or if an authorizer function is
  62632. ** added or changed.
  62633. */
  62634. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  62635. Vdbe *p = (Vdbe*)pStmt;
  62636. return p==0 || p->expired;
  62637. }
  62638. #endif
  62639. /*
  62640. ** Check on a Vdbe to make sure it has not been finalized. Log
  62641. ** an error and return true if it has been finalized (or is otherwise
  62642. ** invalid). Return false if it is ok.
  62643. */
  62644. static int vdbeSafety(Vdbe *p){
  62645. if( p->db==0 ){
  62646. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  62647. return 1;
  62648. }else{
  62649. return 0;
  62650. }
  62651. }
  62652. static int vdbeSafetyNotNull(Vdbe *p){
  62653. if( p==0 ){
  62654. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  62655. return 1;
  62656. }else{
  62657. return vdbeSafety(p);
  62658. }
  62659. }
  62660. /*
  62661. ** The following routine destroys a virtual machine that is created by
  62662. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  62663. ** success/failure code that describes the result of executing the virtual
  62664. ** machine.
  62665. **
  62666. ** This routine sets the error code and string returned by
  62667. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62668. */
  62669. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  62670. int rc;
  62671. if( pStmt==0 ){
  62672. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  62673. ** pointer is a harmless no-op. */
  62674. rc = SQLITE_OK;
  62675. }else{
  62676. Vdbe *v = (Vdbe*)pStmt;
  62677. sqlite3 *db = v->db;
  62678. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  62679. sqlite3_mutex_enter(db->mutex);
  62680. rc = sqlite3VdbeFinalize(v);
  62681. rc = sqlite3ApiExit(db, rc);
  62682. sqlite3LeaveMutexAndCloseZombie(db);
  62683. }
  62684. return rc;
  62685. }
  62686. /*
  62687. ** Terminate the current execution of an SQL statement and reset it
  62688. ** back to its starting state so that it can be reused. A success code from
  62689. ** the prior execution is returned.
  62690. **
  62691. ** This routine sets the error code and string returned by
  62692. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62693. */
  62694. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  62695. int rc;
  62696. if( pStmt==0 ){
  62697. rc = SQLITE_OK;
  62698. }else{
  62699. Vdbe *v = (Vdbe*)pStmt;
  62700. sqlite3_mutex_enter(v->db->mutex);
  62701. rc = sqlite3VdbeReset(v);
  62702. sqlite3VdbeRewind(v);
  62703. assert( (rc & (v->db->errMask))==rc );
  62704. rc = sqlite3ApiExit(v->db, rc);
  62705. sqlite3_mutex_leave(v->db->mutex);
  62706. }
  62707. return rc;
  62708. }
  62709. /*
  62710. ** Set all the parameters in the compiled SQL statement to NULL.
  62711. */
  62712. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  62713. int i;
  62714. int rc = SQLITE_OK;
  62715. Vdbe *p = (Vdbe*)pStmt;
  62716. #if SQLITE_THREADSAFE
  62717. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  62718. #endif
  62719. sqlite3_mutex_enter(mutex);
  62720. for(i=0; i<p->nVar; i++){
  62721. sqlite3VdbeMemRelease(&p->aVar[i]);
  62722. p->aVar[i].flags = MEM_Null;
  62723. }
  62724. if( p->isPrepareV2 && p->expmask ){
  62725. p->expired = 1;
  62726. }
  62727. sqlite3_mutex_leave(mutex);
  62728. return rc;
  62729. }
  62730. /**************************** sqlite3_value_ *******************************
  62731. ** The following routines extract information from a Mem or sqlite3_value
  62732. ** structure.
  62733. */
  62734. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  62735. Mem *p = (Mem*)pVal;
  62736. if( p->flags & (MEM_Blob|MEM_Str) ){
  62737. sqlite3VdbeMemExpandBlob(p);
  62738. p->flags &= ~MEM_Str;
  62739. p->flags |= MEM_Blob;
  62740. return p->n ? p->z : 0;
  62741. }else{
  62742. return sqlite3_value_text(pVal);
  62743. }
  62744. }
  62745. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  62746. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  62747. }
  62748. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  62749. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  62750. }
  62751. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  62752. return sqlite3VdbeRealValue((Mem*)pVal);
  62753. }
  62754. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  62755. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  62756. }
  62757. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  62758. return sqlite3VdbeIntValue((Mem*)pVal);
  62759. }
  62760. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  62761. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  62762. }
  62763. #ifndef SQLITE_OMIT_UTF16
  62764. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  62765. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  62766. }
  62767. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  62768. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  62769. }
  62770. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  62771. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  62772. }
  62773. #endif /* SQLITE_OMIT_UTF16 */
  62774. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  62775. return pVal->type;
  62776. }
  62777. /**************************** sqlite3_result_ *******************************
  62778. ** The following routines are used by user-defined functions to specify
  62779. ** the function result.
  62780. **
  62781. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  62782. ** result as a string or blob but if the string or blob is too large, it
  62783. ** then sets the error code to SQLITE_TOOBIG
  62784. */
  62785. static void setResultStrOrError(
  62786. sqlite3_context *pCtx, /* Function context */
  62787. const char *z, /* String pointer */
  62788. int n, /* Bytes in string, or negative */
  62789. u8 enc, /* Encoding of z. 0 for BLOBs */
  62790. void (*xDel)(void*) /* Destructor function */
  62791. ){
  62792. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  62793. sqlite3_result_error_toobig(pCtx);
  62794. }
  62795. }
  62796. SQLITE_API void sqlite3_result_blob(
  62797. sqlite3_context *pCtx,
  62798. const void *z,
  62799. int n,
  62800. void (*xDel)(void *)
  62801. ){
  62802. assert( n>=0 );
  62803. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62804. setResultStrOrError(pCtx, z, n, 0, xDel);
  62805. }
  62806. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  62807. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62808. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  62809. }
  62810. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  62811. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62812. pCtx->isError = SQLITE_ERROR;
  62813. pCtx->fErrorOrAux = 1;
  62814. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  62815. }
  62816. #ifndef SQLITE_OMIT_UTF16
  62817. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  62818. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62819. pCtx->isError = SQLITE_ERROR;
  62820. pCtx->fErrorOrAux = 1;
  62821. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  62822. }
  62823. #endif
  62824. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  62825. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62826. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  62827. }
  62828. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  62829. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62830. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  62831. }
  62832. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  62833. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62834. sqlite3VdbeMemSetNull(&pCtx->s);
  62835. }
  62836. SQLITE_API void sqlite3_result_text(
  62837. sqlite3_context *pCtx,
  62838. const char *z,
  62839. int n,
  62840. void (*xDel)(void *)
  62841. ){
  62842. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62843. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  62844. }
  62845. #ifndef SQLITE_OMIT_UTF16
  62846. SQLITE_API void sqlite3_result_text16(
  62847. sqlite3_context *pCtx,
  62848. const void *z,
  62849. int n,
  62850. void (*xDel)(void *)
  62851. ){
  62852. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62853. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  62854. }
  62855. SQLITE_API void sqlite3_result_text16be(
  62856. sqlite3_context *pCtx,
  62857. const void *z,
  62858. int n,
  62859. void (*xDel)(void *)
  62860. ){
  62861. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62862. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  62863. }
  62864. SQLITE_API void sqlite3_result_text16le(
  62865. sqlite3_context *pCtx,
  62866. const void *z,
  62867. int n,
  62868. void (*xDel)(void *)
  62869. ){
  62870. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62871. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  62872. }
  62873. #endif /* SQLITE_OMIT_UTF16 */
  62874. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  62875. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62876. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  62877. }
  62878. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  62879. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62880. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  62881. }
  62882. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  62883. pCtx->isError = errCode;
  62884. pCtx->fErrorOrAux = 1;
  62885. if( pCtx->s.flags & MEM_Null ){
  62886. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  62887. SQLITE_UTF8, SQLITE_STATIC);
  62888. }
  62889. }
  62890. /* Force an SQLITE_TOOBIG error. */
  62891. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  62892. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62893. pCtx->isError = SQLITE_TOOBIG;
  62894. pCtx->fErrorOrAux = 1;
  62895. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  62896. SQLITE_UTF8, SQLITE_STATIC);
  62897. }
  62898. /* An SQLITE_NOMEM error. */
  62899. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  62900. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62901. sqlite3VdbeMemSetNull(&pCtx->s);
  62902. pCtx->isError = SQLITE_NOMEM;
  62903. pCtx->fErrorOrAux = 1;
  62904. pCtx->s.db->mallocFailed = 1;
  62905. }
  62906. /*
  62907. ** This function is called after a transaction has been committed. It
  62908. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  62909. */
  62910. static int doWalCallbacks(sqlite3 *db){
  62911. int rc = SQLITE_OK;
  62912. #ifndef SQLITE_OMIT_WAL
  62913. int i;
  62914. for(i=0; i<db->nDb; i++){
  62915. Btree *pBt = db->aDb[i].pBt;
  62916. if( pBt ){
  62917. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  62918. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  62919. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  62920. }
  62921. }
  62922. }
  62923. #endif
  62924. return rc;
  62925. }
  62926. /*
  62927. ** Execute the statement pStmt, either until a row of data is ready, the
  62928. ** statement is completely executed or an error occurs.
  62929. **
  62930. ** This routine implements the bulk of the logic behind the sqlite_step()
  62931. ** API. The only thing omitted is the automatic recompile if a
  62932. ** schema change has occurred. That detail is handled by the
  62933. ** outer sqlite3_step() wrapper procedure.
  62934. */
  62935. static int sqlite3Step(Vdbe *p){
  62936. sqlite3 *db;
  62937. int rc;
  62938. assert(p);
  62939. if( p->magic!=VDBE_MAGIC_RUN ){
  62940. /* We used to require that sqlite3_reset() be called before retrying
  62941. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  62942. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  62943. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  62944. ** This "automatic-reset" change is not technically an incompatibility,
  62945. ** since any application that receives an SQLITE_MISUSE is broken by
  62946. ** definition.
  62947. **
  62948. ** Nevertheless, some published applications that were originally written
  62949. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  62950. ** returns, and those were broken by the automatic-reset change. As a
  62951. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  62952. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  62953. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  62954. ** or SQLITE_BUSY error.
  62955. */
  62956. #ifdef SQLITE_OMIT_AUTORESET
  62957. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  62958. sqlite3_reset((sqlite3_stmt*)p);
  62959. }else{
  62960. return SQLITE_MISUSE_BKPT;
  62961. }
  62962. #else
  62963. sqlite3_reset((sqlite3_stmt*)p);
  62964. #endif
  62965. }
  62966. /* Check that malloc() has not failed. If it has, return early. */
  62967. db = p->db;
  62968. if( db->mallocFailed ){
  62969. p->rc = SQLITE_NOMEM;
  62970. return SQLITE_NOMEM;
  62971. }
  62972. if( p->pc<=0 && p->expired ){
  62973. p->rc = SQLITE_SCHEMA;
  62974. rc = SQLITE_ERROR;
  62975. goto end_of_step;
  62976. }
  62977. if( p->pc<0 ){
  62978. /* If there are no other statements currently running, then
  62979. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  62980. ** from interrupting a statement that has not yet started.
  62981. */
  62982. if( db->nVdbeActive==0 ){
  62983. db->u1.isInterrupted = 0;
  62984. }
  62985. assert( db->nVdbeWrite>0 || db->autoCommit==0
  62986. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  62987. );
  62988. #ifndef SQLITE_OMIT_TRACE
  62989. if( db->xProfile && !db->init.busy ){
  62990. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  62991. }
  62992. #endif
  62993. db->nVdbeActive++;
  62994. if( p->readOnly==0 ) db->nVdbeWrite++;
  62995. if( p->bIsReader ) db->nVdbeRead++;
  62996. p->pc = 0;
  62997. }
  62998. #ifndef SQLITE_OMIT_EXPLAIN
  62999. if( p->explain ){
  63000. rc = sqlite3VdbeList(p);
  63001. }else
  63002. #endif /* SQLITE_OMIT_EXPLAIN */
  63003. {
  63004. db->nVdbeExec++;
  63005. rc = sqlite3VdbeExec(p);
  63006. db->nVdbeExec--;
  63007. }
  63008. #ifndef SQLITE_OMIT_TRACE
  63009. /* Invoke the profile callback if there is one
  63010. */
  63011. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  63012. sqlite3_int64 iNow;
  63013. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  63014. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  63015. }
  63016. #endif
  63017. if( rc==SQLITE_DONE ){
  63018. assert( p->rc==SQLITE_OK );
  63019. p->rc = doWalCallbacks(db);
  63020. if( p->rc!=SQLITE_OK ){
  63021. rc = SQLITE_ERROR;
  63022. }
  63023. }
  63024. db->errCode = rc;
  63025. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  63026. p->rc = SQLITE_NOMEM;
  63027. }
  63028. end_of_step:
  63029. /* At this point local variable rc holds the value that should be
  63030. ** returned if this statement was compiled using the legacy
  63031. ** sqlite3_prepare() interface. According to the docs, this can only
  63032. ** be one of the values in the first assert() below. Variable p->rc
  63033. ** contains the value that would be returned if sqlite3_finalize()
  63034. ** were called on statement p.
  63035. */
  63036. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  63037. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  63038. );
  63039. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  63040. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  63041. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  63042. ** error has occurred, then return the error code in p->rc to the
  63043. ** caller. Set the error code in the database handle to the same value.
  63044. */
  63045. rc = sqlite3VdbeTransferError(p);
  63046. }
  63047. return (rc&db->errMask);
  63048. }
  63049. /*
  63050. ** This is the top-level implementation of sqlite3_step(). Call
  63051. ** sqlite3Step() to do most of the work. If a schema error occurs,
  63052. ** call sqlite3Reprepare() and try again.
  63053. */
  63054. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  63055. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  63056. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  63057. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  63058. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  63059. sqlite3 *db; /* The database connection */
  63060. if( vdbeSafetyNotNull(v) ){
  63061. return SQLITE_MISUSE_BKPT;
  63062. }
  63063. db = v->db;
  63064. sqlite3_mutex_enter(db->mutex);
  63065. v->doingRerun = 0;
  63066. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  63067. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  63068. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  63069. sqlite3_reset(pStmt);
  63070. v->doingRerun = 1;
  63071. assert( v->expired==0 );
  63072. }
  63073. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  63074. /* This case occurs after failing to recompile an sql statement.
  63075. ** The error message from the SQL compiler has already been loaded
  63076. ** into the database handle. This block copies the error message
  63077. ** from the database handle into the statement and sets the statement
  63078. ** program counter to 0 to ensure that when the statement is
  63079. ** finalized or reset the parser error message is available via
  63080. ** sqlite3_errmsg() and sqlite3_errcode().
  63081. */
  63082. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  63083. sqlite3DbFree(db, v->zErrMsg);
  63084. if( !db->mallocFailed ){
  63085. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  63086. v->rc = rc2;
  63087. } else {
  63088. v->zErrMsg = 0;
  63089. v->rc = rc = SQLITE_NOMEM;
  63090. }
  63091. }
  63092. rc = sqlite3ApiExit(db, rc);
  63093. sqlite3_mutex_leave(db->mutex);
  63094. return rc;
  63095. }
  63096. /*
  63097. ** Extract the user data from a sqlite3_context structure and return a
  63098. ** pointer to it.
  63099. */
  63100. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  63101. assert( p && p->pFunc );
  63102. return p->pFunc->pUserData;
  63103. }
  63104. /*
  63105. ** Extract the user data from a sqlite3_context structure and return a
  63106. ** pointer to it.
  63107. **
  63108. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  63109. ** returns a copy of the pointer to the database connection (the 1st
  63110. ** parameter) of the sqlite3_create_function() and
  63111. ** sqlite3_create_function16() routines that originally registered the
  63112. ** application defined function.
  63113. */
  63114. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  63115. assert( p && p->pFunc );
  63116. return p->s.db;
  63117. }
  63118. /*
  63119. ** Return the current time for a statement
  63120. */
  63121. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  63122. Vdbe *v = p->pVdbe;
  63123. int rc;
  63124. if( v->iCurrentTime==0 ){
  63125. rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
  63126. if( rc ) v->iCurrentTime = 0;
  63127. }
  63128. return v->iCurrentTime;
  63129. }
  63130. /*
  63131. ** The following is the implementation of an SQL function that always
  63132. ** fails with an error message stating that the function is used in the
  63133. ** wrong context. The sqlite3_overload_function() API might construct
  63134. ** SQL function that use this routine so that the functions will exist
  63135. ** for name resolution but are actually overloaded by the xFindFunction
  63136. ** method of virtual tables.
  63137. */
  63138. SQLITE_PRIVATE void sqlite3InvalidFunction(
  63139. sqlite3_context *context, /* The function calling context */
  63140. int NotUsed, /* Number of arguments to the function */
  63141. sqlite3_value **NotUsed2 /* Value of each argument */
  63142. ){
  63143. const char *zName = context->pFunc->zName;
  63144. char *zErr;
  63145. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63146. zErr = sqlite3_mprintf(
  63147. "unable to use function %s in the requested context", zName);
  63148. sqlite3_result_error(context, zErr, -1);
  63149. sqlite3_free(zErr);
  63150. }
  63151. /*
  63152. ** Allocate or return the aggregate context for a user function. A new
  63153. ** context is allocated on the first call. Subsequent calls return the
  63154. ** same context that was returned on prior calls.
  63155. */
  63156. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  63157. Mem *pMem;
  63158. assert( p && p->pFunc && p->pFunc->xStep );
  63159. assert( sqlite3_mutex_held(p->s.db->mutex) );
  63160. pMem = p->pMem;
  63161. testcase( nByte<0 );
  63162. if( (pMem->flags & MEM_Agg)==0 ){
  63163. if( nByte<=0 ){
  63164. sqlite3VdbeMemReleaseExternal(pMem);
  63165. pMem->flags = MEM_Null;
  63166. pMem->z = 0;
  63167. }else{
  63168. sqlite3VdbeMemGrow(pMem, nByte, 0);
  63169. pMem->flags = MEM_Agg;
  63170. pMem->u.pDef = p->pFunc;
  63171. if( pMem->z ){
  63172. memset(pMem->z, 0, nByte);
  63173. }
  63174. }
  63175. }
  63176. return (void*)pMem->z;
  63177. }
  63178. /*
  63179. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  63180. ** the user-function defined by pCtx.
  63181. */
  63182. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  63183. AuxData *pAuxData;
  63184. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  63185. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63186. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63187. }
  63188. return (pAuxData ? pAuxData->pAux : 0);
  63189. }
  63190. /*
  63191. ** Set the auxilary data pointer and delete function, for the iArg'th
  63192. ** argument to the user-function defined by pCtx. Any previous value is
  63193. ** deleted by calling the delete function specified when it was set.
  63194. */
  63195. SQLITE_API void sqlite3_set_auxdata(
  63196. sqlite3_context *pCtx,
  63197. int iArg,
  63198. void *pAux,
  63199. void (*xDelete)(void*)
  63200. ){
  63201. AuxData *pAuxData;
  63202. Vdbe *pVdbe = pCtx->pVdbe;
  63203. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  63204. if( iArg<0 ) goto failed;
  63205. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63206. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63207. }
  63208. if( pAuxData==0 ){
  63209. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  63210. if( !pAuxData ) goto failed;
  63211. pAuxData->iOp = pCtx->iOp;
  63212. pAuxData->iArg = iArg;
  63213. pAuxData->pNext = pVdbe->pAuxData;
  63214. pVdbe->pAuxData = pAuxData;
  63215. if( pCtx->fErrorOrAux==0 ){
  63216. pCtx->isError = 0;
  63217. pCtx->fErrorOrAux = 1;
  63218. }
  63219. }else if( pAuxData->xDelete ){
  63220. pAuxData->xDelete(pAuxData->pAux);
  63221. }
  63222. pAuxData->pAux = pAux;
  63223. pAuxData->xDelete = xDelete;
  63224. return;
  63225. failed:
  63226. if( xDelete ){
  63227. xDelete(pAux);
  63228. }
  63229. }
  63230. #ifndef SQLITE_OMIT_DEPRECATED
  63231. /*
  63232. ** Return the number of times the Step function of a aggregate has been
  63233. ** called.
  63234. **
  63235. ** This function is deprecated. Do not use it for new code. It is
  63236. ** provide only to avoid breaking legacy code. New aggregate function
  63237. ** implementations should keep their own counts within their aggregate
  63238. ** context.
  63239. */
  63240. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  63241. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  63242. return p->pMem->n;
  63243. }
  63244. #endif
  63245. /*
  63246. ** Return the number of columns in the result set for the statement pStmt.
  63247. */
  63248. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  63249. Vdbe *pVm = (Vdbe *)pStmt;
  63250. return pVm ? pVm->nResColumn : 0;
  63251. }
  63252. /*
  63253. ** Return the number of values available from the current row of the
  63254. ** currently executing statement pStmt.
  63255. */
  63256. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  63257. Vdbe *pVm = (Vdbe *)pStmt;
  63258. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  63259. return pVm->nResColumn;
  63260. }
  63261. /*
  63262. ** Check to see if column iCol of the given statement is valid. If
  63263. ** it is, return a pointer to the Mem for the value of that column.
  63264. ** If iCol is not valid, return a pointer to a Mem which has a value
  63265. ** of NULL.
  63266. */
  63267. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  63268. Vdbe *pVm;
  63269. Mem *pOut;
  63270. pVm = (Vdbe *)pStmt;
  63271. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  63272. sqlite3_mutex_enter(pVm->db->mutex);
  63273. pOut = &pVm->pResultSet[i];
  63274. }else{
  63275. /* If the value passed as the second argument is out of range, return
  63276. ** a pointer to the following static Mem object which contains the
  63277. ** value SQL NULL. Even though the Mem structure contains an element
  63278. ** of type i64, on certain architectures (x86) with certain compiler
  63279. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  63280. ** instead of an 8-byte one. This all works fine, except that when
  63281. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  63282. ** that a Mem structure is located on an 8-byte boundary. To prevent
  63283. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  63284. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  63285. ** __attribute__((aligned(8))) macro. */
  63286. static const Mem nullMem
  63287. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  63288. __attribute__((aligned(8)))
  63289. #endif
  63290. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  63291. #ifdef SQLITE_DEBUG
  63292. 0, 0, /* pScopyFrom, pFiller */
  63293. #endif
  63294. 0, 0 };
  63295. if( pVm && ALWAYS(pVm->db) ){
  63296. sqlite3_mutex_enter(pVm->db->mutex);
  63297. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  63298. }
  63299. pOut = (Mem*)&nullMem;
  63300. }
  63301. return pOut;
  63302. }
  63303. /*
  63304. ** This function is called after invoking an sqlite3_value_XXX function on a
  63305. ** column value (i.e. a value returned by evaluating an SQL expression in the
  63306. ** select list of a SELECT statement) that may cause a malloc() failure. If
  63307. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  63308. ** code of statement pStmt set to SQLITE_NOMEM.
  63309. **
  63310. ** Specifically, this is called from within:
  63311. **
  63312. ** sqlite3_column_int()
  63313. ** sqlite3_column_int64()
  63314. ** sqlite3_column_text()
  63315. ** sqlite3_column_text16()
  63316. ** sqlite3_column_real()
  63317. ** sqlite3_column_bytes()
  63318. ** sqlite3_column_bytes16()
  63319. ** sqiite3_column_blob()
  63320. */
  63321. static void columnMallocFailure(sqlite3_stmt *pStmt)
  63322. {
  63323. /* If malloc() failed during an encoding conversion within an
  63324. ** sqlite3_column_XXX API, then set the return code of the statement to
  63325. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  63326. ** and _finalize() will return NOMEM.
  63327. */
  63328. Vdbe *p = (Vdbe *)pStmt;
  63329. if( p ){
  63330. p->rc = sqlite3ApiExit(p->db, p->rc);
  63331. sqlite3_mutex_leave(p->db->mutex);
  63332. }
  63333. }
  63334. /**************************** sqlite3_column_ *******************************
  63335. ** The following routines are used to access elements of the current row
  63336. ** in the result set.
  63337. */
  63338. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  63339. const void *val;
  63340. val = sqlite3_value_blob( columnMem(pStmt,i) );
  63341. /* Even though there is no encoding conversion, value_blob() might
  63342. ** need to call malloc() to expand the result of a zeroblob()
  63343. ** expression.
  63344. */
  63345. columnMallocFailure(pStmt);
  63346. return val;
  63347. }
  63348. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  63349. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  63350. columnMallocFailure(pStmt);
  63351. return val;
  63352. }
  63353. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  63354. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  63355. columnMallocFailure(pStmt);
  63356. return val;
  63357. }
  63358. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  63359. double val = sqlite3_value_double( columnMem(pStmt,i) );
  63360. columnMallocFailure(pStmt);
  63361. return val;
  63362. }
  63363. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  63364. int val = sqlite3_value_int( columnMem(pStmt,i) );
  63365. columnMallocFailure(pStmt);
  63366. return val;
  63367. }
  63368. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  63369. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  63370. columnMallocFailure(pStmt);
  63371. return val;
  63372. }
  63373. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  63374. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  63375. columnMallocFailure(pStmt);
  63376. return val;
  63377. }
  63378. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  63379. Mem *pOut = columnMem(pStmt, i);
  63380. if( pOut->flags&MEM_Static ){
  63381. pOut->flags &= ~MEM_Static;
  63382. pOut->flags |= MEM_Ephem;
  63383. }
  63384. columnMallocFailure(pStmt);
  63385. return (sqlite3_value *)pOut;
  63386. }
  63387. #ifndef SQLITE_OMIT_UTF16
  63388. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  63389. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  63390. columnMallocFailure(pStmt);
  63391. return val;
  63392. }
  63393. #endif /* SQLITE_OMIT_UTF16 */
  63394. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  63395. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  63396. columnMallocFailure(pStmt);
  63397. return iType;
  63398. }
  63399. /*
  63400. ** Convert the N-th element of pStmt->pColName[] into a string using
  63401. ** xFunc() then return that string. If N is out of range, return 0.
  63402. **
  63403. ** There are up to 5 names for each column. useType determines which
  63404. ** name is returned. Here are the names:
  63405. **
  63406. ** 0 The column name as it should be displayed for output
  63407. ** 1 The datatype name for the column
  63408. ** 2 The name of the database that the column derives from
  63409. ** 3 The name of the table that the column derives from
  63410. ** 4 The name of the table column that the result column derives from
  63411. **
  63412. ** If the result is not a simple column reference (if it is an expression
  63413. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  63414. */
  63415. static const void *columnName(
  63416. sqlite3_stmt *pStmt,
  63417. int N,
  63418. const void *(*xFunc)(Mem*),
  63419. int useType
  63420. ){
  63421. const void *ret = 0;
  63422. Vdbe *p = (Vdbe *)pStmt;
  63423. int n;
  63424. sqlite3 *db = p->db;
  63425. assert( db!=0 );
  63426. n = sqlite3_column_count(pStmt);
  63427. if( N<n && N>=0 ){
  63428. N += useType*n;
  63429. sqlite3_mutex_enter(db->mutex);
  63430. assert( db->mallocFailed==0 );
  63431. ret = xFunc(&p->aColName[N]);
  63432. /* A malloc may have failed inside of the xFunc() call. If this
  63433. ** is the case, clear the mallocFailed flag and return NULL.
  63434. */
  63435. if( db->mallocFailed ){
  63436. db->mallocFailed = 0;
  63437. ret = 0;
  63438. }
  63439. sqlite3_mutex_leave(db->mutex);
  63440. }
  63441. return ret;
  63442. }
  63443. /*
  63444. ** Return the name of the Nth column of the result set returned by SQL
  63445. ** statement pStmt.
  63446. */
  63447. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  63448. return columnName(
  63449. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  63450. }
  63451. #ifndef SQLITE_OMIT_UTF16
  63452. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  63453. return columnName(
  63454. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  63455. }
  63456. #endif
  63457. /*
  63458. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  63459. ** not define OMIT_DECLTYPE.
  63460. */
  63461. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  63462. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  63463. and SQLITE_ENABLE_COLUMN_METADATA"
  63464. #endif
  63465. #ifndef SQLITE_OMIT_DECLTYPE
  63466. /*
  63467. ** Return the column declaration type (if applicable) of the 'i'th column
  63468. ** of the result set of SQL statement pStmt.
  63469. */
  63470. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  63471. return columnName(
  63472. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  63473. }
  63474. #ifndef SQLITE_OMIT_UTF16
  63475. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  63476. return columnName(
  63477. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  63478. }
  63479. #endif /* SQLITE_OMIT_UTF16 */
  63480. #endif /* SQLITE_OMIT_DECLTYPE */
  63481. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  63482. /*
  63483. ** Return the name of the database from which a result column derives.
  63484. ** NULL is returned if the result column is an expression or constant or
  63485. ** anything else which is not an unabiguous reference to a database column.
  63486. */
  63487. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  63488. return columnName(
  63489. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  63490. }
  63491. #ifndef SQLITE_OMIT_UTF16
  63492. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  63493. return columnName(
  63494. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  63495. }
  63496. #endif /* SQLITE_OMIT_UTF16 */
  63497. /*
  63498. ** Return the name of the table from which a result column derives.
  63499. ** NULL is returned if the result column is an expression or constant or
  63500. ** anything else which is not an unabiguous reference to a database column.
  63501. */
  63502. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  63503. return columnName(
  63504. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  63505. }
  63506. #ifndef SQLITE_OMIT_UTF16
  63507. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  63508. return columnName(
  63509. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  63510. }
  63511. #endif /* SQLITE_OMIT_UTF16 */
  63512. /*
  63513. ** Return the name of the table column from which a result column derives.
  63514. ** NULL is returned if the result column is an expression or constant or
  63515. ** anything else which is not an unabiguous reference to a database column.
  63516. */
  63517. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  63518. return columnName(
  63519. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  63520. }
  63521. #ifndef SQLITE_OMIT_UTF16
  63522. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  63523. return columnName(
  63524. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  63525. }
  63526. #endif /* SQLITE_OMIT_UTF16 */
  63527. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  63528. /******************************* sqlite3_bind_ ***************************
  63529. **
  63530. ** Routines used to attach values to wildcards in a compiled SQL statement.
  63531. */
  63532. /*
  63533. ** Unbind the value bound to variable i in virtual machine p. This is the
  63534. ** the same as binding a NULL value to the column. If the "i" parameter is
  63535. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  63536. **
  63537. ** A successful evaluation of this routine acquires the mutex on p.
  63538. ** the mutex is released if any kind of error occurs.
  63539. **
  63540. ** The error code stored in database p->db is overwritten with the return
  63541. ** value in any case.
  63542. */
  63543. static int vdbeUnbind(Vdbe *p, int i){
  63544. Mem *pVar;
  63545. if( vdbeSafetyNotNull(p) ){
  63546. return SQLITE_MISUSE_BKPT;
  63547. }
  63548. sqlite3_mutex_enter(p->db->mutex);
  63549. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  63550. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  63551. sqlite3_mutex_leave(p->db->mutex);
  63552. sqlite3_log(SQLITE_MISUSE,
  63553. "bind on a busy prepared statement: [%s]", p->zSql);
  63554. return SQLITE_MISUSE_BKPT;
  63555. }
  63556. if( i<1 || i>p->nVar ){
  63557. sqlite3Error(p->db, SQLITE_RANGE, 0);
  63558. sqlite3_mutex_leave(p->db->mutex);
  63559. return SQLITE_RANGE;
  63560. }
  63561. i--;
  63562. pVar = &p->aVar[i];
  63563. sqlite3VdbeMemRelease(pVar);
  63564. pVar->flags = MEM_Null;
  63565. sqlite3Error(p->db, SQLITE_OK, 0);
  63566. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  63567. ** binding a new value to this variable invalidates the current query plan.
  63568. **
  63569. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  63570. ** parameter in the WHERE clause might influence the choice of query plan
  63571. ** for a statement, then the statement will be automatically recompiled,
  63572. ** as if there had been a schema change, on the first sqlite3_step() call
  63573. ** following any change to the bindings of that parameter.
  63574. */
  63575. if( p->isPrepareV2 &&
  63576. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  63577. ){
  63578. p->expired = 1;
  63579. }
  63580. return SQLITE_OK;
  63581. }
  63582. /*
  63583. ** Bind a text or BLOB value.
  63584. */
  63585. static int bindText(
  63586. sqlite3_stmt *pStmt, /* The statement to bind against */
  63587. int i, /* Index of the parameter to bind */
  63588. const void *zData, /* Pointer to the data to be bound */
  63589. int nData, /* Number of bytes of data to be bound */
  63590. void (*xDel)(void*), /* Destructor for the data */
  63591. u8 encoding /* Encoding for the data */
  63592. ){
  63593. Vdbe *p = (Vdbe *)pStmt;
  63594. Mem *pVar;
  63595. int rc;
  63596. rc = vdbeUnbind(p, i);
  63597. if( rc==SQLITE_OK ){
  63598. if( zData!=0 ){
  63599. pVar = &p->aVar[i-1];
  63600. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  63601. if( rc==SQLITE_OK && encoding!=0 ){
  63602. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  63603. }
  63604. sqlite3Error(p->db, rc, 0);
  63605. rc = sqlite3ApiExit(p->db, rc);
  63606. }
  63607. sqlite3_mutex_leave(p->db->mutex);
  63608. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  63609. xDel((void*)zData);
  63610. }
  63611. return rc;
  63612. }
  63613. /*
  63614. ** Bind a blob value to an SQL statement variable.
  63615. */
  63616. SQLITE_API int sqlite3_bind_blob(
  63617. sqlite3_stmt *pStmt,
  63618. int i,
  63619. const void *zData,
  63620. int nData,
  63621. void (*xDel)(void*)
  63622. ){
  63623. return bindText(pStmt, i, zData, nData, xDel, 0);
  63624. }
  63625. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  63626. int rc;
  63627. Vdbe *p = (Vdbe *)pStmt;
  63628. rc = vdbeUnbind(p, i);
  63629. if( rc==SQLITE_OK ){
  63630. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  63631. sqlite3_mutex_leave(p->db->mutex);
  63632. }
  63633. return rc;
  63634. }
  63635. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  63636. return sqlite3_bind_int64(p, i, (i64)iValue);
  63637. }
  63638. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  63639. int rc;
  63640. Vdbe *p = (Vdbe *)pStmt;
  63641. rc = vdbeUnbind(p, i);
  63642. if( rc==SQLITE_OK ){
  63643. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  63644. sqlite3_mutex_leave(p->db->mutex);
  63645. }
  63646. return rc;
  63647. }
  63648. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  63649. int rc;
  63650. Vdbe *p = (Vdbe*)pStmt;
  63651. rc = vdbeUnbind(p, i);
  63652. if( rc==SQLITE_OK ){
  63653. sqlite3_mutex_leave(p->db->mutex);
  63654. }
  63655. return rc;
  63656. }
  63657. SQLITE_API int sqlite3_bind_text(
  63658. sqlite3_stmt *pStmt,
  63659. int i,
  63660. const char *zData,
  63661. int nData,
  63662. void (*xDel)(void*)
  63663. ){
  63664. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  63665. }
  63666. #ifndef SQLITE_OMIT_UTF16
  63667. SQLITE_API int sqlite3_bind_text16(
  63668. sqlite3_stmt *pStmt,
  63669. int i,
  63670. const void *zData,
  63671. int nData,
  63672. void (*xDel)(void*)
  63673. ){
  63674. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  63675. }
  63676. #endif /* SQLITE_OMIT_UTF16 */
  63677. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  63678. int rc;
  63679. switch( pValue->type ){
  63680. case SQLITE_INTEGER: {
  63681. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  63682. break;
  63683. }
  63684. case SQLITE_FLOAT: {
  63685. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  63686. break;
  63687. }
  63688. case SQLITE_BLOB: {
  63689. if( pValue->flags & MEM_Zero ){
  63690. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  63691. }else{
  63692. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  63693. }
  63694. break;
  63695. }
  63696. case SQLITE_TEXT: {
  63697. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  63698. pValue->enc);
  63699. break;
  63700. }
  63701. default: {
  63702. rc = sqlite3_bind_null(pStmt, i);
  63703. break;
  63704. }
  63705. }
  63706. return rc;
  63707. }
  63708. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  63709. int rc;
  63710. Vdbe *p = (Vdbe *)pStmt;
  63711. rc = vdbeUnbind(p, i);
  63712. if( rc==SQLITE_OK ){
  63713. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  63714. sqlite3_mutex_leave(p->db->mutex);
  63715. }
  63716. return rc;
  63717. }
  63718. /*
  63719. ** Return the number of wildcards that can be potentially bound to.
  63720. ** This routine is added to support DBD::SQLite.
  63721. */
  63722. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  63723. Vdbe *p = (Vdbe*)pStmt;
  63724. return p ? p->nVar : 0;
  63725. }
  63726. /*
  63727. ** Return the name of a wildcard parameter. Return NULL if the index
  63728. ** is out of range or if the wildcard is unnamed.
  63729. **
  63730. ** The result is always UTF-8.
  63731. */
  63732. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  63733. Vdbe *p = (Vdbe*)pStmt;
  63734. if( p==0 || i<1 || i>p->nzVar ){
  63735. return 0;
  63736. }
  63737. return p->azVar[i-1];
  63738. }
  63739. /*
  63740. ** Given a wildcard parameter name, return the index of the variable
  63741. ** with that name. If there is no variable with the given name,
  63742. ** return 0.
  63743. */
  63744. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  63745. int i;
  63746. if( p==0 ){
  63747. return 0;
  63748. }
  63749. if( zName ){
  63750. for(i=0; i<p->nzVar; i++){
  63751. const char *z = p->azVar[i];
  63752. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  63753. return i+1;
  63754. }
  63755. }
  63756. }
  63757. return 0;
  63758. }
  63759. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  63760. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  63761. }
  63762. /*
  63763. ** Transfer all bindings from the first statement over to the second.
  63764. */
  63765. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  63766. Vdbe *pFrom = (Vdbe*)pFromStmt;
  63767. Vdbe *pTo = (Vdbe*)pToStmt;
  63768. int i;
  63769. assert( pTo->db==pFrom->db );
  63770. assert( pTo->nVar==pFrom->nVar );
  63771. sqlite3_mutex_enter(pTo->db->mutex);
  63772. for(i=0; i<pFrom->nVar; i++){
  63773. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  63774. }
  63775. sqlite3_mutex_leave(pTo->db->mutex);
  63776. return SQLITE_OK;
  63777. }
  63778. #ifndef SQLITE_OMIT_DEPRECATED
  63779. /*
  63780. ** Deprecated external interface. Internal/core SQLite code
  63781. ** should call sqlite3TransferBindings.
  63782. **
  63783. ** Is is misuse to call this routine with statements from different
  63784. ** database connections. But as this is a deprecated interface, we
  63785. ** will not bother to check for that condition.
  63786. **
  63787. ** If the two statements contain a different number of bindings, then
  63788. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  63789. ** SQLITE_OK is returned.
  63790. */
  63791. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  63792. Vdbe *pFrom = (Vdbe*)pFromStmt;
  63793. Vdbe *pTo = (Vdbe*)pToStmt;
  63794. if( pFrom->nVar!=pTo->nVar ){
  63795. return SQLITE_ERROR;
  63796. }
  63797. if( pTo->isPrepareV2 && pTo->expmask ){
  63798. pTo->expired = 1;
  63799. }
  63800. if( pFrom->isPrepareV2 && pFrom->expmask ){
  63801. pFrom->expired = 1;
  63802. }
  63803. return sqlite3TransferBindings(pFromStmt, pToStmt);
  63804. }
  63805. #endif
  63806. /*
  63807. ** Return the sqlite3* database handle to which the prepared statement given
  63808. ** in the argument belongs. This is the same database handle that was
  63809. ** the first argument to the sqlite3_prepare() that was used to create
  63810. ** the statement in the first place.
  63811. */
  63812. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  63813. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  63814. }
  63815. /*
  63816. ** Return true if the prepared statement is guaranteed to not modify the
  63817. ** database.
  63818. */
  63819. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  63820. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  63821. }
  63822. /*
  63823. ** Return true if the prepared statement is in need of being reset.
  63824. */
  63825. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  63826. Vdbe *v = (Vdbe*)pStmt;
  63827. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  63828. }
  63829. /*
  63830. ** Return a pointer to the next prepared statement after pStmt associated
  63831. ** with database connection pDb. If pStmt is NULL, return the first
  63832. ** prepared statement for the database connection. Return NULL if there
  63833. ** are no more.
  63834. */
  63835. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  63836. sqlite3_stmt *pNext;
  63837. sqlite3_mutex_enter(pDb->mutex);
  63838. if( pStmt==0 ){
  63839. pNext = (sqlite3_stmt*)pDb->pVdbe;
  63840. }else{
  63841. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  63842. }
  63843. sqlite3_mutex_leave(pDb->mutex);
  63844. return pNext;
  63845. }
  63846. /*
  63847. ** Return the value of a status counter for a prepared statement
  63848. */
  63849. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  63850. Vdbe *pVdbe = (Vdbe*)pStmt;
  63851. u32 v = pVdbe->aCounter[op];
  63852. if( resetFlag ) pVdbe->aCounter[op] = 0;
  63853. return (int)v;
  63854. }
  63855. /************** End of vdbeapi.c *********************************************/
  63856. /************** Begin file vdbetrace.c ***************************************/
  63857. /*
  63858. ** 2009 November 25
  63859. **
  63860. ** The author disclaims copyright to this source code. In place of
  63861. ** a legal notice, here is a blessing:
  63862. **
  63863. ** May you do good and not evil.
  63864. ** May you find forgiveness for yourself and forgive others.
  63865. ** May you share freely, never taking more than you give.
  63866. **
  63867. *************************************************************************
  63868. **
  63869. ** This file contains code used to insert the values of host parameters
  63870. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  63871. **
  63872. ** The Vdbe parse-tree explainer is also found here.
  63873. */
  63874. #ifndef SQLITE_OMIT_TRACE
  63875. /*
  63876. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  63877. ** bytes in this text up to but excluding the first character in
  63878. ** a host parameter. If the text contains no host parameters, return
  63879. ** the total number of bytes in the text.
  63880. */
  63881. static int findNextHostParameter(const char *zSql, int *pnToken){
  63882. int tokenType;
  63883. int nTotal = 0;
  63884. int n;
  63885. *pnToken = 0;
  63886. while( zSql[0] ){
  63887. n = sqlite3GetToken((u8*)zSql, &tokenType);
  63888. assert( n>0 && tokenType!=TK_ILLEGAL );
  63889. if( tokenType==TK_VARIABLE ){
  63890. *pnToken = n;
  63891. break;
  63892. }
  63893. nTotal += n;
  63894. zSql += n;
  63895. }
  63896. return nTotal;
  63897. }
  63898. /*
  63899. ** This function returns a pointer to a nul-terminated string in memory
  63900. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  63901. ** string contains a copy of zRawSql but with host parameters expanded to
  63902. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  63903. ** then the returned string holds a copy of zRawSql with "-- " prepended
  63904. ** to each line of text.
  63905. **
  63906. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  63907. ** then long strings and blobs are truncated to that many bytes. This
  63908. ** can be used to prevent unreasonably large trace strings when dealing
  63909. ** with large (multi-megabyte) strings and blobs.
  63910. **
  63911. ** The calling function is responsible for making sure the memory returned
  63912. ** is eventually freed.
  63913. **
  63914. ** ALGORITHM: Scan the input string looking for host parameters in any of
  63915. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  63916. ** string literals, quoted identifier names, and comments. For text forms,
  63917. ** the host parameter index is found by scanning the perpared
  63918. ** statement for the corresponding OP_Variable opcode. Once the host
  63919. ** parameter index is known, locate the value in p->aVar[]. Then render
  63920. ** the value as a literal in place of the host parameter name.
  63921. */
  63922. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  63923. Vdbe *p, /* The prepared statement being evaluated */
  63924. const char *zRawSql /* Raw text of the SQL statement */
  63925. ){
  63926. sqlite3 *db; /* The database connection */
  63927. int idx = 0; /* Index of a host parameter */
  63928. int nextIndex = 1; /* Index of next ? host parameter */
  63929. int n; /* Length of a token prefix */
  63930. int nToken; /* Length of the parameter token */
  63931. int i; /* Loop counter */
  63932. Mem *pVar; /* Value of a host parameter */
  63933. StrAccum out; /* Accumulate the output here */
  63934. char zBase[100]; /* Initial working space */
  63935. db = p->db;
  63936. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  63937. db->aLimit[SQLITE_LIMIT_LENGTH]);
  63938. out.db = db;
  63939. if( db->nVdbeExec>1 ){
  63940. while( *zRawSql ){
  63941. const char *zStart = zRawSql;
  63942. while( *(zRawSql++)!='\n' && *zRawSql );
  63943. sqlite3StrAccumAppend(&out, "-- ", 3);
  63944. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  63945. }
  63946. }else{
  63947. while( zRawSql[0] ){
  63948. n = findNextHostParameter(zRawSql, &nToken);
  63949. assert( n>0 );
  63950. sqlite3StrAccumAppend(&out, zRawSql, n);
  63951. zRawSql += n;
  63952. assert( zRawSql[0] || nToken==0 );
  63953. if( nToken==0 ) break;
  63954. if( zRawSql[0]=='?' ){
  63955. if( nToken>1 ){
  63956. assert( sqlite3Isdigit(zRawSql[1]) );
  63957. sqlite3GetInt32(&zRawSql[1], &idx);
  63958. }else{
  63959. idx = nextIndex;
  63960. }
  63961. }else{
  63962. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  63963. testcase( zRawSql[0]==':' );
  63964. testcase( zRawSql[0]=='$' );
  63965. testcase( zRawSql[0]=='@' );
  63966. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  63967. assert( idx>0 );
  63968. }
  63969. zRawSql += nToken;
  63970. nextIndex = idx + 1;
  63971. assert( idx>0 && idx<=p->nVar );
  63972. pVar = &p->aVar[idx-1];
  63973. if( pVar->flags & MEM_Null ){
  63974. sqlite3StrAccumAppend(&out, "NULL", 4);
  63975. }else if( pVar->flags & MEM_Int ){
  63976. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  63977. }else if( pVar->flags & MEM_Real ){
  63978. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  63979. }else if( pVar->flags & MEM_Str ){
  63980. int nOut; /* Number of bytes of the string text to include in output */
  63981. #ifndef SQLITE_OMIT_UTF16
  63982. u8 enc = ENC(db);
  63983. Mem utf8;
  63984. if( enc!=SQLITE_UTF8 ){
  63985. memset(&utf8, 0, sizeof(utf8));
  63986. utf8.db = db;
  63987. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  63988. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  63989. pVar = &utf8;
  63990. }
  63991. #endif
  63992. nOut = pVar->n;
  63993. #ifdef SQLITE_TRACE_SIZE_LIMIT
  63994. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  63995. nOut = SQLITE_TRACE_SIZE_LIMIT;
  63996. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  63997. }
  63998. #endif
  63999. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  64000. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64001. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  64002. #endif
  64003. #ifndef SQLITE_OMIT_UTF16
  64004. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  64005. #endif
  64006. }else if( pVar->flags & MEM_Zero ){
  64007. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  64008. }else{
  64009. int nOut; /* Number of bytes of the blob to include in output */
  64010. assert( pVar->flags & MEM_Blob );
  64011. sqlite3StrAccumAppend(&out, "x'", 2);
  64012. nOut = pVar->n;
  64013. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64014. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  64015. #endif
  64016. for(i=0; i<nOut; i++){
  64017. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  64018. }
  64019. sqlite3StrAccumAppend(&out, "'", 1);
  64020. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64021. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  64022. #endif
  64023. }
  64024. }
  64025. }
  64026. return sqlite3StrAccumFinish(&out);
  64027. }
  64028. #endif /* #ifndef SQLITE_OMIT_TRACE */
  64029. /*****************************************************************************
  64030. ** The following code implements the data-structure explaining logic
  64031. ** for the Vdbe.
  64032. */
  64033. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64034. /*
  64035. ** Allocate a new Explain object
  64036. */
  64037. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  64038. if( pVdbe ){
  64039. Explain *p;
  64040. sqlite3BeginBenignMalloc();
  64041. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  64042. if( p ){
  64043. p->pVdbe = pVdbe;
  64044. sqlite3_free(pVdbe->pExplain);
  64045. pVdbe->pExplain = p;
  64046. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  64047. SQLITE_MAX_LENGTH);
  64048. p->str.useMalloc = 2;
  64049. }else{
  64050. sqlite3EndBenignMalloc();
  64051. }
  64052. }
  64053. }
  64054. /*
  64055. ** Return true if the Explain ends with a new-line.
  64056. */
  64057. static int endsWithNL(Explain *p){
  64058. return p && p->str.zText && p->str.nChar
  64059. && p->str.zText[p->str.nChar-1]=='\n';
  64060. }
  64061. /*
  64062. ** Append text to the indentation
  64063. */
  64064. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  64065. Explain *p;
  64066. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  64067. va_list ap;
  64068. if( p->nIndent && endsWithNL(p) ){
  64069. int n = p->nIndent;
  64070. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  64071. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  64072. }
  64073. va_start(ap, zFormat);
  64074. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  64075. va_end(ap);
  64076. }
  64077. }
  64078. /*
  64079. ** Append a '\n' if there is not already one.
  64080. */
  64081. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  64082. Explain *p;
  64083. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  64084. sqlite3StrAccumAppend(&p->str, "\n", 1);
  64085. }
  64086. }
  64087. /*
  64088. ** Push a new indentation level. Subsequent lines will be indented
  64089. ** so that they begin at the current cursor position.
  64090. */
  64091. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  64092. Explain *p;
  64093. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  64094. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  64095. const char *z = p->str.zText;
  64096. int i = p->str.nChar-1;
  64097. int x;
  64098. while( i>=0 && z[i]!='\n' ){ i--; }
  64099. x = (p->str.nChar - 1) - i;
  64100. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  64101. x = p->aIndent[p->nIndent-1];
  64102. }
  64103. p->aIndent[p->nIndent] = x;
  64104. }
  64105. p->nIndent++;
  64106. }
  64107. }
  64108. /*
  64109. ** Pop the indentation stack by one level.
  64110. */
  64111. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  64112. if( p && p->pExplain ) p->pExplain->nIndent--;
  64113. }
  64114. /*
  64115. ** Free the indentation structure
  64116. */
  64117. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  64118. if( pVdbe && pVdbe->pExplain ){
  64119. sqlite3_free(pVdbe->zExplain);
  64120. sqlite3ExplainNL(pVdbe);
  64121. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  64122. sqlite3_free(pVdbe->pExplain);
  64123. pVdbe->pExplain = 0;
  64124. sqlite3EndBenignMalloc();
  64125. }
  64126. }
  64127. /*
  64128. ** Return the explanation of a virtual machine.
  64129. */
  64130. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  64131. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  64132. }
  64133. #endif /* defined(SQLITE_DEBUG) */
  64134. /************** End of vdbetrace.c *******************************************/
  64135. /************** Begin file vdbe.c ********************************************/
  64136. /*
  64137. ** 2001 September 15
  64138. **
  64139. ** The author disclaims copyright to this source code. In place of
  64140. ** a legal notice, here is a blessing:
  64141. **
  64142. ** May you do good and not evil.
  64143. ** May you find forgiveness for yourself and forgive others.
  64144. ** May you share freely, never taking more than you give.
  64145. **
  64146. *************************************************************************
  64147. ** The code in this file implements execution method of the
  64148. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  64149. ** handles housekeeping details such as creating and deleting
  64150. ** VDBE instances. This file is solely interested in executing
  64151. ** the VDBE program.
  64152. **
  64153. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  64154. ** to a VDBE.
  64155. **
  64156. ** The SQL parser generates a program which is then executed by
  64157. ** the VDBE to do the work of the SQL statement. VDBE programs are
  64158. ** similar in form to assembly language. The program consists of
  64159. ** a linear sequence of operations. Each operation has an opcode
  64160. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  64161. ** is a null-terminated string. Operand P5 is an unsigned character.
  64162. ** Few opcodes use all 5 operands.
  64163. **
  64164. ** Computation results are stored on a set of registers numbered beginning
  64165. ** with 1 and going up to Vdbe.nMem. Each register can store
  64166. ** either an integer, a null-terminated string, a floating point
  64167. ** number, or the SQL "NULL" value. An implicit conversion from one
  64168. ** type to the other occurs as necessary.
  64169. **
  64170. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  64171. ** function which does the work of interpreting a VDBE program.
  64172. ** But other routines are also provided to help in building up
  64173. ** a program instruction by instruction.
  64174. **
  64175. ** Various scripts scan this source file in order to generate HTML
  64176. ** documentation, headers files, or other derived files. The formatting
  64177. ** of the code in this file is, therefore, important. See other comments
  64178. ** in this file for details. If in doubt, do not deviate from existing
  64179. ** commenting and indentation practices when changing or adding code.
  64180. */
  64181. /*
  64182. ** Invoke this macro on memory cells just prior to changing the
  64183. ** value of the cell. This macro verifies that shallow copies are
  64184. ** not misused.
  64185. */
  64186. #ifdef SQLITE_DEBUG
  64187. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  64188. #else
  64189. # define memAboutToChange(P,M)
  64190. #endif
  64191. /*
  64192. ** The following global variable is incremented every time a cursor
  64193. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  64194. ** procedures use this information to make sure that indices are
  64195. ** working correctly. This variable has no function other than to
  64196. ** help verify the correct operation of the library.
  64197. */
  64198. #ifdef SQLITE_TEST
  64199. SQLITE_API int sqlite3_search_count = 0;
  64200. #endif
  64201. /*
  64202. ** When this global variable is positive, it gets decremented once before
  64203. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  64204. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  64205. **
  64206. ** This facility is used for testing purposes only. It does not function
  64207. ** in an ordinary build.
  64208. */
  64209. #ifdef SQLITE_TEST
  64210. SQLITE_API int sqlite3_interrupt_count = 0;
  64211. #endif
  64212. /*
  64213. ** The next global variable is incremented each type the OP_Sort opcode
  64214. ** is executed. The test procedures use this information to make sure that
  64215. ** sorting is occurring or not occurring at appropriate times. This variable
  64216. ** has no function other than to help verify the correct operation of the
  64217. ** library.
  64218. */
  64219. #ifdef SQLITE_TEST
  64220. SQLITE_API int sqlite3_sort_count = 0;
  64221. #endif
  64222. /*
  64223. ** The next global variable records the size of the largest MEM_Blob
  64224. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  64225. ** use this information to make sure that the zero-blob functionality
  64226. ** is working correctly. This variable has no function other than to
  64227. ** help verify the correct operation of the library.
  64228. */
  64229. #ifdef SQLITE_TEST
  64230. SQLITE_API int sqlite3_max_blobsize = 0;
  64231. static void updateMaxBlobsize(Mem *p){
  64232. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  64233. sqlite3_max_blobsize = p->n;
  64234. }
  64235. }
  64236. #endif
  64237. /*
  64238. ** The next global variable is incremented each type the OP_Found opcode
  64239. ** is executed. This is used to test whether or not the foreign key
  64240. ** operation implemented using OP_FkIsZero is working. This variable
  64241. ** has no function other than to help verify the correct operation of the
  64242. ** library.
  64243. */
  64244. #ifdef SQLITE_TEST
  64245. SQLITE_API int sqlite3_found_count = 0;
  64246. #endif
  64247. /*
  64248. ** Test a register to see if it exceeds the current maximum blob size.
  64249. ** If it does, record the new maximum blob size.
  64250. */
  64251. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  64252. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  64253. #else
  64254. # define UPDATE_MAX_BLOBSIZE(P)
  64255. #endif
  64256. /*
  64257. ** Convert the given register into a string if it isn't one
  64258. ** already. Return non-zero if a malloc() fails.
  64259. */
  64260. #define Stringify(P, enc) \
  64261. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  64262. { goto no_mem; }
  64263. /*
  64264. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  64265. ** a pointer to a dynamically allocated string where some other entity
  64266. ** is responsible for deallocating that string. Because the register
  64267. ** does not control the string, it might be deleted without the register
  64268. ** knowing it.
  64269. **
  64270. ** This routine converts an ephemeral string into a dynamically allocated
  64271. ** string that the register itself controls. In other words, it
  64272. ** converts an MEM_Ephem string into an MEM_Dyn string.
  64273. */
  64274. #define Deephemeralize(P) \
  64275. if( ((P)->flags&MEM_Ephem)!=0 \
  64276. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  64277. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  64278. # define isSorter(x) ((x)->pSorter!=0)
  64279. /*
  64280. ** Argument pMem points at a register that will be passed to a
  64281. ** user-defined function or returned to the user as the result of a query.
  64282. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  64283. ** routines.
  64284. */
  64285. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  64286. int flags = pMem->flags;
  64287. if( flags & MEM_Null ){
  64288. pMem->type = SQLITE_NULL;
  64289. }
  64290. else if( flags & MEM_Int ){
  64291. pMem->type = SQLITE_INTEGER;
  64292. }
  64293. else if( flags & MEM_Real ){
  64294. pMem->type = SQLITE_FLOAT;
  64295. }
  64296. else if( flags & MEM_Str ){
  64297. pMem->type = SQLITE_TEXT;
  64298. }else{
  64299. pMem->type = SQLITE_BLOB;
  64300. }
  64301. }
  64302. /*
  64303. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  64304. ** if we run out of memory.
  64305. */
  64306. static VdbeCursor *allocateCursor(
  64307. Vdbe *p, /* The virtual machine */
  64308. int iCur, /* Index of the new VdbeCursor */
  64309. int nField, /* Number of fields in the table or index */
  64310. int iDb, /* Database the cursor belongs to, or -1 */
  64311. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  64312. ){
  64313. /* Find the memory cell that will be used to store the blob of memory
  64314. ** required for this VdbeCursor structure. It is convenient to use a
  64315. ** vdbe memory cell to manage the memory allocation required for a
  64316. ** VdbeCursor structure for the following reasons:
  64317. **
  64318. ** * Sometimes cursor numbers are used for a couple of different
  64319. ** purposes in a vdbe program. The different uses might require
  64320. ** different sized allocations. Memory cells provide growable
  64321. ** allocations.
  64322. **
  64323. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  64324. ** be freed lazily via the sqlite3_release_memory() API. This
  64325. ** minimizes the number of malloc calls made by the system.
  64326. **
  64327. ** Memory cells for cursors are allocated at the top of the address
  64328. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  64329. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  64330. */
  64331. Mem *pMem = &p->aMem[p->nMem-iCur];
  64332. int nByte;
  64333. VdbeCursor *pCx = 0;
  64334. nByte =
  64335. ROUND8(sizeof(VdbeCursor)) +
  64336. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  64337. 2*nField*sizeof(u32);
  64338. assert( iCur<p->nCursor );
  64339. if( p->apCsr[iCur] ){
  64340. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  64341. p->apCsr[iCur] = 0;
  64342. }
  64343. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  64344. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  64345. memset(pCx, 0, sizeof(VdbeCursor));
  64346. pCx->iDb = iDb;
  64347. pCx->nField = nField;
  64348. if( nField ){
  64349. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  64350. }
  64351. if( isBtreeCursor ){
  64352. pCx->pCursor = (BtCursor*)
  64353. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  64354. sqlite3BtreeCursorZero(pCx->pCursor);
  64355. }
  64356. }
  64357. return pCx;
  64358. }
  64359. /*
  64360. ** Try to convert a value into a numeric representation if we can
  64361. ** do so without loss of information. In other words, if the string
  64362. ** looks like a number, convert it into a number. If it does not
  64363. ** look like a number, leave it alone.
  64364. */
  64365. static void applyNumericAffinity(Mem *pRec){
  64366. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  64367. double rValue;
  64368. i64 iValue;
  64369. u8 enc = pRec->enc;
  64370. if( (pRec->flags&MEM_Str)==0 ) return;
  64371. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  64372. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  64373. pRec->u.i = iValue;
  64374. pRec->flags |= MEM_Int;
  64375. }else{
  64376. pRec->r = rValue;
  64377. pRec->flags |= MEM_Real;
  64378. }
  64379. }
  64380. }
  64381. /*
  64382. ** Processing is determine by the affinity parameter:
  64383. **
  64384. ** SQLITE_AFF_INTEGER:
  64385. ** SQLITE_AFF_REAL:
  64386. ** SQLITE_AFF_NUMERIC:
  64387. ** Try to convert pRec to an integer representation or a
  64388. ** floating-point representation if an integer representation
  64389. ** is not possible. Note that the integer representation is
  64390. ** always preferred, even if the affinity is REAL, because
  64391. ** an integer representation is more space efficient on disk.
  64392. **
  64393. ** SQLITE_AFF_TEXT:
  64394. ** Convert pRec to a text representation.
  64395. **
  64396. ** SQLITE_AFF_NONE:
  64397. ** No-op. pRec is unchanged.
  64398. */
  64399. static void applyAffinity(
  64400. Mem *pRec, /* The value to apply affinity to */
  64401. char affinity, /* The affinity to be applied */
  64402. u8 enc /* Use this text encoding */
  64403. ){
  64404. if( affinity==SQLITE_AFF_TEXT ){
  64405. /* Only attempt the conversion to TEXT if there is an integer or real
  64406. ** representation (blob and NULL do not get converted) but no string
  64407. ** representation.
  64408. */
  64409. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  64410. sqlite3VdbeMemStringify(pRec, enc);
  64411. }
  64412. pRec->flags &= ~(MEM_Real|MEM_Int);
  64413. }else if( affinity!=SQLITE_AFF_NONE ){
  64414. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  64415. || affinity==SQLITE_AFF_NUMERIC );
  64416. applyNumericAffinity(pRec);
  64417. if( pRec->flags & MEM_Real ){
  64418. sqlite3VdbeIntegerAffinity(pRec);
  64419. }
  64420. }
  64421. }
  64422. /*
  64423. ** Try to convert the type of a function argument or a result column
  64424. ** into a numeric representation. Use either INTEGER or REAL whichever
  64425. ** is appropriate. But only do the conversion if it is possible without
  64426. ** loss of information and return the revised type of the argument.
  64427. */
  64428. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  64429. Mem *pMem = (Mem*)pVal;
  64430. if( pMem->type==SQLITE_TEXT ){
  64431. applyNumericAffinity(pMem);
  64432. sqlite3VdbeMemStoreType(pMem);
  64433. }
  64434. return pMem->type;
  64435. }
  64436. /*
  64437. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  64438. ** not the internal Mem* type.
  64439. */
  64440. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  64441. sqlite3_value *pVal,
  64442. u8 affinity,
  64443. u8 enc
  64444. ){
  64445. applyAffinity((Mem *)pVal, affinity, enc);
  64446. }
  64447. #ifdef SQLITE_DEBUG
  64448. /*
  64449. ** Write a nice string representation of the contents of cell pMem
  64450. ** into buffer zBuf, length nBuf.
  64451. */
  64452. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  64453. char *zCsr = zBuf;
  64454. int f = pMem->flags;
  64455. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  64456. if( f&MEM_Blob ){
  64457. int i;
  64458. char c;
  64459. if( f & MEM_Dyn ){
  64460. c = 'z';
  64461. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64462. }else if( f & MEM_Static ){
  64463. c = 't';
  64464. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64465. }else if( f & MEM_Ephem ){
  64466. c = 'e';
  64467. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64468. }else{
  64469. c = 's';
  64470. }
  64471. sqlite3_snprintf(100, zCsr, "%c", c);
  64472. zCsr += sqlite3Strlen30(zCsr);
  64473. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  64474. zCsr += sqlite3Strlen30(zCsr);
  64475. for(i=0; i<16 && i<pMem->n; i++){
  64476. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  64477. zCsr += sqlite3Strlen30(zCsr);
  64478. }
  64479. for(i=0; i<16 && i<pMem->n; i++){
  64480. char z = pMem->z[i];
  64481. if( z<32 || z>126 ) *zCsr++ = '.';
  64482. else *zCsr++ = z;
  64483. }
  64484. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  64485. zCsr += sqlite3Strlen30(zCsr);
  64486. if( f & MEM_Zero ){
  64487. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  64488. zCsr += sqlite3Strlen30(zCsr);
  64489. }
  64490. *zCsr = '\0';
  64491. }else if( f & MEM_Str ){
  64492. int j, k;
  64493. zBuf[0] = ' ';
  64494. if( f & MEM_Dyn ){
  64495. zBuf[1] = 'z';
  64496. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64497. }else if( f & MEM_Static ){
  64498. zBuf[1] = 't';
  64499. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64500. }else if( f & MEM_Ephem ){
  64501. zBuf[1] = 'e';
  64502. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64503. }else{
  64504. zBuf[1] = 's';
  64505. }
  64506. k = 2;
  64507. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  64508. k += sqlite3Strlen30(&zBuf[k]);
  64509. zBuf[k++] = '[';
  64510. for(j=0; j<15 && j<pMem->n; j++){
  64511. u8 c = pMem->z[j];
  64512. if( c>=0x20 && c<0x7f ){
  64513. zBuf[k++] = c;
  64514. }else{
  64515. zBuf[k++] = '.';
  64516. }
  64517. }
  64518. zBuf[k++] = ']';
  64519. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  64520. k += sqlite3Strlen30(&zBuf[k]);
  64521. zBuf[k++] = 0;
  64522. }
  64523. }
  64524. #endif
  64525. #ifdef SQLITE_DEBUG
  64526. /*
  64527. ** Print the value of a register for tracing purposes:
  64528. */
  64529. static void memTracePrint(FILE *out, Mem *p){
  64530. if( p->flags & MEM_Invalid ){
  64531. fprintf(out, " undefined");
  64532. }else if( p->flags & MEM_Null ){
  64533. fprintf(out, " NULL");
  64534. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  64535. fprintf(out, " si:%lld", p->u.i);
  64536. }else if( p->flags & MEM_Int ){
  64537. fprintf(out, " i:%lld", p->u.i);
  64538. #ifndef SQLITE_OMIT_FLOATING_POINT
  64539. }else if( p->flags & MEM_Real ){
  64540. fprintf(out, " r:%g", p->r);
  64541. #endif
  64542. }else if( p->flags & MEM_RowSet ){
  64543. fprintf(out, " (rowset)");
  64544. }else{
  64545. char zBuf[200];
  64546. sqlite3VdbeMemPrettyPrint(p, zBuf);
  64547. fprintf(out, " ");
  64548. fprintf(out, "%s", zBuf);
  64549. }
  64550. }
  64551. static void registerTrace(FILE *out, int iReg, Mem *p){
  64552. fprintf(out, "REG[%d] = ", iReg);
  64553. memTracePrint(out, p);
  64554. fprintf(out, "\n");
  64555. }
  64556. #endif
  64557. #ifdef SQLITE_DEBUG
  64558. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  64559. #else
  64560. # define REGISTER_TRACE(R,M)
  64561. #endif
  64562. #ifdef VDBE_PROFILE
  64563. /*
  64564. ** hwtime.h contains inline assembler code for implementing
  64565. ** high-performance timing routines.
  64566. */
  64567. /************** Include hwtime.h in the middle of vdbe.c *********************/
  64568. /************** Begin file hwtime.h ******************************************/
  64569. /*
  64570. ** 2008 May 27
  64571. **
  64572. ** The author disclaims copyright to this source code. In place of
  64573. ** a legal notice, here is a blessing:
  64574. **
  64575. ** May you do good and not evil.
  64576. ** May you find forgiveness for yourself and forgive others.
  64577. ** May you share freely, never taking more than you give.
  64578. **
  64579. ******************************************************************************
  64580. **
  64581. ** This file contains inline asm code for retrieving "high-performance"
  64582. ** counters for x86 class CPUs.
  64583. */
  64584. #ifndef _HWTIME_H_
  64585. #define _HWTIME_H_
  64586. /*
  64587. ** The following routine only works on pentium-class (or newer) processors.
  64588. ** It uses the RDTSC opcode to read the cycle count value out of the
  64589. ** processor and returns that value. This can be used for high-res
  64590. ** profiling.
  64591. */
  64592. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  64593. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  64594. #if defined(__GNUC__)
  64595. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64596. unsigned int lo, hi;
  64597. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  64598. return (sqlite_uint64)hi << 32 | lo;
  64599. }
  64600. #elif defined(_MSC_VER)
  64601. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  64602. __asm {
  64603. rdtsc
  64604. ret ; return value at EDX:EAX
  64605. }
  64606. }
  64607. #endif
  64608. #elif (defined(__GNUC__) && defined(__x86_64__))
  64609. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64610. unsigned long val;
  64611. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  64612. return val;
  64613. }
  64614. #elif (defined(__GNUC__) && defined(__ppc__))
  64615. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64616. unsigned long long retval;
  64617. unsigned long junk;
  64618. __asm__ __volatile__ ("\n\
  64619. 1: mftbu %1\n\
  64620. mftb %L0\n\
  64621. mftbu %0\n\
  64622. cmpw %0,%1\n\
  64623. bne 1b"
  64624. : "=r" (retval), "=r" (junk));
  64625. return retval;
  64626. }
  64627. #else
  64628. #error Need implementation of sqlite3Hwtime() for your platform.
  64629. /*
  64630. ** To compile without implementing sqlite3Hwtime() for your platform,
  64631. ** you can remove the above #error and use the following
  64632. ** stub function. You will lose timing support for many
  64633. ** of the debugging and testing utilities, but it should at
  64634. ** least compile and run.
  64635. */
  64636. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  64637. #endif
  64638. #endif /* !defined(_HWTIME_H_) */
  64639. /************** End of hwtime.h **********************************************/
  64640. /************** Continuing where we left off in vdbe.c ***********************/
  64641. #endif
  64642. /*
  64643. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  64644. ** sqlite3_interrupt() routine has been called. If it has been, then
  64645. ** processing of the VDBE program is interrupted.
  64646. **
  64647. ** This macro added to every instruction that does a jump in order to
  64648. ** implement a loop. This test used to be on every single instruction,
  64649. ** but that meant we more testing than we needed. By only testing the
  64650. ** flag on jump instructions, we get a (small) speed improvement.
  64651. */
  64652. #define CHECK_FOR_INTERRUPT \
  64653. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  64654. #ifndef NDEBUG
  64655. /*
  64656. ** This function is only called from within an assert() expression. It
  64657. ** checks that the sqlite3.nTransaction variable is correctly set to
  64658. ** the number of non-transaction savepoints currently in the
  64659. ** linked list starting at sqlite3.pSavepoint.
  64660. **
  64661. ** Usage:
  64662. **
  64663. ** assert( checkSavepointCount(db) );
  64664. */
  64665. static int checkSavepointCount(sqlite3 *db){
  64666. int n = 0;
  64667. Savepoint *p;
  64668. for(p=db->pSavepoint; p; p=p->pNext) n++;
  64669. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  64670. return 1;
  64671. }
  64672. #endif
  64673. /*
  64674. ** Execute as much of a VDBE program as we can then return.
  64675. **
  64676. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  64677. ** close the program with a final OP_Halt and to set up the callbacks
  64678. ** and the error message pointer.
  64679. **
  64680. ** Whenever a row or result data is available, this routine will either
  64681. ** invoke the result callback (if there is one) or return with
  64682. ** SQLITE_ROW.
  64683. **
  64684. ** If an attempt is made to open a locked database, then this routine
  64685. ** will either invoke the busy callback (if there is one) or it will
  64686. ** return SQLITE_BUSY.
  64687. **
  64688. ** If an error occurs, an error message is written to memory obtained
  64689. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  64690. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  64691. **
  64692. ** If the callback ever returns non-zero, then the program exits
  64693. ** immediately. There will be no error message but the p->rc field is
  64694. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  64695. **
  64696. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  64697. ** routine to return SQLITE_ERROR.
  64698. **
  64699. ** Other fatal errors return SQLITE_ERROR.
  64700. **
  64701. ** After this routine has finished, sqlite3VdbeFinalize() should be
  64702. ** used to clean up the mess that was left behind.
  64703. */
  64704. SQLITE_PRIVATE int sqlite3VdbeExec(
  64705. Vdbe *p /* The VDBE */
  64706. ){
  64707. int pc=0; /* The program counter */
  64708. Op *aOp = p->aOp; /* Copy of p->aOp */
  64709. Op *pOp; /* Current operation */
  64710. int rc = SQLITE_OK; /* Value to return */
  64711. sqlite3 *db = p->db; /* The database */
  64712. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  64713. u8 encoding = ENC(db); /* The database encoding */
  64714. int iCompare = 0; /* Result of last OP_Compare operation */
  64715. unsigned nVmStep = 0; /* Number of virtual machine steps */
  64716. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  64717. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  64718. #endif
  64719. Mem *aMem = p->aMem; /* Copy of p->aMem */
  64720. Mem *pIn1 = 0; /* 1st input operand */
  64721. Mem *pIn2 = 0; /* 2nd input operand */
  64722. Mem *pIn3 = 0; /* 3rd input operand */
  64723. Mem *pOut = 0; /* Output operand */
  64724. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  64725. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  64726. #ifdef VDBE_PROFILE
  64727. u64 start; /* CPU clock count at start of opcode */
  64728. int origPc; /* Program counter at start of opcode */
  64729. #endif
  64730. /********************************************************************
  64731. ** Automatically generated code
  64732. **
  64733. ** The following union is automatically generated by the
  64734. ** vdbe-compress.tcl script. The purpose of this union is to
  64735. ** reduce the amount of stack space required by this function.
  64736. ** See comments in the vdbe-compress.tcl script for details.
  64737. */
  64738. union vdbeExecUnion {
  64739. struct OP_Yield_stack_vars {
  64740. int pcDest;
  64741. } aa;
  64742. struct OP_Null_stack_vars {
  64743. int cnt;
  64744. u16 nullFlag;
  64745. } ab;
  64746. struct OP_Variable_stack_vars {
  64747. Mem *pVar; /* Value being transferred */
  64748. } ac;
  64749. struct OP_Move_stack_vars {
  64750. char *zMalloc; /* Holding variable for allocated memory */
  64751. int n; /* Number of registers left to copy */
  64752. int p1; /* Register to copy from */
  64753. int p2; /* Register to copy to */
  64754. } ad;
  64755. struct OP_Copy_stack_vars {
  64756. int n;
  64757. } ae;
  64758. struct OP_ResultRow_stack_vars {
  64759. Mem *pMem;
  64760. int i;
  64761. } af;
  64762. struct OP_Concat_stack_vars {
  64763. i64 nByte;
  64764. } ag;
  64765. struct OP_Remainder_stack_vars {
  64766. char bIntint; /* Started out as two integer operands */
  64767. int flags; /* Combined MEM_* flags from both inputs */
  64768. i64 iA; /* Integer value of left operand */
  64769. i64 iB; /* Integer value of right operand */
  64770. double rA; /* Real value of left operand */
  64771. double rB; /* Real value of right operand */
  64772. } ah;
  64773. struct OP_Function_stack_vars {
  64774. int i;
  64775. Mem *pArg;
  64776. sqlite3_context ctx;
  64777. sqlite3_value **apVal;
  64778. int n;
  64779. } ai;
  64780. struct OP_ShiftRight_stack_vars {
  64781. i64 iA;
  64782. u64 uA;
  64783. i64 iB;
  64784. u8 op;
  64785. } aj;
  64786. struct OP_Ge_stack_vars {
  64787. int res; /* Result of the comparison of pIn1 against pIn3 */
  64788. char affinity; /* Affinity to use for comparison */
  64789. u16 flags1; /* Copy of initial value of pIn1->flags */
  64790. u16 flags3; /* Copy of initial value of pIn3->flags */
  64791. } ak;
  64792. struct OP_Compare_stack_vars {
  64793. int n;
  64794. int i;
  64795. int p1;
  64796. int p2;
  64797. const KeyInfo *pKeyInfo;
  64798. int idx;
  64799. CollSeq *pColl; /* Collating sequence to use on this term */
  64800. int bRev; /* True for DESCENDING sort order */
  64801. } al;
  64802. struct OP_Or_stack_vars {
  64803. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  64804. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  64805. } am;
  64806. struct OP_IfNot_stack_vars {
  64807. int c;
  64808. } an;
  64809. struct OP_Column_stack_vars {
  64810. u32 payloadSize; /* Number of bytes in the record */
  64811. i64 payloadSize64; /* Number of bytes in the record */
  64812. int p1; /* P1 value of the opcode */
  64813. int p2; /* column number to retrieve */
  64814. VdbeCursor *pC; /* The VDBE cursor */
  64815. char *zRec; /* Pointer to complete record-data */
  64816. BtCursor *pCrsr; /* The BTree cursor */
  64817. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  64818. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  64819. int nField; /* number of fields in the record */
  64820. int len; /* The length of the serialized data for the column */
  64821. int i; /* Loop counter */
  64822. char *zData; /* Part of the record being decoded */
  64823. Mem *pDest; /* Where to write the extracted value */
  64824. Mem sMem; /* For storing the record being decoded */
  64825. u8 *zIdx; /* Index into header */
  64826. u8 *zEndHdr; /* Pointer to first byte after the header */
  64827. u32 offset; /* Offset into the data */
  64828. u32 szField; /* Number of bytes in the content of a field */
  64829. int szHdr; /* Size of the header size field at start of record */
  64830. int avail; /* Number of bytes of available data */
  64831. u32 t; /* A type code from the record header */
  64832. Mem *pReg; /* PseudoTable input register */
  64833. } ao;
  64834. struct OP_Affinity_stack_vars {
  64835. const char *zAffinity; /* The affinity to be applied */
  64836. char cAff; /* A single character of affinity */
  64837. } ap;
  64838. struct OP_MakeRecord_stack_vars {
  64839. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  64840. Mem *pRec; /* The new record */
  64841. u64 nData; /* Number of bytes of data space */
  64842. int nHdr; /* Number of bytes of header space */
  64843. i64 nByte; /* Data space required for this record */
  64844. int nZero; /* Number of zero bytes at the end of the record */
  64845. int nVarint; /* Number of bytes in a varint */
  64846. u32 serial_type; /* Type field */
  64847. Mem *pData0; /* First field to be combined into the record */
  64848. Mem *pLast; /* Last field of the record */
  64849. int nField; /* Number of fields in the record */
  64850. char *zAffinity; /* The affinity string for the record */
  64851. int file_format; /* File format to use for encoding */
  64852. int i; /* Space used in zNewRecord[] */
  64853. int len; /* Length of a field */
  64854. } aq;
  64855. struct OP_Count_stack_vars {
  64856. i64 nEntry;
  64857. BtCursor *pCrsr;
  64858. } ar;
  64859. struct OP_Savepoint_stack_vars {
  64860. int p1; /* Value of P1 operand */
  64861. char *zName; /* Name of savepoint */
  64862. int nName;
  64863. Savepoint *pNew;
  64864. Savepoint *pSavepoint;
  64865. Savepoint *pTmp;
  64866. int iSavepoint;
  64867. int ii;
  64868. } as;
  64869. struct OP_AutoCommit_stack_vars {
  64870. int desiredAutoCommit;
  64871. int iRollback;
  64872. int turnOnAC;
  64873. } at;
  64874. struct OP_Transaction_stack_vars {
  64875. Btree *pBt;
  64876. } au;
  64877. struct OP_ReadCookie_stack_vars {
  64878. int iMeta;
  64879. int iDb;
  64880. int iCookie;
  64881. } av;
  64882. struct OP_SetCookie_stack_vars {
  64883. Db *pDb;
  64884. } aw;
  64885. struct OP_VerifyCookie_stack_vars {
  64886. int iMeta;
  64887. int iGen;
  64888. Btree *pBt;
  64889. } ax;
  64890. struct OP_OpenWrite_stack_vars {
  64891. int nField;
  64892. KeyInfo *pKeyInfo;
  64893. int p2;
  64894. int iDb;
  64895. int wrFlag;
  64896. Btree *pX;
  64897. VdbeCursor *pCur;
  64898. Db *pDb;
  64899. } ay;
  64900. struct OP_OpenEphemeral_stack_vars {
  64901. VdbeCursor *pCx;
  64902. } az;
  64903. struct OP_SorterOpen_stack_vars {
  64904. VdbeCursor *pCx;
  64905. } ba;
  64906. struct OP_OpenPseudo_stack_vars {
  64907. VdbeCursor *pCx;
  64908. } bb;
  64909. struct OP_SeekGt_stack_vars {
  64910. int res;
  64911. int oc;
  64912. VdbeCursor *pC;
  64913. UnpackedRecord r;
  64914. int nField;
  64915. i64 iKey; /* The rowid we are to seek to */
  64916. } bc;
  64917. struct OP_Seek_stack_vars {
  64918. VdbeCursor *pC;
  64919. } bd;
  64920. struct OP_Found_stack_vars {
  64921. int alreadyExists;
  64922. VdbeCursor *pC;
  64923. int res;
  64924. char *pFree;
  64925. UnpackedRecord *pIdxKey;
  64926. UnpackedRecord r;
  64927. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  64928. } be;
  64929. struct OP_IsUnique_stack_vars {
  64930. u16 ii;
  64931. VdbeCursor *pCx;
  64932. BtCursor *pCrsr;
  64933. u16 nField;
  64934. Mem *aMx;
  64935. UnpackedRecord r; /* B-Tree index search key */
  64936. i64 R; /* Rowid stored in register P3 */
  64937. } bf;
  64938. struct OP_NotExists_stack_vars {
  64939. VdbeCursor *pC;
  64940. BtCursor *pCrsr;
  64941. int res;
  64942. u64 iKey;
  64943. } bg;
  64944. struct OP_NewRowid_stack_vars {
  64945. i64 v; /* The new rowid */
  64946. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  64947. int res; /* Result of an sqlite3BtreeLast() */
  64948. int cnt; /* Counter to limit the number of searches */
  64949. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  64950. VdbeFrame *pFrame; /* Root frame of VDBE */
  64951. } bh;
  64952. struct OP_InsertInt_stack_vars {
  64953. Mem *pData; /* MEM cell holding data for the record to be inserted */
  64954. Mem *pKey; /* MEM cell holding key for the record */
  64955. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  64956. VdbeCursor *pC; /* Cursor to table into which insert is written */
  64957. int nZero; /* Number of zero-bytes to append */
  64958. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  64959. const char *zDb; /* database name - used by the update hook */
  64960. const char *zTbl; /* Table name - used by the opdate hook */
  64961. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  64962. } bi;
  64963. struct OP_Delete_stack_vars {
  64964. i64 iKey;
  64965. VdbeCursor *pC;
  64966. } bj;
  64967. struct OP_SorterCompare_stack_vars {
  64968. VdbeCursor *pC;
  64969. int res;
  64970. } bk;
  64971. struct OP_SorterData_stack_vars {
  64972. VdbeCursor *pC;
  64973. } bl;
  64974. struct OP_RowData_stack_vars {
  64975. VdbeCursor *pC;
  64976. BtCursor *pCrsr;
  64977. u32 n;
  64978. i64 n64;
  64979. } bm;
  64980. struct OP_Rowid_stack_vars {
  64981. VdbeCursor *pC;
  64982. i64 v;
  64983. sqlite3_vtab *pVtab;
  64984. const sqlite3_module *pModule;
  64985. } bn;
  64986. struct OP_NullRow_stack_vars {
  64987. VdbeCursor *pC;
  64988. } bo;
  64989. struct OP_Last_stack_vars {
  64990. VdbeCursor *pC;
  64991. BtCursor *pCrsr;
  64992. int res;
  64993. } bp;
  64994. struct OP_Rewind_stack_vars {
  64995. VdbeCursor *pC;
  64996. BtCursor *pCrsr;
  64997. int res;
  64998. } bq;
  64999. struct OP_Next_stack_vars {
  65000. VdbeCursor *pC;
  65001. int res;
  65002. } br;
  65003. struct OP_IdxInsert_stack_vars {
  65004. VdbeCursor *pC;
  65005. BtCursor *pCrsr;
  65006. int nKey;
  65007. const char *zKey;
  65008. } bs;
  65009. struct OP_IdxDelete_stack_vars {
  65010. VdbeCursor *pC;
  65011. BtCursor *pCrsr;
  65012. int res;
  65013. UnpackedRecord r;
  65014. } bt;
  65015. struct OP_IdxRowid_stack_vars {
  65016. BtCursor *pCrsr;
  65017. VdbeCursor *pC;
  65018. i64 rowid;
  65019. } bu;
  65020. struct OP_IdxGE_stack_vars {
  65021. VdbeCursor *pC;
  65022. int res;
  65023. UnpackedRecord r;
  65024. } bv;
  65025. struct OP_Destroy_stack_vars {
  65026. int iMoved;
  65027. int iCnt;
  65028. Vdbe *pVdbe;
  65029. int iDb;
  65030. } bw;
  65031. struct OP_Clear_stack_vars {
  65032. int nChange;
  65033. } bx;
  65034. struct OP_CreateTable_stack_vars {
  65035. int pgno;
  65036. int flags;
  65037. Db *pDb;
  65038. } by;
  65039. struct OP_ParseSchema_stack_vars {
  65040. int iDb;
  65041. const char *zMaster;
  65042. char *zSql;
  65043. InitData initData;
  65044. } bz;
  65045. struct OP_IntegrityCk_stack_vars {
  65046. int nRoot; /* Number of tables to check. (Number of root pages.) */
  65047. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  65048. int j; /* Loop counter */
  65049. int nErr; /* Number of errors reported */
  65050. char *z; /* Text of the error report */
  65051. Mem *pnErr; /* Register keeping track of errors remaining */
  65052. } ca;
  65053. struct OP_RowSetRead_stack_vars {
  65054. i64 val;
  65055. } cb;
  65056. struct OP_RowSetTest_stack_vars {
  65057. int iSet;
  65058. int exists;
  65059. } cc;
  65060. struct OP_Program_stack_vars {
  65061. int nMem; /* Number of memory registers for sub-program */
  65062. int nByte; /* Bytes of runtime space required for sub-program */
  65063. Mem *pRt; /* Register to allocate runtime space */
  65064. Mem *pMem; /* Used to iterate through memory cells */
  65065. Mem *pEnd; /* Last memory cell in new array */
  65066. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  65067. SubProgram *pProgram; /* Sub-program to execute */
  65068. void *t; /* Token identifying trigger */
  65069. } cd;
  65070. struct OP_Param_stack_vars {
  65071. VdbeFrame *pFrame;
  65072. Mem *pIn;
  65073. } ce;
  65074. struct OP_MemMax_stack_vars {
  65075. Mem *pIn1;
  65076. VdbeFrame *pFrame;
  65077. } cf;
  65078. struct OP_AggStep_stack_vars {
  65079. int n;
  65080. int i;
  65081. Mem *pMem;
  65082. Mem *pRec;
  65083. sqlite3_context ctx;
  65084. sqlite3_value **apVal;
  65085. } cg;
  65086. struct OP_AggFinal_stack_vars {
  65087. Mem *pMem;
  65088. } ch;
  65089. struct OP_Checkpoint_stack_vars {
  65090. int i; /* Loop counter */
  65091. int aRes[3]; /* Results */
  65092. Mem *pMem; /* Write results here */
  65093. } ci;
  65094. struct OP_JournalMode_stack_vars {
  65095. Btree *pBt; /* Btree to change journal mode of */
  65096. Pager *pPager; /* Pager associated with pBt */
  65097. int eNew; /* New journal mode */
  65098. int eOld; /* The old journal mode */
  65099. #ifndef SQLITE_OMIT_WAL
  65100. const char *zFilename; /* Name of database file for pPager */
  65101. #endif
  65102. } cj;
  65103. struct OP_IncrVacuum_stack_vars {
  65104. Btree *pBt;
  65105. } ck;
  65106. struct OP_VBegin_stack_vars {
  65107. VTable *pVTab;
  65108. } cl;
  65109. struct OP_VOpen_stack_vars {
  65110. VdbeCursor *pCur;
  65111. sqlite3_vtab_cursor *pVtabCursor;
  65112. sqlite3_vtab *pVtab;
  65113. sqlite3_module *pModule;
  65114. } cm;
  65115. struct OP_VFilter_stack_vars {
  65116. int nArg;
  65117. int iQuery;
  65118. const sqlite3_module *pModule;
  65119. Mem *pQuery;
  65120. Mem *pArgc;
  65121. sqlite3_vtab_cursor *pVtabCursor;
  65122. sqlite3_vtab *pVtab;
  65123. VdbeCursor *pCur;
  65124. int res;
  65125. int i;
  65126. Mem **apArg;
  65127. } cn;
  65128. struct OP_VColumn_stack_vars {
  65129. sqlite3_vtab *pVtab;
  65130. const sqlite3_module *pModule;
  65131. Mem *pDest;
  65132. sqlite3_context sContext;
  65133. } co;
  65134. struct OP_VNext_stack_vars {
  65135. sqlite3_vtab *pVtab;
  65136. const sqlite3_module *pModule;
  65137. int res;
  65138. VdbeCursor *pCur;
  65139. } cp;
  65140. struct OP_VRename_stack_vars {
  65141. sqlite3_vtab *pVtab;
  65142. Mem *pName;
  65143. } cq;
  65144. struct OP_VUpdate_stack_vars {
  65145. sqlite3_vtab *pVtab;
  65146. sqlite3_module *pModule;
  65147. int nArg;
  65148. int i;
  65149. sqlite_int64 rowid;
  65150. Mem **apArg;
  65151. Mem *pX;
  65152. } cr;
  65153. struct OP_Trace_stack_vars {
  65154. char *zTrace;
  65155. char *z;
  65156. } cs;
  65157. } u;
  65158. /* End automatically generated code
  65159. ********************************************************************/
  65160. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  65161. sqlite3VdbeEnter(p);
  65162. if( p->rc==SQLITE_NOMEM ){
  65163. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  65164. ** sqlite3_column_text16() failed. */
  65165. goto no_mem;
  65166. }
  65167. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  65168. assert( p->bIsReader || p->readOnly!=0 );
  65169. p->rc = SQLITE_OK;
  65170. p->iCurrentTime = 0;
  65171. assert( p->explain==0 );
  65172. p->pResultSet = 0;
  65173. db->busyHandler.nBusy = 0;
  65174. CHECK_FOR_INTERRUPT;
  65175. sqlite3VdbeIOTraceSql(p);
  65176. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65177. if( db->xProgress ){
  65178. assert( 0 < db->nProgressOps );
  65179. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  65180. if( nProgressLimit==0 ){
  65181. nProgressLimit = db->nProgressOps;
  65182. }else{
  65183. nProgressLimit %= (unsigned)db->nProgressOps;
  65184. }
  65185. }
  65186. #endif
  65187. #ifdef SQLITE_DEBUG
  65188. sqlite3BeginBenignMalloc();
  65189. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  65190. int i;
  65191. printf("VDBE Program Listing:\n");
  65192. sqlite3VdbePrintSql(p);
  65193. for(i=0; i<p->nOp; i++){
  65194. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  65195. }
  65196. }
  65197. sqlite3EndBenignMalloc();
  65198. #endif
  65199. for(pc=p->pc; rc==SQLITE_OK; pc++){
  65200. assert( pc>=0 && pc<p->nOp );
  65201. if( db->mallocFailed ) goto no_mem;
  65202. #ifdef VDBE_PROFILE
  65203. origPc = pc;
  65204. start = sqlite3Hwtime();
  65205. #endif
  65206. nVmStep++;
  65207. pOp = &aOp[pc];
  65208. /* Only allow tracing if SQLITE_DEBUG is defined.
  65209. */
  65210. #ifdef SQLITE_DEBUG
  65211. if( p->trace ){
  65212. if( pc==0 ){
  65213. printf("VDBE Execution Trace:\n");
  65214. sqlite3VdbePrintSql(p);
  65215. }
  65216. sqlite3VdbePrintOp(p->trace, pc, pOp);
  65217. }
  65218. #endif
  65219. /* Check to see if we need to simulate an interrupt. This only happens
  65220. ** if we have a special test build.
  65221. */
  65222. #ifdef SQLITE_TEST
  65223. if( sqlite3_interrupt_count>0 ){
  65224. sqlite3_interrupt_count--;
  65225. if( sqlite3_interrupt_count==0 ){
  65226. sqlite3_interrupt(db);
  65227. }
  65228. }
  65229. #endif
  65230. /* On any opcode with the "out2-prerelease" tag, free any
  65231. ** external allocations out of mem[p2] and set mem[p2] to be
  65232. ** an undefined integer. Opcodes will either fill in the integer
  65233. ** value or convert mem[p2] to a different type.
  65234. */
  65235. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  65236. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  65237. assert( pOp->p2>0 );
  65238. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65239. pOut = &aMem[pOp->p2];
  65240. memAboutToChange(p, pOut);
  65241. VdbeMemRelease(pOut);
  65242. pOut->flags = MEM_Int;
  65243. }
  65244. /* Sanity checking on other operands */
  65245. #ifdef SQLITE_DEBUG
  65246. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  65247. assert( pOp->p1>0 );
  65248. assert( pOp->p1<=(p->nMem-p->nCursor) );
  65249. assert( memIsValid(&aMem[pOp->p1]) );
  65250. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  65251. }
  65252. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  65253. assert( pOp->p2>0 );
  65254. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65255. assert( memIsValid(&aMem[pOp->p2]) );
  65256. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  65257. }
  65258. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  65259. assert( pOp->p3>0 );
  65260. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65261. assert( memIsValid(&aMem[pOp->p3]) );
  65262. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  65263. }
  65264. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  65265. assert( pOp->p2>0 );
  65266. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65267. memAboutToChange(p, &aMem[pOp->p2]);
  65268. }
  65269. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  65270. assert( pOp->p3>0 );
  65271. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65272. memAboutToChange(p, &aMem[pOp->p3]);
  65273. }
  65274. #endif
  65275. switch( pOp->opcode ){
  65276. /*****************************************************************************
  65277. ** What follows is a massive switch statement where each case implements a
  65278. ** separate instruction in the virtual machine. If we follow the usual
  65279. ** indentation conventions, each case should be indented by 6 spaces. But
  65280. ** that is a lot of wasted space on the left margin. So the code within
  65281. ** the switch statement will break with convention and be flush-left. Another
  65282. ** big comment (similar to this one) will mark the point in the code where
  65283. ** we transition back to normal indentation.
  65284. **
  65285. ** The formatting of each case is important. The makefile for SQLite
  65286. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  65287. ** file looking for lines that begin with "case OP_". The opcodes.h files
  65288. ** will be filled with #defines that give unique integer values to each
  65289. ** opcode and the opcodes.c file is filled with an array of strings where
  65290. ** each string is the symbolic name for the corresponding opcode. If the
  65291. ** case statement is followed by a comment of the form "/# same as ... #/"
  65292. ** that comment is used to determine the particular value of the opcode.
  65293. **
  65294. ** Other keywords in the comment that follows each case are used to
  65295. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  65296. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  65297. ** the mkopcodeh.awk script for additional information.
  65298. **
  65299. ** Documentation about VDBE opcodes is generated by scanning this file
  65300. ** for lines of that contain "Opcode:". That line and all subsequent
  65301. ** comment lines are used in the generation of the opcode.html documentation
  65302. ** file.
  65303. **
  65304. ** SUMMARY:
  65305. **
  65306. ** Formatting is important to scripts that scan this file.
  65307. ** Do not deviate from the formatting style currently in use.
  65308. **
  65309. *****************************************************************************/
  65310. /* Opcode: Goto * P2 * * *
  65311. **
  65312. ** An unconditional jump to address P2.
  65313. ** The next instruction executed will be
  65314. ** the one at index P2 from the beginning of
  65315. ** the program.
  65316. */
  65317. case OP_Goto: { /* jump */
  65318. pc = pOp->p2 - 1;
  65319. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  65320. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  65321. ** completion. Check to see if sqlite3_interrupt() has been called
  65322. ** or if the progress callback needs to be invoked.
  65323. **
  65324. ** This code uses unstructured "goto" statements and does not look clean.
  65325. ** But that is not due to sloppy coding habits. The code is written this
  65326. ** way for performance, to avoid having to run the interrupt and progress
  65327. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  65328. ** faster according to "valgrind --tool=cachegrind" */
  65329. check_for_interrupt:
  65330. CHECK_FOR_INTERRUPT;
  65331. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65332. /* Call the progress callback if it is configured and the required number
  65333. ** of VDBE ops have been executed (either since this invocation of
  65334. ** sqlite3VdbeExec() or since last time the progress callback was called).
  65335. ** If the progress callback returns non-zero, exit the virtual machine with
  65336. ** a return code SQLITE_ABORT.
  65337. */
  65338. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  65339. int prc;
  65340. prc = db->xProgress(db->pProgressArg);
  65341. if( prc!=0 ){
  65342. rc = SQLITE_INTERRUPT;
  65343. goto vdbe_error_halt;
  65344. }
  65345. if( db->xProgress!=0 ){
  65346. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  65347. }
  65348. }
  65349. #endif
  65350. break;
  65351. }
  65352. /* Opcode: Gosub P1 P2 * * *
  65353. **
  65354. ** Write the current address onto register P1
  65355. ** and then jump to address P2.
  65356. */
  65357. case OP_Gosub: { /* jump */
  65358. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65359. pIn1 = &aMem[pOp->p1];
  65360. assert( (pIn1->flags & MEM_Dyn)==0 );
  65361. memAboutToChange(p, pIn1);
  65362. pIn1->flags = MEM_Int;
  65363. pIn1->u.i = pc;
  65364. REGISTER_TRACE(pOp->p1, pIn1);
  65365. pc = pOp->p2 - 1;
  65366. break;
  65367. }
  65368. /* Opcode: Return P1 * * * *
  65369. **
  65370. ** Jump to the next instruction after the address in register P1.
  65371. */
  65372. case OP_Return: { /* in1 */
  65373. pIn1 = &aMem[pOp->p1];
  65374. assert( pIn1->flags & MEM_Int );
  65375. pc = (int)pIn1->u.i;
  65376. break;
  65377. }
  65378. /* Opcode: Yield P1 * * * *
  65379. **
  65380. ** Swap the program counter with the value in register P1.
  65381. */
  65382. case OP_Yield: { /* in1 */
  65383. #if 0 /* local variables moved into u.aa */
  65384. int pcDest;
  65385. #endif /* local variables moved into u.aa */
  65386. pIn1 = &aMem[pOp->p1];
  65387. assert( (pIn1->flags & MEM_Dyn)==0 );
  65388. pIn1->flags = MEM_Int;
  65389. u.aa.pcDest = (int)pIn1->u.i;
  65390. pIn1->u.i = pc;
  65391. REGISTER_TRACE(pOp->p1, pIn1);
  65392. pc = u.aa.pcDest;
  65393. break;
  65394. }
  65395. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  65396. **
  65397. ** Check the value in register P3. If it is NULL then Halt using
  65398. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  65399. ** value in register P3 is not NULL, then this routine is a no-op.
  65400. */
  65401. case OP_HaltIfNull: { /* in3 */
  65402. pIn3 = &aMem[pOp->p3];
  65403. if( (pIn3->flags & MEM_Null)==0 ) break;
  65404. /* Fall through into OP_Halt */
  65405. }
  65406. /* Opcode: Halt P1 P2 * P4 *
  65407. **
  65408. ** Exit immediately. All open cursors, etc are closed
  65409. ** automatically.
  65410. **
  65411. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  65412. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  65413. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  65414. ** whether or not to rollback the current transaction. Do not rollback
  65415. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  65416. ** then back out all changes that have occurred during this execution of the
  65417. ** VDBE, but do not rollback the transaction.
  65418. **
  65419. ** If P4 is not null then it is an error message string.
  65420. **
  65421. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  65422. ** every program. So a jump past the last instruction of the program
  65423. ** is the same as executing Halt.
  65424. */
  65425. case OP_Halt: {
  65426. if( pOp->p1==SQLITE_OK && p->pFrame ){
  65427. /* Halt the sub-program. Return control to the parent frame. */
  65428. VdbeFrame *pFrame = p->pFrame;
  65429. p->pFrame = pFrame->pParent;
  65430. p->nFrame--;
  65431. sqlite3VdbeSetChanges(db, p->nChange);
  65432. pc = sqlite3VdbeFrameRestore(pFrame);
  65433. lastRowid = db->lastRowid;
  65434. if( pOp->p2==OE_Ignore ){
  65435. /* Instruction pc is the OP_Program that invoked the sub-program
  65436. ** currently being halted. If the p2 instruction of this OP_Halt
  65437. ** instruction is set to OE_Ignore, then the sub-program is throwing
  65438. ** an IGNORE exception. In this case jump to the address specified
  65439. ** as the p2 of the calling OP_Program. */
  65440. pc = p->aOp[pc].p2-1;
  65441. }
  65442. aOp = p->aOp;
  65443. aMem = p->aMem;
  65444. break;
  65445. }
  65446. p->rc = pOp->p1;
  65447. p->errorAction = (u8)pOp->p2;
  65448. p->pc = pc;
  65449. if( pOp->p4.z ){
  65450. assert( p->rc!=SQLITE_OK );
  65451. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  65452. testcase( sqlite3GlobalConfig.xLog!=0 );
  65453. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  65454. }else if( p->rc ){
  65455. testcase( sqlite3GlobalConfig.xLog!=0 );
  65456. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  65457. }
  65458. rc = sqlite3VdbeHalt(p);
  65459. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  65460. if( rc==SQLITE_BUSY ){
  65461. p->rc = rc = SQLITE_BUSY;
  65462. }else{
  65463. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  65464. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  65465. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  65466. }
  65467. goto vdbe_return;
  65468. }
  65469. /* Opcode: Integer P1 P2 * * *
  65470. **
  65471. ** The 32-bit integer value P1 is written into register P2.
  65472. */
  65473. case OP_Integer: { /* out2-prerelease */
  65474. pOut->u.i = pOp->p1;
  65475. break;
  65476. }
  65477. /* Opcode: Int64 * P2 * P4 *
  65478. **
  65479. ** P4 is a pointer to a 64-bit integer value.
  65480. ** Write that value into register P2.
  65481. */
  65482. case OP_Int64: { /* out2-prerelease */
  65483. assert( pOp->p4.pI64!=0 );
  65484. pOut->u.i = *pOp->p4.pI64;
  65485. break;
  65486. }
  65487. #ifndef SQLITE_OMIT_FLOATING_POINT
  65488. /* Opcode: Real * P2 * P4 *
  65489. **
  65490. ** P4 is a pointer to a 64-bit floating point value.
  65491. ** Write that value into register P2.
  65492. */
  65493. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  65494. pOut->flags = MEM_Real;
  65495. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  65496. pOut->r = *pOp->p4.pReal;
  65497. break;
  65498. }
  65499. #endif
  65500. /* Opcode: String8 * P2 * P4 *
  65501. **
  65502. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  65503. ** into an OP_String before it is executed for the first time.
  65504. */
  65505. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  65506. assert( pOp->p4.z!=0 );
  65507. pOp->opcode = OP_String;
  65508. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  65509. #ifndef SQLITE_OMIT_UTF16
  65510. if( encoding!=SQLITE_UTF8 ){
  65511. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  65512. if( rc==SQLITE_TOOBIG ) goto too_big;
  65513. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  65514. assert( pOut->zMalloc==pOut->z );
  65515. assert( pOut->flags & MEM_Dyn );
  65516. pOut->zMalloc = 0;
  65517. pOut->flags |= MEM_Static;
  65518. pOut->flags &= ~MEM_Dyn;
  65519. if( pOp->p4type==P4_DYNAMIC ){
  65520. sqlite3DbFree(db, pOp->p4.z);
  65521. }
  65522. pOp->p4type = P4_DYNAMIC;
  65523. pOp->p4.z = pOut->z;
  65524. pOp->p1 = pOut->n;
  65525. }
  65526. #endif
  65527. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65528. goto too_big;
  65529. }
  65530. /* Fall through to the next case, OP_String */
  65531. }
  65532. /* Opcode: String P1 P2 * P4 *
  65533. **
  65534. ** The string value P4 of length P1 (bytes) is stored in register P2.
  65535. */
  65536. case OP_String: { /* out2-prerelease */
  65537. assert( pOp->p4.z!=0 );
  65538. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  65539. pOut->z = pOp->p4.z;
  65540. pOut->n = pOp->p1;
  65541. pOut->enc = encoding;
  65542. UPDATE_MAX_BLOBSIZE(pOut);
  65543. break;
  65544. }
  65545. /* Opcode: Null P1 P2 P3 * *
  65546. **
  65547. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  65548. ** NULL into register P3 and every register in between P2 and P3. If P3
  65549. ** is less than P2 (typically P3 is zero) then only register P2 is
  65550. ** set to NULL.
  65551. **
  65552. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  65553. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  65554. ** OP_Ne or OP_Eq.
  65555. */
  65556. case OP_Null: { /* out2-prerelease */
  65557. #if 0 /* local variables moved into u.ab */
  65558. int cnt;
  65559. u16 nullFlag;
  65560. #endif /* local variables moved into u.ab */
  65561. u.ab.cnt = pOp->p3-pOp->p2;
  65562. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65563. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  65564. while( u.ab.cnt>0 ){
  65565. pOut++;
  65566. memAboutToChange(p, pOut);
  65567. VdbeMemRelease(pOut);
  65568. pOut->flags = u.ab.nullFlag;
  65569. u.ab.cnt--;
  65570. }
  65571. break;
  65572. }
  65573. /* Opcode: Blob P1 P2 * P4
  65574. **
  65575. ** P4 points to a blob of data P1 bytes long. Store this
  65576. ** blob in register P2.
  65577. */
  65578. case OP_Blob: { /* out2-prerelease */
  65579. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  65580. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  65581. pOut->enc = encoding;
  65582. UPDATE_MAX_BLOBSIZE(pOut);
  65583. break;
  65584. }
  65585. /* Opcode: Variable P1 P2 * P4 *
  65586. **
  65587. ** Transfer the values of bound parameter P1 into register P2
  65588. **
  65589. ** If the parameter is named, then its name appears in P4 and P3==1.
  65590. ** The P4 value is used by sqlite3_bind_parameter_name().
  65591. */
  65592. case OP_Variable: { /* out2-prerelease */
  65593. #if 0 /* local variables moved into u.ac */
  65594. Mem *pVar; /* Value being transferred */
  65595. #endif /* local variables moved into u.ac */
  65596. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  65597. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  65598. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  65599. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  65600. goto too_big;
  65601. }
  65602. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  65603. UPDATE_MAX_BLOBSIZE(pOut);
  65604. break;
  65605. }
  65606. /* Opcode: Move P1 P2 P3 * *
  65607. **
  65608. ** Move the values in register P1..P1+P3 over into
  65609. ** registers P2..P2+P3. Registers P1..P1+P3 are
  65610. ** left holding a NULL. It is an error for register ranges
  65611. ** P1..P1+P3 and P2..P2+P3 to overlap.
  65612. */
  65613. case OP_Move: {
  65614. #if 0 /* local variables moved into u.ad */
  65615. char *zMalloc; /* Holding variable for allocated memory */
  65616. int n; /* Number of registers left to copy */
  65617. int p1; /* Register to copy from */
  65618. int p2; /* Register to copy to */
  65619. #endif /* local variables moved into u.ad */
  65620. u.ad.n = pOp->p3 + 1;
  65621. u.ad.p1 = pOp->p1;
  65622. u.ad.p2 = pOp->p2;
  65623. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  65624. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  65625. pIn1 = &aMem[u.ad.p1];
  65626. pOut = &aMem[u.ad.p2];
  65627. while( u.ad.n-- ){
  65628. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  65629. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  65630. assert( memIsValid(pIn1) );
  65631. memAboutToChange(p, pOut);
  65632. u.ad.zMalloc = pOut->zMalloc;
  65633. pOut->zMalloc = 0;
  65634. sqlite3VdbeMemMove(pOut, pIn1);
  65635. #ifdef SQLITE_DEBUG
  65636. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  65637. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  65638. }
  65639. #endif
  65640. pIn1->zMalloc = u.ad.zMalloc;
  65641. REGISTER_TRACE(u.ad.p2++, pOut);
  65642. pIn1++;
  65643. pOut++;
  65644. }
  65645. break;
  65646. }
  65647. /* Opcode: Copy P1 P2 P3 * *
  65648. **
  65649. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  65650. **
  65651. ** This instruction makes a deep copy of the value. A duplicate
  65652. ** is made of any string or blob constant. See also OP_SCopy.
  65653. */
  65654. case OP_Copy: {
  65655. #if 0 /* local variables moved into u.ae */
  65656. int n;
  65657. #endif /* local variables moved into u.ae */
  65658. u.ae.n = pOp->p3;
  65659. pIn1 = &aMem[pOp->p1];
  65660. pOut = &aMem[pOp->p2];
  65661. assert( pOut!=pIn1 );
  65662. while( 1 ){
  65663. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65664. Deephemeralize(pOut);
  65665. #ifdef SQLITE_DEBUG
  65666. pOut->pScopyFrom = 0;
  65667. #endif
  65668. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  65669. if( (u.ae.n--)==0 ) break;
  65670. pOut++;
  65671. pIn1++;
  65672. }
  65673. break;
  65674. }
  65675. /* Opcode: SCopy P1 P2 * * *
  65676. **
  65677. ** Make a shallow copy of register P1 into register P2.
  65678. **
  65679. ** This instruction makes a shallow copy of the value. If the value
  65680. ** is a string or blob, then the copy is only a pointer to the
  65681. ** original and hence if the original changes so will the copy.
  65682. ** Worse, if the original is deallocated, the copy becomes invalid.
  65683. ** Thus the program must guarantee that the original will not change
  65684. ** during the lifetime of the copy. Use OP_Copy to make a complete
  65685. ** copy.
  65686. */
  65687. case OP_SCopy: { /* in1, out2 */
  65688. pIn1 = &aMem[pOp->p1];
  65689. pOut = &aMem[pOp->p2];
  65690. assert( pOut!=pIn1 );
  65691. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65692. #ifdef SQLITE_DEBUG
  65693. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  65694. #endif
  65695. REGISTER_TRACE(pOp->p2, pOut);
  65696. break;
  65697. }
  65698. /* Opcode: ResultRow P1 P2 * * *
  65699. **
  65700. ** The registers P1 through P1+P2-1 contain a single row of
  65701. ** results. This opcode causes the sqlite3_step() call to terminate
  65702. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  65703. ** structure to provide access to the top P1 values as the result
  65704. ** row.
  65705. */
  65706. case OP_ResultRow: {
  65707. #if 0 /* local variables moved into u.af */
  65708. Mem *pMem;
  65709. int i;
  65710. #endif /* local variables moved into u.af */
  65711. assert( p->nResColumn==pOp->p2 );
  65712. assert( pOp->p1>0 );
  65713. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  65714. /* If this statement has violated immediate foreign key constraints, do
  65715. ** not return the number of rows modified. And do not RELEASE the statement
  65716. ** transaction. It needs to be rolled back. */
  65717. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  65718. assert( db->flags&SQLITE_CountRows );
  65719. assert( p->usesStmtJournal );
  65720. break;
  65721. }
  65722. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  65723. ** DML statements invoke this opcode to return the number of rows
  65724. ** modified to the user. This is the only way that a VM that
  65725. ** opens a statement transaction may invoke this opcode.
  65726. **
  65727. ** In case this is such a statement, close any statement transaction
  65728. ** opened by this VM before returning control to the user. This is to
  65729. ** ensure that statement-transactions are always nested, not overlapping.
  65730. ** If the open statement-transaction is not closed here, then the user
  65731. ** may step another VM that opens its own statement transaction. This
  65732. ** may lead to overlapping statement transactions.
  65733. **
  65734. ** The statement transaction is never a top-level transaction. Hence
  65735. ** the RELEASE call below can never fail.
  65736. */
  65737. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  65738. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  65739. if( NEVER(rc!=SQLITE_OK) ){
  65740. break;
  65741. }
  65742. /* Invalidate all ephemeral cursor row caches */
  65743. p->cacheCtr = (p->cacheCtr + 2)|1;
  65744. /* Make sure the results of the current row are \000 terminated
  65745. ** and have an assigned type. The results are de-ephemeralized as
  65746. ** a side effect.
  65747. */
  65748. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  65749. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  65750. assert( memIsValid(&u.af.pMem[u.af.i]) );
  65751. Deephemeralize(&u.af.pMem[u.af.i]);
  65752. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  65753. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  65754. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  65755. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  65756. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  65757. }
  65758. if( db->mallocFailed ) goto no_mem;
  65759. /* Return SQLITE_ROW
  65760. */
  65761. p->pc = pc + 1;
  65762. rc = SQLITE_ROW;
  65763. goto vdbe_return;
  65764. }
  65765. /* Opcode: Concat P1 P2 P3 * *
  65766. **
  65767. ** Add the text in register P1 onto the end of the text in
  65768. ** register P2 and store the result in register P3.
  65769. ** If either the P1 or P2 text are NULL then store NULL in P3.
  65770. **
  65771. ** P3 = P2 || P1
  65772. **
  65773. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  65774. ** if P3 is the same register as P2, the implementation is able
  65775. ** to avoid a memcpy().
  65776. */
  65777. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  65778. #if 0 /* local variables moved into u.ag */
  65779. i64 nByte;
  65780. #endif /* local variables moved into u.ag */
  65781. pIn1 = &aMem[pOp->p1];
  65782. pIn2 = &aMem[pOp->p2];
  65783. pOut = &aMem[pOp->p3];
  65784. assert( pIn1!=pOut );
  65785. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  65786. sqlite3VdbeMemSetNull(pOut);
  65787. break;
  65788. }
  65789. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  65790. Stringify(pIn1, encoding);
  65791. Stringify(pIn2, encoding);
  65792. u.ag.nByte = pIn1->n + pIn2->n;
  65793. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65794. goto too_big;
  65795. }
  65796. MemSetTypeFlag(pOut, MEM_Str);
  65797. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  65798. goto no_mem;
  65799. }
  65800. if( pOut!=pIn2 ){
  65801. memcpy(pOut->z, pIn2->z, pIn2->n);
  65802. }
  65803. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  65804. pOut->z[u.ag.nByte] = 0;
  65805. pOut->z[u.ag.nByte+1] = 0;
  65806. pOut->flags |= MEM_Term;
  65807. pOut->n = (int)u.ag.nByte;
  65808. pOut->enc = encoding;
  65809. UPDATE_MAX_BLOBSIZE(pOut);
  65810. break;
  65811. }
  65812. /* Opcode: Add P1 P2 P3 * *
  65813. **
  65814. ** Add the value in register P1 to the value in register P2
  65815. ** and store the result in register P3.
  65816. ** If either input is NULL, the result is NULL.
  65817. */
  65818. /* Opcode: Multiply P1 P2 P3 * *
  65819. **
  65820. **
  65821. ** Multiply the value in register P1 by the value in register P2
  65822. ** and store the result in register P3.
  65823. ** If either input is NULL, the result is NULL.
  65824. */
  65825. /* Opcode: Subtract P1 P2 P3 * *
  65826. **
  65827. ** Subtract the value in register P1 from the value in register P2
  65828. ** and store the result in register P3.
  65829. ** If either input is NULL, the result is NULL.
  65830. */
  65831. /* Opcode: Divide P1 P2 P3 * *
  65832. **
  65833. ** Divide the value in register P1 by the value in register P2
  65834. ** and store the result in register P3 (P3=P2/P1). If the value in
  65835. ** register P1 is zero, then the result is NULL. If either input is
  65836. ** NULL, the result is NULL.
  65837. */
  65838. /* Opcode: Remainder P1 P2 P3 * *
  65839. **
  65840. ** Compute the remainder after integer division of the value in
  65841. ** register P1 by the value in register P2 and store the result in P3.
  65842. ** If the value in register P2 is zero the result is NULL.
  65843. ** If either operand is NULL, the result is NULL.
  65844. */
  65845. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  65846. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  65847. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  65848. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  65849. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  65850. #if 0 /* local variables moved into u.ah */
  65851. char bIntint; /* Started out as two integer operands */
  65852. int flags; /* Combined MEM_* flags from both inputs */
  65853. i64 iA; /* Integer value of left operand */
  65854. i64 iB; /* Integer value of right operand */
  65855. double rA; /* Real value of left operand */
  65856. double rB; /* Real value of right operand */
  65857. #endif /* local variables moved into u.ah */
  65858. pIn1 = &aMem[pOp->p1];
  65859. applyNumericAffinity(pIn1);
  65860. pIn2 = &aMem[pOp->p2];
  65861. applyNumericAffinity(pIn2);
  65862. pOut = &aMem[pOp->p3];
  65863. u.ah.flags = pIn1->flags | pIn2->flags;
  65864. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  65865. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  65866. u.ah.iA = pIn1->u.i;
  65867. u.ah.iB = pIn2->u.i;
  65868. u.ah.bIntint = 1;
  65869. switch( pOp->opcode ){
  65870. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65871. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65872. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65873. case OP_Divide: {
  65874. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65875. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  65876. u.ah.iB /= u.ah.iA;
  65877. break;
  65878. }
  65879. default: {
  65880. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65881. if( u.ah.iA==-1 ) u.ah.iA = 1;
  65882. u.ah.iB %= u.ah.iA;
  65883. break;
  65884. }
  65885. }
  65886. pOut->u.i = u.ah.iB;
  65887. MemSetTypeFlag(pOut, MEM_Int);
  65888. }else{
  65889. u.ah.bIntint = 0;
  65890. fp_math:
  65891. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  65892. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  65893. switch( pOp->opcode ){
  65894. case OP_Add: u.ah.rB += u.ah.rA; break;
  65895. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  65896. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  65897. case OP_Divide: {
  65898. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65899. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  65900. u.ah.rB /= u.ah.rA;
  65901. break;
  65902. }
  65903. default: {
  65904. u.ah.iA = (i64)u.ah.rA;
  65905. u.ah.iB = (i64)u.ah.rB;
  65906. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65907. if( u.ah.iA==-1 ) u.ah.iA = 1;
  65908. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  65909. break;
  65910. }
  65911. }
  65912. #ifdef SQLITE_OMIT_FLOATING_POINT
  65913. pOut->u.i = u.ah.rB;
  65914. MemSetTypeFlag(pOut, MEM_Int);
  65915. #else
  65916. if( sqlite3IsNaN(u.ah.rB) ){
  65917. goto arithmetic_result_is_null;
  65918. }
  65919. pOut->r = u.ah.rB;
  65920. MemSetTypeFlag(pOut, MEM_Real);
  65921. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  65922. sqlite3VdbeIntegerAffinity(pOut);
  65923. }
  65924. #endif
  65925. }
  65926. break;
  65927. arithmetic_result_is_null:
  65928. sqlite3VdbeMemSetNull(pOut);
  65929. break;
  65930. }
  65931. /* Opcode: CollSeq P1 * * P4
  65932. **
  65933. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  65934. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  65935. ** be returned. This is used by the built-in min(), max() and nullif()
  65936. ** functions.
  65937. **
  65938. ** If P1 is not zero, then it is a register that a subsequent min() or
  65939. ** max() aggregate will set to 1 if the current row is not the minimum or
  65940. ** maximum. The P1 register is initialized to 0 by this instruction.
  65941. **
  65942. ** The interface used by the implementation of the aforementioned functions
  65943. ** to retrieve the collation sequence set by this opcode is not available
  65944. ** publicly, only to user functions defined in func.c.
  65945. */
  65946. case OP_CollSeq: {
  65947. assert( pOp->p4type==P4_COLLSEQ );
  65948. if( pOp->p1 ){
  65949. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  65950. }
  65951. break;
  65952. }
  65953. /* Opcode: Function P1 P2 P3 P4 P5
  65954. **
  65955. ** Invoke a user function (P4 is a pointer to a Function structure that
  65956. ** defines the function) with P5 arguments taken from register P2 and
  65957. ** successors. The result of the function is stored in register P3.
  65958. ** Register P3 must not be one of the function inputs.
  65959. **
  65960. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  65961. ** function was determined to be constant at compile time. If the first
  65962. ** argument was constant then bit 0 of P1 is set. This is used to determine
  65963. ** whether meta data associated with a user function argument using the
  65964. ** sqlite3_set_auxdata() API may be safely retained until the next
  65965. ** invocation of this opcode.
  65966. **
  65967. ** See also: AggStep and AggFinal
  65968. */
  65969. case OP_Function: {
  65970. #if 0 /* local variables moved into u.ai */
  65971. int i;
  65972. Mem *pArg;
  65973. sqlite3_context ctx;
  65974. sqlite3_value **apVal;
  65975. int n;
  65976. #endif /* local variables moved into u.ai */
  65977. u.ai.n = pOp->p5;
  65978. u.ai.apVal = p->apArg;
  65979. assert( u.ai.apVal || u.ai.n==0 );
  65980. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  65981. pOut = &aMem[pOp->p3];
  65982. memAboutToChange(p, pOut);
  65983. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) );
  65984. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  65985. u.ai.pArg = &aMem[pOp->p2];
  65986. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  65987. assert( memIsValid(u.ai.pArg) );
  65988. u.ai.apVal[u.ai.i] = u.ai.pArg;
  65989. Deephemeralize(u.ai.pArg);
  65990. sqlite3VdbeMemStoreType(u.ai.pArg);
  65991. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  65992. }
  65993. assert( pOp->p4type==P4_FUNCDEF );
  65994. u.ai.ctx.pFunc = pOp->p4.pFunc;
  65995. u.ai.ctx.s.flags = MEM_Null;
  65996. u.ai.ctx.s.db = db;
  65997. u.ai.ctx.s.xDel = 0;
  65998. u.ai.ctx.s.zMalloc = 0;
  65999. u.ai.ctx.iOp = pc;
  66000. u.ai.ctx.pVdbe = p;
  66001. /* The output cell may already have a buffer allocated. Move
  66002. ** the pointer to u.ai.ctx.s so in case the user-function can use
  66003. ** the already allocated buffer instead of allocating a new one.
  66004. */
  66005. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  66006. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  66007. u.ai.ctx.fErrorOrAux = 0;
  66008. if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  66009. assert( pOp>aOp );
  66010. assert( pOp[-1].p4type==P4_COLLSEQ );
  66011. assert( pOp[-1].opcode==OP_CollSeq );
  66012. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  66013. }
  66014. db->lastRowid = lastRowid;
  66015. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  66016. lastRowid = db->lastRowid;
  66017. if( db->mallocFailed ){
  66018. /* Even though a malloc() has failed, the implementation of the
  66019. ** user function may have called an sqlite3_result_XXX() function
  66020. ** to return a value. The following call releases any resources
  66021. ** associated with such a value.
  66022. */
  66023. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  66024. goto no_mem;
  66025. }
  66026. /* If the function returned an error, throw an exception */
  66027. if( u.ai.ctx.fErrorOrAux ){
  66028. if( u.ai.ctx.isError ){
  66029. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  66030. rc = u.ai.ctx.isError;
  66031. }
  66032. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  66033. }
  66034. /* Copy the result of the function into register P3 */
  66035. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  66036. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  66037. if( sqlite3VdbeMemTooBig(pOut) ){
  66038. goto too_big;
  66039. }
  66040. #if 0
  66041. /* The app-defined function has done something that as caused this
  66042. ** statement to expire. (Perhaps the function called sqlite3_exec()
  66043. ** with a CREATE TABLE statement.)
  66044. */
  66045. if( p->expired ) rc = SQLITE_ABORT;
  66046. #endif
  66047. REGISTER_TRACE(pOp->p3, pOut);
  66048. UPDATE_MAX_BLOBSIZE(pOut);
  66049. break;
  66050. }
  66051. /* Opcode: BitAnd P1 P2 P3 * *
  66052. **
  66053. ** Take the bit-wise AND of the values in register P1 and P2 and
  66054. ** store the result in register P3.
  66055. ** If either input is NULL, the result is NULL.
  66056. */
  66057. /* Opcode: BitOr P1 P2 P3 * *
  66058. **
  66059. ** Take the bit-wise OR of the values in register P1 and P2 and
  66060. ** store the result in register P3.
  66061. ** If either input is NULL, the result is NULL.
  66062. */
  66063. /* Opcode: ShiftLeft P1 P2 P3 * *
  66064. **
  66065. ** Shift the integer value in register P2 to the left by the
  66066. ** number of bits specified by the integer in register P1.
  66067. ** Store the result in register P3.
  66068. ** If either input is NULL, the result is NULL.
  66069. */
  66070. /* Opcode: ShiftRight P1 P2 P3 * *
  66071. **
  66072. ** Shift the integer value in register P2 to the right by the
  66073. ** number of bits specified by the integer in register P1.
  66074. ** Store the result in register P3.
  66075. ** If either input is NULL, the result is NULL.
  66076. */
  66077. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  66078. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  66079. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  66080. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  66081. #if 0 /* local variables moved into u.aj */
  66082. i64 iA;
  66083. u64 uA;
  66084. i64 iB;
  66085. u8 op;
  66086. #endif /* local variables moved into u.aj */
  66087. pIn1 = &aMem[pOp->p1];
  66088. pIn2 = &aMem[pOp->p2];
  66089. pOut = &aMem[pOp->p3];
  66090. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  66091. sqlite3VdbeMemSetNull(pOut);
  66092. break;
  66093. }
  66094. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  66095. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  66096. u.aj.op = pOp->opcode;
  66097. if( u.aj.op==OP_BitAnd ){
  66098. u.aj.iA &= u.aj.iB;
  66099. }else if( u.aj.op==OP_BitOr ){
  66100. u.aj.iA |= u.aj.iB;
  66101. }else if( u.aj.iB!=0 ){
  66102. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  66103. /* If shifting by a negative amount, shift in the other direction */
  66104. if( u.aj.iB<0 ){
  66105. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  66106. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  66107. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  66108. }
  66109. if( u.aj.iB>=64 ){
  66110. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  66111. }else{
  66112. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  66113. if( u.aj.op==OP_ShiftLeft ){
  66114. u.aj.uA <<= u.aj.iB;
  66115. }else{
  66116. u.aj.uA >>= u.aj.iB;
  66117. /* Sign-extend on a right shift of a negative number */
  66118. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  66119. }
  66120. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  66121. }
  66122. }
  66123. pOut->u.i = u.aj.iA;
  66124. MemSetTypeFlag(pOut, MEM_Int);
  66125. break;
  66126. }
  66127. /* Opcode: AddImm P1 P2 * * *
  66128. **
  66129. ** Add the constant P2 to the value in register P1.
  66130. ** The result is always an integer.
  66131. **
  66132. ** To force any register to be an integer, just add 0.
  66133. */
  66134. case OP_AddImm: { /* in1 */
  66135. pIn1 = &aMem[pOp->p1];
  66136. memAboutToChange(p, pIn1);
  66137. sqlite3VdbeMemIntegerify(pIn1);
  66138. pIn1->u.i += pOp->p2;
  66139. break;
  66140. }
  66141. /* Opcode: MustBeInt P1 P2 * * *
  66142. **
  66143. ** Force the value in register P1 to be an integer. If the value
  66144. ** in P1 is not an integer and cannot be converted into an integer
  66145. ** without data loss, then jump immediately to P2, or if P2==0
  66146. ** raise an SQLITE_MISMATCH exception.
  66147. */
  66148. case OP_MustBeInt: { /* jump, in1 */
  66149. pIn1 = &aMem[pOp->p1];
  66150. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  66151. if( (pIn1->flags & MEM_Int)==0 ){
  66152. if( pOp->p2==0 ){
  66153. rc = SQLITE_MISMATCH;
  66154. goto abort_due_to_error;
  66155. }else{
  66156. pc = pOp->p2 - 1;
  66157. }
  66158. }else{
  66159. MemSetTypeFlag(pIn1, MEM_Int);
  66160. }
  66161. break;
  66162. }
  66163. #ifndef SQLITE_OMIT_FLOATING_POINT
  66164. /* Opcode: RealAffinity P1 * * * *
  66165. **
  66166. ** If register P1 holds an integer convert it to a real value.
  66167. **
  66168. ** This opcode is used when extracting information from a column that
  66169. ** has REAL affinity. Such column values may still be stored as
  66170. ** integers, for space efficiency, but after extraction we want them
  66171. ** to have only a real value.
  66172. */
  66173. case OP_RealAffinity: { /* in1 */
  66174. pIn1 = &aMem[pOp->p1];
  66175. if( pIn1->flags & MEM_Int ){
  66176. sqlite3VdbeMemRealify(pIn1);
  66177. }
  66178. break;
  66179. }
  66180. #endif
  66181. #ifndef SQLITE_OMIT_CAST
  66182. /* Opcode: ToText P1 * * * *
  66183. **
  66184. ** Force the value in register P1 to be text.
  66185. ** If the value is numeric, convert it to a string using the
  66186. ** equivalent of printf(). Blob values are unchanged and
  66187. ** are afterwards simply interpreted as text.
  66188. **
  66189. ** A NULL value is not changed by this routine. It remains NULL.
  66190. */
  66191. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  66192. pIn1 = &aMem[pOp->p1];
  66193. memAboutToChange(p, pIn1);
  66194. if( pIn1->flags & MEM_Null ) break;
  66195. assert( MEM_Str==(MEM_Blob>>3) );
  66196. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  66197. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  66198. rc = ExpandBlob(pIn1);
  66199. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  66200. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  66201. UPDATE_MAX_BLOBSIZE(pIn1);
  66202. break;
  66203. }
  66204. /* Opcode: ToBlob P1 * * * *
  66205. **
  66206. ** Force the value in register P1 to be a BLOB.
  66207. ** If the value is numeric, convert it to a string first.
  66208. ** Strings are simply reinterpreted as blobs with no change
  66209. ** to the underlying data.
  66210. **
  66211. ** A NULL value is not changed by this routine. It remains NULL.
  66212. */
  66213. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  66214. pIn1 = &aMem[pOp->p1];
  66215. if( pIn1->flags & MEM_Null ) break;
  66216. if( (pIn1->flags & MEM_Blob)==0 ){
  66217. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  66218. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  66219. MemSetTypeFlag(pIn1, MEM_Blob);
  66220. }else{
  66221. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  66222. }
  66223. UPDATE_MAX_BLOBSIZE(pIn1);
  66224. break;
  66225. }
  66226. /* Opcode: ToNumeric P1 * * * *
  66227. **
  66228. ** Force the value in register P1 to be numeric (either an
  66229. ** integer or a floating-point number.)
  66230. ** If the value is text or blob, try to convert it to an using the
  66231. ** equivalent of atoi() or atof() and store 0 if no such conversion
  66232. ** is possible.
  66233. **
  66234. ** A NULL value is not changed by this routine. It remains NULL.
  66235. */
  66236. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  66237. pIn1 = &aMem[pOp->p1];
  66238. sqlite3VdbeMemNumerify(pIn1);
  66239. break;
  66240. }
  66241. #endif /* SQLITE_OMIT_CAST */
  66242. /* Opcode: ToInt P1 * * * *
  66243. **
  66244. ** Force the value in register P1 to be an integer. If
  66245. ** The value is currently a real number, drop its fractional part.
  66246. ** If the value is text or blob, try to convert it to an integer using the
  66247. ** equivalent of atoi() and store 0 if no such conversion is possible.
  66248. **
  66249. ** A NULL value is not changed by this routine. It remains NULL.
  66250. */
  66251. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  66252. pIn1 = &aMem[pOp->p1];
  66253. if( (pIn1->flags & MEM_Null)==0 ){
  66254. sqlite3VdbeMemIntegerify(pIn1);
  66255. }
  66256. break;
  66257. }
  66258. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  66259. /* Opcode: ToReal P1 * * * *
  66260. **
  66261. ** Force the value in register P1 to be a floating point number.
  66262. ** If The value is currently an integer, convert it.
  66263. ** If the value is text or blob, try to convert it to an integer using the
  66264. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  66265. **
  66266. ** A NULL value is not changed by this routine. It remains NULL.
  66267. */
  66268. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  66269. pIn1 = &aMem[pOp->p1];
  66270. memAboutToChange(p, pIn1);
  66271. if( (pIn1->flags & MEM_Null)==0 ){
  66272. sqlite3VdbeMemRealify(pIn1);
  66273. }
  66274. break;
  66275. }
  66276. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  66277. /* Opcode: Lt P1 P2 P3 P4 P5
  66278. **
  66279. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  66280. ** jump to address P2.
  66281. **
  66282. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  66283. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  66284. ** bit is clear then fall through if either operand is NULL.
  66285. **
  66286. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  66287. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  66288. ** to coerce both inputs according to this affinity before the
  66289. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  66290. ** affinity is used. Note that the affinity conversions are stored
  66291. ** back into the input registers P1 and P3. So this opcode can cause
  66292. ** persistent changes to registers P1 and P3.
  66293. **
  66294. ** Once any conversions have taken place, and neither value is NULL,
  66295. ** the values are compared. If both values are blobs then memcmp() is
  66296. ** used to determine the results of the comparison. If both values
  66297. ** are text, then the appropriate collating function specified in
  66298. ** P4 is used to do the comparison. If P4 is not specified then
  66299. ** memcmp() is used to compare text string. If both values are
  66300. ** numeric, then a numeric comparison is used. If the two values
  66301. ** are of different types, then numbers are considered less than
  66302. ** strings and strings are considered less than blobs.
  66303. **
  66304. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  66305. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  66306. **
  66307. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  66308. ** equal to one another, provided that they do not have their MEM_Cleared
  66309. ** bit set.
  66310. */
  66311. /* Opcode: Ne P1 P2 P3 P4 P5
  66312. **
  66313. ** This works just like the Lt opcode except that the jump is taken if
  66314. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  66315. ** additional information.
  66316. **
  66317. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66318. ** true or false and is never NULL. If both operands are NULL then the result
  66319. ** of comparison is false. If either operand is NULL then the result is true.
  66320. ** If neither operand is NULL the result is the same as it would be if
  66321. ** the SQLITE_NULLEQ flag were omitted from P5.
  66322. */
  66323. /* Opcode: Eq P1 P2 P3 P4 P5
  66324. **
  66325. ** This works just like the Lt opcode except that the jump is taken if
  66326. ** the operands in registers P1 and P3 are equal.
  66327. ** See the Lt opcode for additional information.
  66328. **
  66329. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66330. ** true or false and is never NULL. If both operands are NULL then the result
  66331. ** of comparison is true. If either operand is NULL then the result is false.
  66332. ** If neither operand is NULL the result is the same as it would be if
  66333. ** the SQLITE_NULLEQ flag were omitted from P5.
  66334. */
  66335. /* Opcode: Le P1 P2 P3 P4 P5
  66336. **
  66337. ** This works just like the Lt opcode except that the jump is taken if
  66338. ** the content of register P3 is less than or equal to the content of
  66339. ** register P1. See the Lt opcode for additional information.
  66340. */
  66341. /* Opcode: Gt P1 P2 P3 P4 P5
  66342. **
  66343. ** This works just like the Lt opcode except that the jump is taken if
  66344. ** the content of register P3 is greater than the content of
  66345. ** register P1. See the Lt opcode for additional information.
  66346. */
  66347. /* Opcode: Ge P1 P2 P3 P4 P5
  66348. **
  66349. ** This works just like the Lt opcode except that the jump is taken if
  66350. ** the content of register P3 is greater than or equal to the content of
  66351. ** register P1. See the Lt opcode for additional information.
  66352. */
  66353. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  66354. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  66355. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  66356. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  66357. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  66358. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  66359. #if 0 /* local variables moved into u.ak */
  66360. int res; /* Result of the comparison of pIn1 against pIn3 */
  66361. char affinity; /* Affinity to use for comparison */
  66362. u16 flags1; /* Copy of initial value of pIn1->flags */
  66363. u16 flags3; /* Copy of initial value of pIn3->flags */
  66364. #endif /* local variables moved into u.ak */
  66365. pIn1 = &aMem[pOp->p1];
  66366. pIn3 = &aMem[pOp->p3];
  66367. u.ak.flags1 = pIn1->flags;
  66368. u.ak.flags3 = pIn3->flags;
  66369. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  66370. /* One or both operands are NULL */
  66371. if( pOp->p5 & SQLITE_NULLEQ ){
  66372. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  66373. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  66374. ** or not both operands are null.
  66375. */
  66376. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  66377. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  66378. if( (u.ak.flags1&MEM_Null)!=0
  66379. && (u.ak.flags3&MEM_Null)!=0
  66380. && (u.ak.flags3&MEM_Cleared)==0
  66381. ){
  66382. u.ak.res = 0; /* Results are equal */
  66383. }else{
  66384. u.ak.res = 1; /* Results are not equal */
  66385. }
  66386. }else{
  66387. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  66388. ** then the result is always NULL.
  66389. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  66390. */
  66391. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  66392. pc = pOp->p2-1;
  66393. }else if( pOp->p5 & SQLITE_STOREP2 ){
  66394. pOut = &aMem[pOp->p2];
  66395. MemSetTypeFlag(pOut, MEM_Null);
  66396. REGISTER_TRACE(pOp->p2, pOut);
  66397. }
  66398. break;
  66399. }
  66400. }else{
  66401. /* Neither operand is NULL. Do a comparison. */
  66402. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  66403. if( u.ak.affinity ){
  66404. applyAffinity(pIn1, u.ak.affinity, encoding);
  66405. applyAffinity(pIn3, u.ak.affinity, encoding);
  66406. if( db->mallocFailed ) goto no_mem;
  66407. }
  66408. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  66409. ExpandBlob(pIn1);
  66410. ExpandBlob(pIn3);
  66411. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  66412. }
  66413. switch( pOp->opcode ){
  66414. case OP_Eq: u.ak.res = u.ak.res==0; break;
  66415. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  66416. case OP_Lt: u.ak.res = u.ak.res<0; break;
  66417. case OP_Le: u.ak.res = u.ak.res<=0; break;
  66418. case OP_Gt: u.ak.res = u.ak.res>0; break;
  66419. default: u.ak.res = u.ak.res>=0; break;
  66420. }
  66421. if( pOp->p5 & SQLITE_STOREP2 ){
  66422. pOut = &aMem[pOp->p2];
  66423. memAboutToChange(p, pOut);
  66424. MemSetTypeFlag(pOut, MEM_Int);
  66425. pOut->u.i = u.ak.res;
  66426. REGISTER_TRACE(pOp->p2, pOut);
  66427. }else if( u.ak.res ){
  66428. pc = pOp->p2-1;
  66429. }
  66430. /* Undo any changes made by applyAffinity() to the input registers. */
  66431. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  66432. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  66433. break;
  66434. }
  66435. /* Opcode: Permutation * * * P4 *
  66436. **
  66437. ** Set the permutation used by the OP_Compare operator to be the array
  66438. ** of integers in P4.
  66439. **
  66440. ** The permutation is only valid until the next OP_Compare that has
  66441. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  66442. ** occur immediately prior to the OP_Compare.
  66443. */
  66444. case OP_Permutation: {
  66445. assert( pOp->p4type==P4_INTARRAY );
  66446. assert( pOp->p4.ai );
  66447. aPermute = pOp->p4.ai;
  66448. break;
  66449. }
  66450. /* Opcode: Compare P1 P2 P3 P4 P5
  66451. **
  66452. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  66453. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  66454. ** the comparison for use by the next OP_Jump instruct.
  66455. **
  66456. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  66457. ** determined by the most recent OP_Permutation operator. If the
  66458. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  66459. ** order.
  66460. **
  66461. ** P4 is a KeyInfo structure that defines collating sequences and sort
  66462. ** orders for the comparison. The permutation applies to registers
  66463. ** only. The KeyInfo elements are used sequentially.
  66464. **
  66465. ** The comparison is a sort comparison, so NULLs compare equal,
  66466. ** NULLs are less than numbers, numbers are less than strings,
  66467. ** and strings are less than blobs.
  66468. */
  66469. case OP_Compare: {
  66470. #if 0 /* local variables moved into u.al */
  66471. int n;
  66472. int i;
  66473. int p1;
  66474. int p2;
  66475. const KeyInfo *pKeyInfo;
  66476. int idx;
  66477. CollSeq *pColl; /* Collating sequence to use on this term */
  66478. int bRev; /* True for DESCENDING sort order */
  66479. #endif /* local variables moved into u.al */
  66480. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  66481. u.al.n = pOp->p3;
  66482. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  66483. assert( u.al.n>0 );
  66484. assert( u.al.pKeyInfo!=0 );
  66485. u.al.p1 = pOp->p1;
  66486. u.al.p2 = pOp->p2;
  66487. #if SQLITE_DEBUG
  66488. if( aPermute ){
  66489. int k, mx = 0;
  66490. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  66491. assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 );
  66492. assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 );
  66493. }else{
  66494. assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 );
  66495. assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 );
  66496. }
  66497. #endif /* SQLITE_DEBUG */
  66498. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  66499. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  66500. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  66501. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  66502. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  66503. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  66504. assert( u.al.i<u.al.pKeyInfo->nField );
  66505. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  66506. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  66507. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  66508. if( iCompare ){
  66509. if( u.al.bRev ) iCompare = -iCompare;
  66510. break;
  66511. }
  66512. }
  66513. aPermute = 0;
  66514. break;
  66515. }
  66516. /* Opcode: Jump P1 P2 P3 * *
  66517. **
  66518. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  66519. ** in the most recent OP_Compare instruction the P1 vector was less than
  66520. ** equal to, or greater than the P2 vector, respectively.
  66521. */
  66522. case OP_Jump: { /* jump */
  66523. if( iCompare<0 ){
  66524. pc = pOp->p1 - 1;
  66525. }else if( iCompare==0 ){
  66526. pc = pOp->p2 - 1;
  66527. }else{
  66528. pc = pOp->p3 - 1;
  66529. }
  66530. break;
  66531. }
  66532. /* Opcode: And P1 P2 P3 * *
  66533. **
  66534. ** Take the logical AND of the values in registers P1 and P2 and
  66535. ** write the result into register P3.
  66536. **
  66537. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  66538. ** the other input is NULL. A NULL and true or two NULLs give
  66539. ** a NULL output.
  66540. */
  66541. /* Opcode: Or P1 P2 P3 * *
  66542. **
  66543. ** Take the logical OR of the values in register P1 and P2 and
  66544. ** store the answer in register P3.
  66545. **
  66546. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  66547. ** even if the other input is NULL. A NULL and false or two NULLs
  66548. ** give a NULL output.
  66549. */
  66550. case OP_And: /* same as TK_AND, in1, in2, out3 */
  66551. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  66552. #if 0 /* local variables moved into u.am */
  66553. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66554. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66555. #endif /* local variables moved into u.am */
  66556. pIn1 = &aMem[pOp->p1];
  66557. if( pIn1->flags & MEM_Null ){
  66558. u.am.v1 = 2;
  66559. }else{
  66560. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  66561. }
  66562. pIn2 = &aMem[pOp->p2];
  66563. if( pIn2->flags & MEM_Null ){
  66564. u.am.v2 = 2;
  66565. }else{
  66566. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  66567. }
  66568. if( pOp->opcode==OP_And ){
  66569. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  66570. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  66571. }else{
  66572. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  66573. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  66574. }
  66575. pOut = &aMem[pOp->p3];
  66576. if( u.am.v1==2 ){
  66577. MemSetTypeFlag(pOut, MEM_Null);
  66578. }else{
  66579. pOut->u.i = u.am.v1;
  66580. MemSetTypeFlag(pOut, MEM_Int);
  66581. }
  66582. break;
  66583. }
  66584. /* Opcode: Not P1 P2 * * *
  66585. **
  66586. ** Interpret the value in register P1 as a boolean value. Store the
  66587. ** boolean complement in register P2. If the value in register P1 is
  66588. ** NULL, then a NULL is stored in P2.
  66589. */
  66590. case OP_Not: { /* same as TK_NOT, in1, out2 */
  66591. pIn1 = &aMem[pOp->p1];
  66592. pOut = &aMem[pOp->p2];
  66593. if( pIn1->flags & MEM_Null ){
  66594. sqlite3VdbeMemSetNull(pOut);
  66595. }else{
  66596. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  66597. }
  66598. break;
  66599. }
  66600. /* Opcode: BitNot P1 P2 * * *
  66601. **
  66602. ** Interpret the content of register P1 as an integer. Store the
  66603. ** ones-complement of the P1 value into register P2. If P1 holds
  66604. ** a NULL then store a NULL in P2.
  66605. */
  66606. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  66607. pIn1 = &aMem[pOp->p1];
  66608. pOut = &aMem[pOp->p2];
  66609. if( pIn1->flags & MEM_Null ){
  66610. sqlite3VdbeMemSetNull(pOut);
  66611. }else{
  66612. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  66613. }
  66614. break;
  66615. }
  66616. /* Opcode: Once P1 P2 * * *
  66617. **
  66618. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  66619. ** set the flag and fall through to the next instruction.
  66620. */
  66621. case OP_Once: { /* jump */
  66622. assert( pOp->p1<p->nOnceFlag );
  66623. if( p->aOnceFlag[pOp->p1] ){
  66624. pc = pOp->p2-1;
  66625. }else{
  66626. p->aOnceFlag[pOp->p1] = 1;
  66627. }
  66628. break;
  66629. }
  66630. /* Opcode: If P1 P2 P3 * *
  66631. **
  66632. ** Jump to P2 if the value in register P1 is true. The value
  66633. ** is considered true if it is numeric and non-zero. If the value
  66634. ** in P1 is NULL then take the jump if P3 is non-zero.
  66635. */
  66636. /* Opcode: IfNot P1 P2 P3 * *
  66637. **
  66638. ** Jump to P2 if the value in register P1 is False. The value
  66639. ** is considered false if it has a numeric value of zero. If the value
  66640. ** in P1 is NULL then take the jump if P3 is zero.
  66641. */
  66642. case OP_If: /* jump, in1 */
  66643. case OP_IfNot: { /* jump, in1 */
  66644. #if 0 /* local variables moved into u.an */
  66645. int c;
  66646. #endif /* local variables moved into u.an */
  66647. pIn1 = &aMem[pOp->p1];
  66648. if( pIn1->flags & MEM_Null ){
  66649. u.an.c = pOp->p3;
  66650. }else{
  66651. #ifdef SQLITE_OMIT_FLOATING_POINT
  66652. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  66653. #else
  66654. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  66655. #endif
  66656. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  66657. }
  66658. if( u.an.c ){
  66659. pc = pOp->p2-1;
  66660. }
  66661. break;
  66662. }
  66663. /* Opcode: IsNull P1 P2 * * *
  66664. **
  66665. ** Jump to P2 if the value in register P1 is NULL.
  66666. */
  66667. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  66668. pIn1 = &aMem[pOp->p1];
  66669. if( (pIn1->flags & MEM_Null)!=0 ){
  66670. pc = pOp->p2 - 1;
  66671. }
  66672. break;
  66673. }
  66674. /* Opcode: NotNull P1 P2 * * *
  66675. **
  66676. ** Jump to P2 if the value in register P1 is not NULL.
  66677. */
  66678. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  66679. pIn1 = &aMem[pOp->p1];
  66680. if( (pIn1->flags & MEM_Null)==0 ){
  66681. pc = pOp->p2 - 1;
  66682. }
  66683. break;
  66684. }
  66685. /* Opcode: Column P1 P2 P3 P4 P5
  66686. **
  66687. ** Interpret the data that cursor P1 points to as a structure built using
  66688. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  66689. ** information about the format of the data.) Extract the P2-th column
  66690. ** from this record. If there are less that (P2+1)
  66691. ** values in the record, extract a NULL.
  66692. **
  66693. ** The value extracted is stored in register P3.
  66694. **
  66695. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  66696. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  66697. ** the result.
  66698. **
  66699. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  66700. ** then the cache of the cursor is reset prior to extracting the column.
  66701. ** The first OP_Column against a pseudo-table after the value of the content
  66702. ** register has changed should have this bit set.
  66703. **
  66704. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  66705. ** the result is guaranteed to only be used as the argument of a length()
  66706. ** or typeof() function, respectively. The loading of large blobs can be
  66707. ** skipped for length() and all content loading can be skipped for typeof().
  66708. */
  66709. case OP_Column: {
  66710. #if 0 /* local variables moved into u.ao */
  66711. u32 payloadSize; /* Number of bytes in the record */
  66712. i64 payloadSize64; /* Number of bytes in the record */
  66713. int p1; /* P1 value of the opcode */
  66714. int p2; /* column number to retrieve */
  66715. VdbeCursor *pC; /* The VDBE cursor */
  66716. char *zRec; /* Pointer to complete record-data */
  66717. BtCursor *pCrsr; /* The BTree cursor */
  66718. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  66719. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  66720. int nField; /* number of fields in the record */
  66721. int len; /* The length of the serialized data for the column */
  66722. int i; /* Loop counter */
  66723. char *zData; /* Part of the record being decoded */
  66724. Mem *pDest; /* Where to write the extracted value */
  66725. Mem sMem; /* For storing the record being decoded */
  66726. u8 *zIdx; /* Index into header */
  66727. u8 *zEndHdr; /* Pointer to first byte after the header */
  66728. u32 offset; /* Offset into the data */
  66729. u32 szField; /* Number of bytes in the content of a field */
  66730. int szHdr; /* Size of the header size field at start of record */
  66731. int avail; /* Number of bytes of available data */
  66732. u32 t; /* A type code from the record header */
  66733. Mem *pReg; /* PseudoTable input register */
  66734. #endif /* local variables moved into u.ao */
  66735. u.ao.p1 = pOp->p1;
  66736. u.ao.p2 = pOp->p2;
  66737. u.ao.pC = 0;
  66738. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  66739. assert( u.ao.p1<p->nCursor );
  66740. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66741. u.ao.pDest = &aMem[pOp->p3];
  66742. memAboutToChange(p, u.ao.pDest);
  66743. u.ao.zRec = 0;
  66744. /* This block sets the variable u.ao.payloadSize to be the total number of
  66745. ** bytes in the record.
  66746. **
  66747. ** u.ao.zRec is set to be the complete text of the record if it is available.
  66748. ** The complete record text is always available for pseudo-tables
  66749. ** If the record is stored in a cursor, the complete record text
  66750. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  66751. ** If the data is unavailable, u.ao.zRec is set to NULL.
  66752. **
  66753. ** We also compute the number of columns in the record. For cursors,
  66754. ** the number of columns is stored in the VdbeCursor.nField element.
  66755. */
  66756. u.ao.pC = p->apCsr[u.ao.p1];
  66757. assert( u.ao.pC!=0 );
  66758. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66759. assert( u.ao.pC->pVtabCursor==0 );
  66760. #endif
  66761. u.ao.pCrsr = u.ao.pC->pCursor;
  66762. if( u.ao.pCrsr!=0 ){
  66763. /* The record is stored in a B-Tree */
  66764. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  66765. if( rc ) goto abort_due_to_error;
  66766. if( u.ao.pC->nullRow ){
  66767. u.ao.payloadSize = 0;
  66768. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  66769. u.ao.payloadSize = u.ao.pC->payloadSize;
  66770. u.ao.zRec = (char*)u.ao.pC->aRow;
  66771. }else if( u.ao.pC->isIndex ){
  66772. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  66773. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  66774. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  66775. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  66776. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  66777. ** larger than 32 bits. */
  66778. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  66779. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  66780. }else{
  66781. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  66782. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  66783. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  66784. }
  66785. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  66786. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  66787. if( u.ao.pC->multiPseudo ){
  66788. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  66789. Deephemeralize(u.ao.pDest);
  66790. goto op_column_out;
  66791. }
  66792. assert( u.ao.pReg->flags & MEM_Blob );
  66793. assert( memIsValid(u.ao.pReg) );
  66794. u.ao.payloadSize = u.ao.pReg->n;
  66795. u.ao.zRec = u.ao.pReg->z;
  66796. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  66797. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  66798. }else{
  66799. /* Consider the row to be NULL */
  66800. u.ao.payloadSize = 0;
  66801. }
  66802. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  66803. ** nullRow or because of a corrupt database. */
  66804. if( u.ao.payloadSize==0 ){
  66805. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  66806. goto op_column_out;
  66807. }
  66808. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  66809. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66810. goto too_big;
  66811. }
  66812. u.ao.nField = u.ao.pC->nField;
  66813. assert( u.ao.p2<u.ao.nField );
  66814. /* Read and parse the table header. Store the results of the parse
  66815. ** into the record header cache fields of the cursor.
  66816. */
  66817. u.ao.aType = u.ao.pC->aType;
  66818. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  66819. u.ao.aOffset = u.ao.pC->aOffset;
  66820. }else{
  66821. assert(u.ao.aType);
  66822. u.ao.avail = 0;
  66823. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  66824. u.ao.pC->payloadSize = u.ao.payloadSize;
  66825. u.ao.pC->cacheStatus = p->cacheCtr;
  66826. /* Figure out how many bytes are in the header */
  66827. if( u.ao.zRec ){
  66828. u.ao.zData = u.ao.zRec;
  66829. }else{
  66830. if( u.ao.pC->isIndex ){
  66831. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  66832. }else{
  66833. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  66834. }
  66835. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  66836. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  66837. ** having to make additional calls to fetch the content portion of
  66838. ** the record.
  66839. */
  66840. assert( u.ao.avail>=0 );
  66841. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  66842. u.ao.zRec = u.ao.zData;
  66843. u.ao.pC->aRow = (u8*)u.ao.zData;
  66844. }else{
  66845. u.ao.pC->aRow = 0;
  66846. }
  66847. }
  66848. /* The following assert is true in all cases except when
  66849. ** the database file has been corrupted externally.
  66850. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  66851. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  66852. /* Make sure a corrupt database has not given us an oversize header.
  66853. ** Do this now to avoid an oversize memory allocation.
  66854. **
  66855. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  66856. ** types use so much data space that there can only be 4096 and 32 of
  66857. ** them, respectively. So the maximum header length results from a
  66858. ** 3-byte type for each of the maximum of 32768 columns plus three
  66859. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  66860. */
  66861. if( u.ao.offset > 98307 ){
  66862. rc = SQLITE_CORRUPT_BKPT;
  66863. goto op_column_out;
  66864. }
  66865. /* Compute in u.ao.len the number of bytes of data we need to read in order
  66866. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  66867. ** u.ao.nField might be significantly less than the true number of columns
  66868. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  66869. ** We want to minimize u.ao.len in order to limit the size of the memory
  66870. ** allocation, especially if a corrupt database file has caused u.ao.offset
  66871. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  66872. ** still exceed Robson memory allocation limits on some configurations.
  66873. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  66874. ** will likely be much smaller since u.ao.nField will likely be less than
  66875. ** 20 or so. This insures that Robson memory allocation limits are
  66876. ** not exceeded even for corrupt database files.
  66877. */
  66878. u.ao.len = u.ao.nField*5 + 3;
  66879. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  66880. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  66881. ** record header in most cases. But they will fail to get the complete
  66882. ** record header if the record header does not fit on a single page
  66883. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  66884. ** acquire the complete header text.
  66885. */
  66886. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  66887. u.ao.sMem.flags = 0;
  66888. u.ao.sMem.db = 0;
  66889. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  66890. if( rc!=SQLITE_OK ){
  66891. goto op_column_out;
  66892. }
  66893. u.ao.zData = u.ao.sMem.z;
  66894. }
  66895. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  66896. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  66897. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  66898. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  66899. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  66900. ** of the record to the start of the data for the u.ao.i-th column
  66901. */
  66902. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  66903. if( u.ao.zIdx<u.ao.zEndHdr ){
  66904. u.ao.aOffset[u.ao.i] = u.ao.offset;
  66905. if( u.ao.zIdx[0]<0x80 ){
  66906. u.ao.t = u.ao.zIdx[0];
  66907. u.ao.zIdx++;
  66908. }else{
  66909. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  66910. }
  66911. u.ao.aType[u.ao.i] = u.ao.t;
  66912. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  66913. u.ao.offset += u.ao.szField;
  66914. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  66915. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  66916. break;
  66917. }
  66918. }else{
  66919. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  66920. ** record than SetNumColumns indicated there are columns in the
  66921. ** table. Set the u.ao.offset for any extra columns not present in
  66922. ** the record to 0. This tells code below to store the default value
  66923. ** for the column instead of deserializing a value from the record.
  66924. */
  66925. u.ao.aOffset[u.ao.i] = 0;
  66926. }
  66927. }
  66928. sqlite3VdbeMemRelease(&u.ao.sMem);
  66929. u.ao.sMem.flags = MEM_Null;
  66930. /* If we have read more header data than was contained in the header,
  66931. ** or if the end of the last field appears to be past the end of the
  66932. ** record, or if the end of the last field appears to be before the end
  66933. ** of the record (when all fields present), then we must be dealing
  66934. ** with a corrupt database.
  66935. */
  66936. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  66937. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  66938. rc = SQLITE_CORRUPT_BKPT;
  66939. goto op_column_out;
  66940. }
  66941. }
  66942. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  66943. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  66944. ** then there are not enough fields in the record to satisfy the
  66945. ** request. In this case, set the value NULL or to P4 if P4 is
  66946. ** a pointer to a Mem object.
  66947. */
  66948. if( u.ao.aOffset[u.ao.p2] ){
  66949. assert( rc==SQLITE_OK );
  66950. if( u.ao.zRec ){
  66951. /* This is the common case where the whole row fits on a single page */
  66952. VdbeMemRelease(u.ao.pDest);
  66953. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  66954. }else{
  66955. /* This branch happens only when the row overflows onto multiple pages */
  66956. u.ao.t = u.ao.aType[u.ao.p2];
  66957. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  66958. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  66959. ){
  66960. /* Content is irrelevant for the typeof() function and for
  66961. ** the length(X) function if X is a blob. So we might as well use
  66962. ** bogus content rather than reading content from disk. NULL works
  66963. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  66964. ** will work for everything else. */
  66965. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  66966. }else{
  66967. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  66968. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  66969. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  66970. &u.ao.sMem);
  66971. if( rc!=SQLITE_OK ){
  66972. goto op_column_out;
  66973. }
  66974. u.ao.zData = u.ao.sMem.z;
  66975. }
  66976. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  66977. }
  66978. u.ao.pDest->enc = encoding;
  66979. }else{
  66980. if( pOp->p4type==P4_MEM ){
  66981. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  66982. }else{
  66983. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  66984. }
  66985. }
  66986. /* If we dynamically allocated space to hold the data (in the
  66987. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  66988. ** dynamically allocated space over to the u.ao.pDest structure.
  66989. ** This prevents a memory copy.
  66990. */
  66991. if( u.ao.sMem.zMalloc ){
  66992. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  66993. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  66994. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  66995. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  66996. u.ao.pDest->flags |= MEM_Term;
  66997. u.ao.pDest->z = u.ao.sMem.z;
  66998. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  66999. }
  67000. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  67001. op_column_out:
  67002. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  67003. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  67004. break;
  67005. }
  67006. /* Opcode: Affinity P1 P2 * P4 *
  67007. **
  67008. ** Apply affinities to a range of P2 registers starting with P1.
  67009. **
  67010. ** P4 is a string that is P2 characters long. The nth character of the
  67011. ** string indicates the column affinity that should be used for the nth
  67012. ** memory cell in the range.
  67013. */
  67014. case OP_Affinity: {
  67015. #if 0 /* local variables moved into u.ap */
  67016. const char *zAffinity; /* The affinity to be applied */
  67017. char cAff; /* A single character of affinity */
  67018. #endif /* local variables moved into u.ap */
  67019. u.ap.zAffinity = pOp->p4.z;
  67020. assert( u.ap.zAffinity!=0 );
  67021. assert( u.ap.zAffinity[pOp->p2]==0 );
  67022. pIn1 = &aMem[pOp->p1];
  67023. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  67024. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  67025. assert( memIsValid(pIn1) );
  67026. ExpandBlob(pIn1);
  67027. applyAffinity(pIn1, u.ap.cAff, encoding);
  67028. pIn1++;
  67029. }
  67030. break;
  67031. }
  67032. /* Opcode: MakeRecord P1 P2 P3 P4 *
  67033. **
  67034. ** Convert P2 registers beginning with P1 into the [record format]
  67035. ** use as a data record in a database table or as a key
  67036. ** in an index. The OP_Column opcode can decode the record later.
  67037. **
  67038. ** P4 may be a string that is P2 characters long. The nth character of the
  67039. ** string indicates the column affinity that should be used for the nth
  67040. ** field of the index key.
  67041. **
  67042. ** The mapping from character to affinity is given by the SQLITE_AFF_
  67043. ** macros defined in sqliteInt.h.
  67044. **
  67045. ** If P4 is NULL then all index fields have the affinity NONE.
  67046. */
  67047. case OP_MakeRecord: {
  67048. #if 0 /* local variables moved into u.aq */
  67049. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  67050. Mem *pRec; /* The new record */
  67051. u64 nData; /* Number of bytes of data space */
  67052. int nHdr; /* Number of bytes of header space */
  67053. i64 nByte; /* Data space required for this record */
  67054. int nZero; /* Number of zero bytes at the end of the record */
  67055. int nVarint; /* Number of bytes in a varint */
  67056. u32 serial_type; /* Type field */
  67057. Mem *pData0; /* First field to be combined into the record */
  67058. Mem *pLast; /* Last field of the record */
  67059. int nField; /* Number of fields in the record */
  67060. char *zAffinity; /* The affinity string for the record */
  67061. int file_format; /* File format to use for encoding */
  67062. int i; /* Space used in zNewRecord[] */
  67063. int len; /* Length of a field */
  67064. #endif /* local variables moved into u.aq */
  67065. /* Assuming the record contains N fields, the record format looks
  67066. ** like this:
  67067. **
  67068. ** ------------------------------------------------------------------------
  67069. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  67070. ** ------------------------------------------------------------------------
  67071. **
  67072. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  67073. ** and so froth.
  67074. **
  67075. ** Each type field is a varint representing the serial type of the
  67076. ** corresponding data element (see sqlite3VdbeSerialType()). The
  67077. ** hdr-size field is also a varint which is the offset from the beginning
  67078. ** of the record to data0.
  67079. */
  67080. u.aq.nData = 0; /* Number of bytes of data space */
  67081. u.aq.nHdr = 0; /* Number of bytes of header space */
  67082. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  67083. u.aq.nField = pOp->p1;
  67084. u.aq.zAffinity = pOp->p4.z;
  67085. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 );
  67086. u.aq.pData0 = &aMem[u.aq.nField];
  67087. u.aq.nField = pOp->p2;
  67088. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  67089. u.aq.file_format = p->minWriteFileFormat;
  67090. /* Identify the output register */
  67091. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  67092. pOut = &aMem[pOp->p3];
  67093. memAboutToChange(p, pOut);
  67094. /* Loop through the elements that will make up the record to figure
  67095. ** out how much space is required for the new record.
  67096. */
  67097. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  67098. assert( memIsValid(u.aq.pRec) );
  67099. if( u.aq.zAffinity ){
  67100. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  67101. }
  67102. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  67103. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  67104. }
  67105. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  67106. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  67107. u.aq.nData += u.aq.len;
  67108. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  67109. if( u.aq.pRec->flags & MEM_Zero ){
  67110. /* Only pure zero-filled BLOBs can be input to this Opcode.
  67111. ** We do not allow blobs with a prefix and a zero-filled tail. */
  67112. u.aq.nZero += u.aq.pRec->u.nZero;
  67113. }else if( u.aq.len ){
  67114. u.aq.nZero = 0;
  67115. }
  67116. }
  67117. /* Add the initial header varint and total the size */
  67118. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  67119. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  67120. u.aq.nHdr++;
  67121. }
  67122. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  67123. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67124. goto too_big;
  67125. }
  67126. /* Make sure the output register has a buffer large enough to store
  67127. ** the new record. The output register (pOp->p3) is not allowed to
  67128. ** be one of the input registers (because the following call to
  67129. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  67130. */
  67131. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  67132. goto no_mem;
  67133. }
  67134. u.aq.zNewRecord = (u8 *)pOut->z;
  67135. /* Write the record */
  67136. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  67137. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  67138. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  67139. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  67140. }
  67141. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  67142. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  67143. }
  67144. assert( u.aq.i==u.aq.nByte );
  67145. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  67146. pOut->n = (int)u.aq.nByte;
  67147. pOut->flags = MEM_Blob | MEM_Dyn;
  67148. pOut->xDel = 0;
  67149. if( u.aq.nZero ){
  67150. pOut->u.nZero = u.aq.nZero;
  67151. pOut->flags |= MEM_Zero;
  67152. }
  67153. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  67154. REGISTER_TRACE(pOp->p3, pOut);
  67155. UPDATE_MAX_BLOBSIZE(pOut);
  67156. break;
  67157. }
  67158. /* Opcode: Count P1 P2 * * *
  67159. **
  67160. ** Store the number of entries (an integer value) in the table or index
  67161. ** opened by cursor P1 in register P2
  67162. */
  67163. #ifndef SQLITE_OMIT_BTREECOUNT
  67164. case OP_Count: { /* out2-prerelease */
  67165. #if 0 /* local variables moved into u.ar */
  67166. i64 nEntry;
  67167. BtCursor *pCrsr;
  67168. #endif /* local variables moved into u.ar */
  67169. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  67170. if( ALWAYS(u.ar.pCrsr) ){
  67171. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  67172. }else{
  67173. u.ar.nEntry = 0;
  67174. }
  67175. pOut->u.i = u.ar.nEntry;
  67176. break;
  67177. }
  67178. #endif
  67179. /* Opcode: Savepoint P1 * * P4 *
  67180. **
  67181. ** Open, release or rollback the savepoint named by parameter P4, depending
  67182. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  67183. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  67184. */
  67185. case OP_Savepoint: {
  67186. #if 0 /* local variables moved into u.as */
  67187. int p1; /* Value of P1 operand */
  67188. char *zName; /* Name of savepoint */
  67189. int nName;
  67190. Savepoint *pNew;
  67191. Savepoint *pSavepoint;
  67192. Savepoint *pTmp;
  67193. int iSavepoint;
  67194. int ii;
  67195. #endif /* local variables moved into u.as */
  67196. u.as.p1 = pOp->p1;
  67197. u.as.zName = pOp->p4.z;
  67198. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  67199. ** transaction, then there cannot be any savepoints.
  67200. */
  67201. assert( db->pSavepoint==0 || db->autoCommit==0 );
  67202. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  67203. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  67204. assert( checkSavepointCount(db) );
  67205. assert( p->bIsReader );
  67206. if( u.as.p1==SAVEPOINT_BEGIN ){
  67207. if( db->nVdbeWrite>0 ){
  67208. /* A new savepoint cannot be created if there are active write
  67209. ** statements (i.e. open read/write incremental blob handles).
  67210. */
  67211. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  67212. "SQL statements in progress");
  67213. rc = SQLITE_BUSY;
  67214. }else{
  67215. u.as.nName = sqlite3Strlen30(u.as.zName);
  67216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67217. /* This call is Ok even if this savepoint is actually a transaction
  67218. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  67219. ** If this is a transaction savepoint being opened, it is guaranteed
  67220. ** that the db->aVTrans[] array is empty. */
  67221. assert( db->autoCommit==0 || db->nVTrans==0 );
  67222. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  67223. db->nStatement+db->nSavepoint);
  67224. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67225. #endif
  67226. /* Create a new savepoint structure. */
  67227. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  67228. if( u.as.pNew ){
  67229. u.as.pNew->zName = (char *)&u.as.pNew[1];
  67230. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  67231. /* If there is no open transaction, then mark this as a special
  67232. ** "transaction savepoint". */
  67233. if( db->autoCommit ){
  67234. db->autoCommit = 0;
  67235. db->isTransactionSavepoint = 1;
  67236. }else{
  67237. db->nSavepoint++;
  67238. }
  67239. /* Link the new savepoint into the database handle's list. */
  67240. u.as.pNew->pNext = db->pSavepoint;
  67241. db->pSavepoint = u.as.pNew;
  67242. u.as.pNew->nDeferredCons = db->nDeferredCons;
  67243. u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
  67244. }
  67245. }
  67246. }else{
  67247. u.as.iSavepoint = 0;
  67248. /* Find the named savepoint. If there is no such savepoint, then an
  67249. ** an error is returned to the user. */
  67250. for(
  67251. u.as.pSavepoint = db->pSavepoint;
  67252. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  67253. u.as.pSavepoint = u.as.pSavepoint->pNext
  67254. ){
  67255. u.as.iSavepoint++;
  67256. }
  67257. if( !u.as.pSavepoint ){
  67258. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  67259. rc = SQLITE_ERROR;
  67260. }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
  67261. /* It is not possible to release (commit) a savepoint if there are
  67262. ** active write statements.
  67263. */
  67264. sqlite3SetString(&p->zErrMsg, db,
  67265. "cannot release savepoint - SQL statements in progress"
  67266. );
  67267. rc = SQLITE_BUSY;
  67268. }else{
  67269. /* Determine whether or not this is a transaction savepoint. If so,
  67270. ** and this is a RELEASE command, then the current transaction
  67271. ** is committed.
  67272. */
  67273. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  67274. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  67275. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67276. goto vdbe_return;
  67277. }
  67278. db->autoCommit = 1;
  67279. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67280. p->pc = pc;
  67281. db->autoCommit = 0;
  67282. p->rc = rc = SQLITE_BUSY;
  67283. goto vdbe_return;
  67284. }
  67285. db->isTransactionSavepoint = 0;
  67286. rc = p->rc;
  67287. }else{
  67288. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  67289. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  67290. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  67291. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  67292. }
  67293. }
  67294. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  67295. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  67296. if( rc!=SQLITE_OK ){
  67297. goto abort_due_to_error;
  67298. }
  67299. }
  67300. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  67301. sqlite3ExpirePreparedStatements(db);
  67302. sqlite3ResetAllSchemasOfConnection(db);
  67303. db->flags = (db->flags | SQLITE_InternChanges);
  67304. }
  67305. }
  67306. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  67307. ** savepoints nested inside of the savepoint being operated on. */
  67308. while( db->pSavepoint!=u.as.pSavepoint ){
  67309. u.as.pTmp = db->pSavepoint;
  67310. db->pSavepoint = u.as.pTmp->pNext;
  67311. sqlite3DbFree(db, u.as.pTmp);
  67312. db->nSavepoint--;
  67313. }
  67314. /* If it is a RELEASE, then destroy the savepoint being operated on
  67315. ** too. If it is a ROLLBACK TO, then set the number of deferred
  67316. ** constraint violations present in the database to the value stored
  67317. ** when the savepoint was created. */
  67318. if( u.as.p1==SAVEPOINT_RELEASE ){
  67319. assert( u.as.pSavepoint==db->pSavepoint );
  67320. db->pSavepoint = u.as.pSavepoint->pNext;
  67321. sqlite3DbFree(db, u.as.pSavepoint);
  67322. if( !isTransaction ){
  67323. db->nSavepoint--;
  67324. }
  67325. }else{
  67326. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  67327. db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
  67328. }
  67329. if( !isTransaction ){
  67330. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  67331. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67332. }
  67333. }
  67334. }
  67335. break;
  67336. }
  67337. /* Opcode: AutoCommit P1 P2 * * *
  67338. **
  67339. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  67340. ** back any currently active btree transactions. If there are any active
  67341. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  67342. ** there are active writing VMs or active VMs that use shared cache.
  67343. **
  67344. ** This instruction causes the VM to halt.
  67345. */
  67346. case OP_AutoCommit: {
  67347. #if 0 /* local variables moved into u.at */
  67348. int desiredAutoCommit;
  67349. int iRollback;
  67350. int turnOnAC;
  67351. #endif /* local variables moved into u.at */
  67352. u.at.desiredAutoCommit = pOp->p1;
  67353. u.at.iRollback = pOp->p2;
  67354. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  67355. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  67356. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  67357. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  67358. assert( p->bIsReader );
  67359. #if 0
  67360. if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
  67361. /* If this instruction implements a ROLLBACK and other VMs are
  67362. ** still running, and a transaction is active, return an error indicating
  67363. ** that the other VMs must complete first.
  67364. */
  67365. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  67366. "SQL statements in progress");
  67367. rc = SQLITE_BUSY;
  67368. }else
  67369. #endif
  67370. if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
  67371. /* If this instruction implements a COMMIT and other VMs are writing
  67372. ** return an error indicating that the other VMs must complete first.
  67373. */
  67374. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  67375. "SQL statements in progress");
  67376. rc = SQLITE_BUSY;
  67377. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  67378. if( u.at.iRollback ){
  67379. assert( u.at.desiredAutoCommit==1 );
  67380. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  67381. db->autoCommit = 1;
  67382. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67383. goto vdbe_return;
  67384. }else{
  67385. db->autoCommit = (u8)u.at.desiredAutoCommit;
  67386. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67387. p->pc = pc;
  67388. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  67389. p->rc = rc = SQLITE_BUSY;
  67390. goto vdbe_return;
  67391. }
  67392. }
  67393. assert( db->nStatement==0 );
  67394. sqlite3CloseSavepoints(db);
  67395. if( p->rc==SQLITE_OK ){
  67396. rc = SQLITE_DONE;
  67397. }else{
  67398. rc = SQLITE_ERROR;
  67399. }
  67400. goto vdbe_return;
  67401. }else{
  67402. sqlite3SetString(&p->zErrMsg, db,
  67403. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  67404. (u.at.iRollback)?"cannot rollback - no transaction is active":
  67405. "cannot commit - no transaction is active"));
  67406. rc = SQLITE_ERROR;
  67407. }
  67408. break;
  67409. }
  67410. /* Opcode: Transaction P1 P2 * * *
  67411. **
  67412. ** Begin a transaction. The transaction ends when a Commit or Rollback
  67413. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  67414. ** transaction might also be rolled back if an error is encountered.
  67415. **
  67416. ** P1 is the index of the database file on which the transaction is
  67417. ** started. Index 0 is the main database file and index 1 is the
  67418. ** file used for temporary tables. Indices of 2 or more are used for
  67419. ** attached databases.
  67420. **
  67421. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  67422. ** obtained on the database file when a write-transaction is started. No
  67423. ** other process can start another write transaction while this transaction is
  67424. ** underway. Starting a write transaction also creates a rollback journal. A
  67425. ** write transaction must be started before any changes can be made to the
  67426. ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  67427. ** also obtained on the file.
  67428. **
  67429. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  67430. ** true (this flag is set if the Vdbe may modify more than one row and may
  67431. ** throw an ABORT exception), a statement transaction may also be opened.
  67432. ** More specifically, a statement transaction is opened iff the database
  67433. ** connection is currently not in autocommit mode, or if there are other
  67434. ** active statements. A statement transaction allows the changes made by this
  67435. ** VDBE to be rolled back after an error without having to roll back the
  67436. ** entire transaction. If no error is encountered, the statement transaction
  67437. ** will automatically commit when the VDBE halts.
  67438. **
  67439. ** If P2 is zero, then a read-lock is obtained on the database file.
  67440. */
  67441. case OP_Transaction: {
  67442. #if 0 /* local variables moved into u.au */
  67443. Btree *pBt;
  67444. #endif /* local variables moved into u.au */
  67445. assert( p->bIsReader );
  67446. assert( p->readOnly==0 || pOp->p2==0 );
  67447. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67448. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67449. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  67450. rc = SQLITE_READONLY;
  67451. goto abort_due_to_error;
  67452. }
  67453. u.au.pBt = db->aDb[pOp->p1].pBt;
  67454. if( u.au.pBt ){
  67455. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  67456. if( rc==SQLITE_BUSY ){
  67457. p->pc = pc;
  67458. p->rc = rc = SQLITE_BUSY;
  67459. goto vdbe_return;
  67460. }
  67461. if( rc!=SQLITE_OK ){
  67462. goto abort_due_to_error;
  67463. }
  67464. if( pOp->p2 && p->usesStmtJournal
  67465. && (db->autoCommit==0 || db->nVdbeRead>1)
  67466. ){
  67467. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  67468. if( p->iStatement==0 ){
  67469. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  67470. db->nStatement++;
  67471. p->iStatement = db->nSavepoint + db->nStatement;
  67472. }
  67473. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  67474. if( rc==SQLITE_OK ){
  67475. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  67476. }
  67477. /* Store the current value of the database handles deferred constraint
  67478. ** counter. If the statement transaction needs to be rolled back,
  67479. ** the value of this counter needs to be restored too. */
  67480. p->nStmtDefCons = db->nDeferredCons;
  67481. p->nStmtDefImmCons = db->nDeferredImmCons;
  67482. }
  67483. }
  67484. break;
  67485. }
  67486. /* Opcode: ReadCookie P1 P2 P3 * *
  67487. **
  67488. ** Read cookie number P3 from database P1 and write it into register P2.
  67489. ** P3==1 is the schema version. P3==2 is the database format.
  67490. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  67491. ** the main database file and P1==1 is the database file used to store
  67492. ** temporary tables.
  67493. **
  67494. ** There must be a read-lock on the database (either a transaction
  67495. ** must be started or there must be an open cursor) before
  67496. ** executing this instruction.
  67497. */
  67498. case OP_ReadCookie: { /* out2-prerelease */
  67499. #if 0 /* local variables moved into u.av */
  67500. int iMeta;
  67501. int iDb;
  67502. int iCookie;
  67503. #endif /* local variables moved into u.av */
  67504. assert( p->bIsReader );
  67505. u.av.iDb = pOp->p1;
  67506. u.av.iCookie = pOp->p3;
  67507. assert( pOp->p3<SQLITE_N_BTREE_META );
  67508. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  67509. assert( db->aDb[u.av.iDb].pBt!=0 );
  67510. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  67511. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  67512. pOut->u.i = u.av.iMeta;
  67513. break;
  67514. }
  67515. /* Opcode: SetCookie P1 P2 P3 * *
  67516. **
  67517. ** Write the content of register P3 (interpreted as an integer)
  67518. ** into cookie number P2 of database P1. P2==1 is the schema version.
  67519. ** P2==2 is the database format. P2==3 is the recommended pager cache
  67520. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  67521. ** database file used to store temporary tables.
  67522. **
  67523. ** A transaction must be started before executing this opcode.
  67524. */
  67525. case OP_SetCookie: { /* in3 */
  67526. #if 0 /* local variables moved into u.aw */
  67527. Db *pDb;
  67528. #endif /* local variables moved into u.aw */
  67529. assert( pOp->p2<SQLITE_N_BTREE_META );
  67530. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67531. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67532. assert( p->readOnly==0 );
  67533. u.aw.pDb = &db->aDb[pOp->p1];
  67534. assert( u.aw.pDb->pBt!=0 );
  67535. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67536. pIn3 = &aMem[pOp->p3];
  67537. sqlite3VdbeMemIntegerify(pIn3);
  67538. /* See note about index shifting on OP_ReadCookie */
  67539. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  67540. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  67541. /* When the schema cookie changes, record the new cookie internally */
  67542. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  67543. db->flags |= SQLITE_InternChanges;
  67544. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  67545. /* Record changes in the file format */
  67546. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  67547. }
  67548. if( pOp->p1==1 ){
  67549. /* Invalidate all prepared statements whenever the TEMP database
  67550. ** schema is changed. Ticket #1644 */
  67551. sqlite3ExpirePreparedStatements(db);
  67552. p->expired = 0;
  67553. }
  67554. break;
  67555. }
  67556. /* Opcode: VerifyCookie P1 P2 P3 * *
  67557. **
  67558. ** Check the value of global database parameter number 0 (the
  67559. ** schema version) and make sure it is equal to P2 and that the
  67560. ** generation counter on the local schema parse equals P3.
  67561. **
  67562. ** P1 is the database number which is 0 for the main database file
  67563. ** and 1 for the file holding temporary tables and some higher number
  67564. ** for auxiliary databases.
  67565. **
  67566. ** The cookie changes its value whenever the database schema changes.
  67567. ** This operation is used to detect when that the cookie has changed
  67568. ** and that the current process needs to reread the schema.
  67569. **
  67570. ** Either a transaction needs to have been started or an OP_Open needs
  67571. ** to be executed (to establish a read lock) before this opcode is
  67572. ** invoked.
  67573. */
  67574. case OP_VerifyCookie: {
  67575. #if 0 /* local variables moved into u.ax */
  67576. int iMeta;
  67577. int iGen;
  67578. Btree *pBt;
  67579. #endif /* local variables moved into u.ax */
  67580. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67581. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67582. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67583. assert( p->bIsReader );
  67584. u.ax.pBt = db->aDb[pOp->p1].pBt;
  67585. if( u.ax.pBt ){
  67586. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  67587. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  67588. }else{
  67589. u.ax.iGen = u.ax.iMeta = 0;
  67590. }
  67591. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  67592. sqlite3DbFree(db, p->zErrMsg);
  67593. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  67594. /* If the schema-cookie from the database file matches the cookie
  67595. ** stored with the in-memory representation of the schema, do
  67596. ** not reload the schema from the database file.
  67597. **
  67598. ** If virtual-tables are in use, this is not just an optimization.
  67599. ** Often, v-tables store their data in other SQLite tables, which
  67600. ** are queried from within xNext() and other v-table methods using
  67601. ** prepared queries. If such a query is out-of-date, we do not want to
  67602. ** discard the database schema, as the user code implementing the
  67603. ** v-table would have to be ready for the sqlite3_vtab structure itself
  67604. ** to be invalidated whenever sqlite3_step() is called from within
  67605. ** a v-table method.
  67606. */
  67607. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  67608. sqlite3ResetOneSchema(db, pOp->p1);
  67609. }
  67610. p->expired = 1;
  67611. rc = SQLITE_SCHEMA;
  67612. }
  67613. break;
  67614. }
  67615. /* Opcode: OpenRead P1 P2 P3 P4 P5
  67616. **
  67617. ** Open a read-only cursor for the database table whose root page is
  67618. ** P2 in a database file. The database file is determined by P3.
  67619. ** P3==0 means the main database, P3==1 means the database used for
  67620. ** temporary tables, and P3>1 means used the corresponding attached
  67621. ** database. Give the new cursor an identifier of P1. The P1
  67622. ** values need not be contiguous but all P1 values should be small integers.
  67623. ** It is an error for P1 to be negative.
  67624. **
  67625. ** If P5!=0 then use the content of register P2 as the root page, not
  67626. ** the value of P2 itself.
  67627. **
  67628. ** There will be a read lock on the database whenever there is an
  67629. ** open cursor. If the database was unlocked prior to this instruction
  67630. ** then a read lock is acquired as part of this instruction. A read
  67631. ** lock allows other processes to read the database but prohibits
  67632. ** any other process from modifying the database. The read lock is
  67633. ** released when all cursors are closed. If this instruction attempts
  67634. ** to get a read lock but fails, the script terminates with an
  67635. ** SQLITE_BUSY error code.
  67636. **
  67637. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67638. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67639. ** structure, then said structure defines the content and collating
  67640. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67641. ** value, it is set to the number of columns in the table.
  67642. **
  67643. ** See also OpenWrite.
  67644. */
  67645. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  67646. **
  67647. ** Open a read/write cursor named P1 on the table or index whose root
  67648. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  67649. ** root page.
  67650. **
  67651. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67652. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67653. ** structure, then said structure defines the content and collating
  67654. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67655. ** value, it is set to the number of columns in the table, or to the
  67656. ** largest index of any column of the table that is actually used.
  67657. **
  67658. ** This instruction works just like OpenRead except that it opens the cursor
  67659. ** in read/write mode. For a given table, there can be one or more read-only
  67660. ** cursors or a single read/write cursor but not both.
  67661. **
  67662. ** See also OpenRead.
  67663. */
  67664. case OP_OpenRead:
  67665. case OP_OpenWrite: {
  67666. #if 0 /* local variables moved into u.ay */
  67667. int nField;
  67668. KeyInfo *pKeyInfo;
  67669. int p2;
  67670. int iDb;
  67671. int wrFlag;
  67672. Btree *pX;
  67673. VdbeCursor *pCur;
  67674. Db *pDb;
  67675. #endif /* local variables moved into u.ay */
  67676. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  67677. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  67678. assert( p->bIsReader );
  67679. assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
  67680. if( p->expired ){
  67681. rc = SQLITE_ABORT;
  67682. break;
  67683. }
  67684. u.ay.nField = 0;
  67685. u.ay.pKeyInfo = 0;
  67686. u.ay.p2 = pOp->p2;
  67687. u.ay.iDb = pOp->p3;
  67688. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  67689. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  67690. u.ay.pDb = &db->aDb[u.ay.iDb];
  67691. u.ay.pX = u.ay.pDb->pBt;
  67692. assert( u.ay.pX!=0 );
  67693. if( pOp->opcode==OP_OpenWrite ){
  67694. u.ay.wrFlag = 1;
  67695. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  67696. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  67697. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  67698. }
  67699. }else{
  67700. u.ay.wrFlag = 0;
  67701. }
  67702. if( pOp->p5 & OPFLAG_P2ISREG ){
  67703. assert( u.ay.p2>0 );
  67704. assert( u.ay.p2<=(p->nMem-p->nCursor) );
  67705. pIn2 = &aMem[u.ay.p2];
  67706. assert( memIsValid(pIn2) );
  67707. assert( (pIn2->flags & MEM_Int)!=0 );
  67708. sqlite3VdbeMemIntegerify(pIn2);
  67709. u.ay.p2 = (int)pIn2->u.i;
  67710. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  67711. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  67712. ** If there were a failure, the prepared statement would have halted
  67713. ** before reaching this instruction. */
  67714. if( NEVER(u.ay.p2<2) ) {
  67715. rc = SQLITE_CORRUPT_BKPT;
  67716. goto abort_due_to_error;
  67717. }
  67718. }
  67719. if( pOp->p4type==P4_KEYINFO ){
  67720. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  67721. u.ay.pKeyInfo->enc = ENC(p->db);
  67722. u.ay.nField = u.ay.pKeyInfo->nField+1;
  67723. }else if( pOp->p4type==P4_INT32 ){
  67724. u.ay.nField = pOp->p4.i;
  67725. }
  67726. assert( pOp->p1>=0 );
  67727. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  67728. if( u.ay.pCur==0 ) goto no_mem;
  67729. u.ay.pCur->nullRow = 1;
  67730. u.ay.pCur->isOrdered = 1;
  67731. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  67732. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  67733. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  67734. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  67735. /* Since it performs no memory allocation or IO, the only value that
  67736. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  67737. assert( rc==SQLITE_OK );
  67738. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  67739. ** SQLite used to check if the root-page flags were sane at this point
  67740. ** and report database corruption if they were not, but this check has
  67741. ** since moved into the btree layer. */
  67742. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  67743. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  67744. break;
  67745. }
  67746. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  67747. **
  67748. ** Open a new cursor P1 to a transient table.
  67749. ** The cursor is always opened read/write even if
  67750. ** the main database is read-only. The ephemeral
  67751. ** table is deleted automatically when the cursor is closed.
  67752. **
  67753. ** P2 is the number of columns in the ephemeral table.
  67754. ** The cursor points to a BTree table if P4==0 and to a BTree index
  67755. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  67756. ** that defines the format of keys in the index.
  67757. **
  67758. ** This opcode was once called OpenTemp. But that created
  67759. ** confusion because the term "temp table", might refer either
  67760. ** to a TEMP table at the SQL level, or to a table opened by
  67761. ** this opcode. Then this opcode was call OpenVirtual. But
  67762. ** that created confusion with the whole virtual-table idea.
  67763. **
  67764. ** The P5 parameter can be a mask of the BTREE_* flags defined
  67765. ** in btree.h. These flags control aspects of the operation of
  67766. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  67767. ** added automatically.
  67768. */
  67769. /* Opcode: OpenAutoindex P1 P2 * P4 *
  67770. **
  67771. ** This opcode works the same as OP_OpenEphemeral. It has a
  67772. ** different name to distinguish its use. Tables created using
  67773. ** by this opcode will be used for automatically created transient
  67774. ** indices in joins.
  67775. */
  67776. case OP_OpenAutoindex:
  67777. case OP_OpenEphemeral: {
  67778. #if 0 /* local variables moved into u.az */
  67779. VdbeCursor *pCx;
  67780. #endif /* local variables moved into u.az */
  67781. static const int vfsFlags =
  67782. SQLITE_OPEN_READWRITE |
  67783. SQLITE_OPEN_CREATE |
  67784. SQLITE_OPEN_EXCLUSIVE |
  67785. SQLITE_OPEN_DELETEONCLOSE |
  67786. SQLITE_OPEN_TRANSIENT_DB;
  67787. assert( pOp->p1>=0 );
  67788. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67789. if( u.az.pCx==0 ) goto no_mem;
  67790. u.az.pCx->nullRow = 1;
  67791. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  67792. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  67793. if( rc==SQLITE_OK ){
  67794. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  67795. }
  67796. if( rc==SQLITE_OK ){
  67797. /* If a transient index is required, create it by calling
  67798. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  67799. ** opening it. If a transient table is required, just use the
  67800. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  67801. */
  67802. if( pOp->p4.pKeyInfo ){
  67803. int pgno;
  67804. assert( pOp->p4type==P4_KEYINFO );
  67805. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  67806. if( rc==SQLITE_OK ){
  67807. assert( pgno==MASTER_ROOT+1 );
  67808. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  67809. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  67810. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67811. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  67812. }
  67813. u.az.pCx->isTable = 0;
  67814. }else{
  67815. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  67816. u.az.pCx->isTable = 1;
  67817. }
  67818. }
  67819. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  67820. u.az.pCx->isIndex = !u.az.pCx->isTable;
  67821. break;
  67822. }
  67823. /* Opcode: SorterOpen P1 P2 * P4 *
  67824. **
  67825. ** This opcode works like OP_OpenEphemeral except that it opens
  67826. ** a transient index that is specifically designed to sort large
  67827. ** tables using an external merge-sort algorithm.
  67828. */
  67829. case OP_SorterOpen: {
  67830. #if 0 /* local variables moved into u.ba */
  67831. VdbeCursor *pCx;
  67832. #endif /* local variables moved into u.ba */
  67833. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67834. if( u.ba.pCx==0 ) goto no_mem;
  67835. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67836. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  67837. u.ba.pCx->isSorter = 1;
  67838. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  67839. break;
  67840. }
  67841. /* Opcode: OpenPseudo P1 P2 P3 * P5
  67842. **
  67843. ** Open a new cursor that points to a fake table that contains a single
  67844. ** row of data. The content of that one row in the content of memory
  67845. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  67846. ** MEM_Blob content contained in register P2. When P5==1, then the
  67847. ** row is represented by P3 consecutive registers beginning with P2.
  67848. **
  67849. ** A pseudo-table created by this opcode is used to hold a single
  67850. ** row output from the sorter so that the row can be decomposed into
  67851. ** individual columns using the OP_Column opcode. The OP_Column opcode
  67852. ** is the only cursor opcode that works with a pseudo-table.
  67853. **
  67854. ** P3 is the number of fields in the records that will be stored by
  67855. ** the pseudo-table.
  67856. */
  67857. case OP_OpenPseudo: {
  67858. #if 0 /* local variables moved into u.bb */
  67859. VdbeCursor *pCx;
  67860. #endif /* local variables moved into u.bb */
  67861. assert( pOp->p1>=0 );
  67862. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  67863. if( u.bb.pCx==0 ) goto no_mem;
  67864. u.bb.pCx->nullRow = 1;
  67865. u.bb.pCx->pseudoTableReg = pOp->p2;
  67866. u.bb.pCx->isTable = 1;
  67867. u.bb.pCx->isIndex = 0;
  67868. u.bb.pCx->multiPseudo = pOp->p5;
  67869. break;
  67870. }
  67871. /* Opcode: Close P1 * * * *
  67872. **
  67873. ** Close a cursor previously opened as P1. If P1 is not
  67874. ** currently open, this instruction is a no-op.
  67875. */
  67876. case OP_Close: {
  67877. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67878. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  67879. p->apCsr[pOp->p1] = 0;
  67880. break;
  67881. }
  67882. /* Opcode: SeekGe P1 P2 P3 P4 *
  67883. **
  67884. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67885. ** use the value in register P3 as the key. If cursor P1 refers
  67886. ** to an SQL index, then P3 is the first in an array of P4 registers
  67887. ** that are used as an unpacked index key.
  67888. **
  67889. ** Reposition cursor P1 so that it points to the smallest entry that
  67890. ** is greater than or equal to the key value. If there are no records
  67891. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  67892. **
  67893. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  67894. */
  67895. /* Opcode: SeekGt P1 P2 P3 P4 *
  67896. **
  67897. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67898. ** use the value in register P3 as a key. If cursor P1 refers
  67899. ** to an SQL index, then P3 is the first in an array of P4 registers
  67900. ** that are used as an unpacked index key.
  67901. **
  67902. ** Reposition cursor P1 so that it points to the smallest entry that
  67903. ** is greater than the key value. If there are no records greater than
  67904. ** the key and P2 is not zero, then jump to P2.
  67905. **
  67906. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  67907. */
  67908. /* Opcode: SeekLt P1 P2 P3 P4 *
  67909. **
  67910. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67911. ** use the value in register P3 as a key. If cursor P1 refers
  67912. ** to an SQL index, then P3 is the first in an array of P4 registers
  67913. ** that are used as an unpacked index key.
  67914. **
  67915. ** Reposition cursor P1 so that it points to the largest entry that
  67916. ** is less than the key value. If there are no records less than
  67917. ** the key and P2 is not zero, then jump to P2.
  67918. **
  67919. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  67920. */
  67921. /* Opcode: SeekLe P1 P2 P3 P4 *
  67922. **
  67923. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67924. ** use the value in register P3 as a key. If cursor P1 refers
  67925. ** to an SQL index, then P3 is the first in an array of P4 registers
  67926. ** that are used as an unpacked index key.
  67927. **
  67928. ** Reposition cursor P1 so that it points to the largest entry that
  67929. ** is less than or equal to the key value. If there are no records
  67930. ** less than or equal to the key and P2 is not zero, then jump to P2.
  67931. **
  67932. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  67933. */
  67934. case OP_SeekLt: /* jump, in3 */
  67935. case OP_SeekLe: /* jump, in3 */
  67936. case OP_SeekGe: /* jump, in3 */
  67937. case OP_SeekGt: { /* jump, in3 */
  67938. #if 0 /* local variables moved into u.bc */
  67939. int res;
  67940. int oc;
  67941. VdbeCursor *pC;
  67942. UnpackedRecord r;
  67943. int nField;
  67944. i64 iKey; /* The rowid we are to seek to */
  67945. #endif /* local variables moved into u.bc */
  67946. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67947. assert( pOp->p2!=0 );
  67948. u.bc.pC = p->apCsr[pOp->p1];
  67949. assert( u.bc.pC!=0 );
  67950. assert( u.bc.pC->pseudoTableReg==0 );
  67951. assert( OP_SeekLe == OP_SeekLt+1 );
  67952. assert( OP_SeekGe == OP_SeekLt+2 );
  67953. assert( OP_SeekGt == OP_SeekLt+3 );
  67954. assert( u.bc.pC->isOrdered );
  67955. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  67956. u.bc.oc = pOp->opcode;
  67957. u.bc.pC->nullRow = 0;
  67958. if( u.bc.pC->isTable ){
  67959. /* The input value in P3 might be of any type: integer, real, string,
  67960. ** blob, or NULL. But it needs to be an integer before we can do
  67961. ** the seek, so covert it. */
  67962. pIn3 = &aMem[pOp->p3];
  67963. applyNumericAffinity(pIn3);
  67964. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  67965. u.bc.pC->rowidIsValid = 0;
  67966. /* If the P3 value could not be converted into an integer without
  67967. ** loss of information, then special processing is required... */
  67968. if( (pIn3->flags & MEM_Int)==0 ){
  67969. if( (pIn3->flags & MEM_Real)==0 ){
  67970. /* If the P3 value cannot be converted into any kind of a number,
  67971. ** then the seek is not possible, so jump to P2 */
  67972. pc = pOp->p2 - 1;
  67973. break;
  67974. }
  67975. /* If we reach this point, then the P3 value must be a floating
  67976. ** point number. */
  67977. assert( (pIn3->flags & MEM_Real)!=0 );
  67978. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  67979. /* The P3 value is too large in magnitude to be expressed as an
  67980. ** integer. */
  67981. u.bc.res = 1;
  67982. if( pIn3->r<0 ){
  67983. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  67984. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  67985. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67986. }
  67987. }else{
  67988. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  67989. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  67990. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67991. }
  67992. }
  67993. if( u.bc.res ){
  67994. pc = pOp->p2 - 1;
  67995. }
  67996. break;
  67997. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  67998. /* Use the ceiling() function to convert real->int */
  67999. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  68000. }else{
  68001. /* Use the floor() function to convert real->int */
  68002. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  68003. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  68004. }
  68005. }
  68006. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  68007. if( rc!=SQLITE_OK ){
  68008. goto abort_due_to_error;
  68009. }
  68010. if( u.bc.res==0 ){
  68011. u.bc.pC->rowidIsValid = 1;
  68012. u.bc.pC->lastRowid = u.bc.iKey;
  68013. }
  68014. }else{
  68015. u.bc.nField = pOp->p4.i;
  68016. assert( pOp->p4type==P4_INT32 );
  68017. assert( u.bc.nField>0 );
  68018. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  68019. u.bc.r.nField = (u16)u.bc.nField;
  68020. /* The next line of code computes as follows, only faster:
  68021. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  68022. ** u.bc.r.flags = UNPACKED_INCRKEY;
  68023. ** }else{
  68024. ** u.bc.r.flags = 0;
  68025. ** }
  68026. */
  68027. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  68028. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  68029. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  68030. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  68031. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  68032. u.bc.r.aMem = &aMem[pOp->p3];
  68033. #ifdef SQLITE_DEBUG
  68034. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  68035. #endif
  68036. ExpandBlob(u.bc.r.aMem);
  68037. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  68038. if( rc!=SQLITE_OK ){
  68039. goto abort_due_to_error;
  68040. }
  68041. u.bc.pC->rowidIsValid = 0;
  68042. }
  68043. u.bc.pC->deferredMoveto = 0;
  68044. u.bc.pC->cacheStatus = CACHE_STALE;
  68045. #ifdef SQLITE_TEST
  68046. sqlite3_search_count++;
  68047. #endif
  68048. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  68049. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  68050. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  68051. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68052. u.bc.pC->rowidIsValid = 0;
  68053. }else{
  68054. u.bc.res = 0;
  68055. }
  68056. }else{
  68057. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  68058. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  68059. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  68060. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68061. u.bc.pC->rowidIsValid = 0;
  68062. }else{
  68063. /* u.bc.res might be negative because the table is empty. Check to
  68064. ** see if this is the case.
  68065. */
  68066. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  68067. }
  68068. }
  68069. assert( pOp->p2>0 );
  68070. if( u.bc.res ){
  68071. pc = pOp->p2 - 1;
  68072. }
  68073. }else{
  68074. /* This happens when attempting to open the sqlite3_master table
  68075. ** for read access returns SQLITE_EMPTY. In this case always
  68076. ** take the jump (since there are no records in the table).
  68077. */
  68078. pc = pOp->p2 - 1;
  68079. }
  68080. break;
  68081. }
  68082. /* Opcode: Seek P1 P2 * * *
  68083. **
  68084. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  68085. ** for P1 to move so that it points to the rowid given by P2.
  68086. **
  68087. ** This is actually a deferred seek. Nothing actually happens until
  68088. ** the cursor is used to read a record. That way, if no reads
  68089. ** occur, no unnecessary I/O happens.
  68090. */
  68091. case OP_Seek: { /* in2 */
  68092. #if 0 /* local variables moved into u.bd */
  68093. VdbeCursor *pC;
  68094. #endif /* local variables moved into u.bd */
  68095. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68096. u.bd.pC = p->apCsr[pOp->p1];
  68097. assert( u.bd.pC!=0 );
  68098. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  68099. assert( u.bd.pC->isTable );
  68100. u.bd.pC->nullRow = 0;
  68101. pIn2 = &aMem[pOp->p2];
  68102. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  68103. u.bd.pC->rowidIsValid = 0;
  68104. u.bd.pC->deferredMoveto = 1;
  68105. }
  68106. break;
  68107. }
  68108. /* Opcode: Found P1 P2 P3 P4 *
  68109. **
  68110. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68111. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68112. ** record.
  68113. **
  68114. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68115. ** is a prefix of any entry in P1 then a jump is made to P2 and
  68116. ** P1 is left pointing at the matching entry.
  68117. */
  68118. /* Opcode: NotFound P1 P2 P3 P4 *
  68119. **
  68120. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68121. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68122. ** record.
  68123. **
  68124. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68125. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  68126. ** does contain an entry whose prefix matches the P3/P4 record then control
  68127. ** falls through to the next instruction and P1 is left pointing at the
  68128. ** matching entry.
  68129. **
  68130. ** See also: Found, NotExists, IsUnique
  68131. */
  68132. case OP_NotFound: /* jump, in3 */
  68133. case OP_Found: { /* jump, in3 */
  68134. #if 0 /* local variables moved into u.be */
  68135. int alreadyExists;
  68136. VdbeCursor *pC;
  68137. int res;
  68138. char *pFree;
  68139. UnpackedRecord *pIdxKey;
  68140. UnpackedRecord r;
  68141. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  68142. #endif /* local variables moved into u.be */
  68143. #ifdef SQLITE_TEST
  68144. sqlite3_found_count++;
  68145. #endif
  68146. u.be.alreadyExists = 0;
  68147. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68148. assert( pOp->p4type==P4_INT32 );
  68149. u.be.pC = p->apCsr[pOp->p1];
  68150. assert( u.be.pC!=0 );
  68151. pIn3 = &aMem[pOp->p3];
  68152. if( ALWAYS(u.be.pC->pCursor!=0) ){
  68153. assert( u.be.pC->isTable==0 );
  68154. if( pOp->p4.i>0 ){
  68155. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  68156. u.be.r.nField = (u16)pOp->p4.i;
  68157. u.be.r.aMem = pIn3;
  68158. #ifdef SQLITE_DEBUG
  68159. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  68160. #endif
  68161. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  68162. u.be.pIdxKey = &u.be.r;
  68163. }else{
  68164. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  68165. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  68166. );
  68167. if( u.be.pIdxKey==0 ) goto no_mem;
  68168. assert( pIn3->flags & MEM_Blob );
  68169. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  68170. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  68171. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  68172. }
  68173. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  68174. if( pOp->p4.i==0 ){
  68175. sqlite3DbFree(db, u.be.pFree);
  68176. }
  68177. if( rc!=SQLITE_OK ){
  68178. break;
  68179. }
  68180. u.be.alreadyExists = (u.be.res==0);
  68181. u.be.pC->deferredMoveto = 0;
  68182. u.be.pC->cacheStatus = CACHE_STALE;
  68183. }
  68184. if( pOp->opcode==OP_Found ){
  68185. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  68186. }else{
  68187. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  68188. }
  68189. break;
  68190. }
  68191. /* Opcode: IsUnique P1 P2 P3 P4 *
  68192. **
  68193. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  68194. ** no data and where the key are records generated by OP_MakeRecord with
  68195. ** the list field being the integer ROWID of the entry that the index
  68196. ** entry refers to.
  68197. **
  68198. ** The P3 register contains an integer record number. Call this record
  68199. ** number R. Register P4 is the first in a set of N contiguous registers
  68200. ** that make up an unpacked index key that can be used with cursor P1.
  68201. ** The value of N can be inferred from the cursor. N includes the rowid
  68202. ** value appended to the end of the index record. This rowid value may
  68203. ** or may not be the same as R.
  68204. **
  68205. ** If any of the N registers beginning with register P4 contains a NULL
  68206. ** value, jump immediately to P2.
  68207. **
  68208. ** Otherwise, this instruction checks if cursor P1 contains an entry
  68209. ** where the first (N-1) fields match but the rowid value at the end
  68210. ** of the index entry is not R. If there is no such entry, control jumps
  68211. ** to instruction P2. Otherwise, the rowid of the conflicting index
  68212. ** entry is copied to register P3 and control falls through to the next
  68213. ** instruction.
  68214. **
  68215. ** See also: NotFound, NotExists, Found
  68216. */
  68217. case OP_IsUnique: { /* jump, in3 */
  68218. #if 0 /* local variables moved into u.bf */
  68219. u16 ii;
  68220. VdbeCursor *pCx;
  68221. BtCursor *pCrsr;
  68222. u16 nField;
  68223. Mem *aMx;
  68224. UnpackedRecord r; /* B-Tree index search key */
  68225. i64 R; /* Rowid stored in register P3 */
  68226. #endif /* local variables moved into u.bf */
  68227. pIn3 = &aMem[pOp->p3];
  68228. u.bf.aMx = &aMem[pOp->p4.i];
  68229. /* Assert that the values of parameters P1 and P4 are in range. */
  68230. assert( pOp->p4type==P4_INT32 );
  68231. assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) );
  68232. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68233. /* Find the index cursor. */
  68234. u.bf.pCx = p->apCsr[pOp->p1];
  68235. assert( u.bf.pCx->deferredMoveto==0 );
  68236. u.bf.pCx->seekResult = 0;
  68237. u.bf.pCx->cacheStatus = CACHE_STALE;
  68238. u.bf.pCrsr = u.bf.pCx->pCursor;
  68239. /* If any of the values are NULL, take the jump. */
  68240. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  68241. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  68242. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  68243. pc = pOp->p2 - 1;
  68244. u.bf.pCrsr = 0;
  68245. break;
  68246. }
  68247. }
  68248. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  68249. if( u.bf.pCrsr!=0 ){
  68250. /* Populate the index search key. */
  68251. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  68252. u.bf.r.nField = u.bf.nField + 1;
  68253. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  68254. u.bf.r.aMem = u.bf.aMx;
  68255. #ifdef SQLITE_DEBUG
  68256. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  68257. #endif
  68258. /* Extract the value of u.bf.R from register P3. */
  68259. sqlite3VdbeMemIntegerify(pIn3);
  68260. u.bf.R = pIn3->u.i;
  68261. /* Search the B-Tree index. If no conflicting record is found, jump
  68262. ** to P2. Otherwise, copy the rowid of the conflicting record to
  68263. ** register P3 and fall through to the next instruction. */
  68264. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  68265. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  68266. pc = pOp->p2 - 1;
  68267. }else{
  68268. pIn3->u.i = u.bf.r.rowid;
  68269. }
  68270. }
  68271. break;
  68272. }
  68273. /* Opcode: NotExists P1 P2 P3 * *
  68274. **
  68275. ** Use the content of register P3 as an integer key. If a record
  68276. ** with that key does not exist in table of P1, then jump to P2.
  68277. ** If the record does exist, then fall through. The cursor is left
  68278. ** pointing to the record if it exists.
  68279. **
  68280. ** The difference between this operation and NotFound is that this
  68281. ** operation assumes the key is an integer and that P1 is a table whereas
  68282. ** NotFound assumes key is a blob constructed from MakeRecord and
  68283. ** P1 is an index.
  68284. **
  68285. ** See also: Found, NotFound, IsUnique
  68286. */
  68287. case OP_NotExists: { /* jump, in3 */
  68288. #if 0 /* local variables moved into u.bg */
  68289. VdbeCursor *pC;
  68290. BtCursor *pCrsr;
  68291. int res;
  68292. u64 iKey;
  68293. #endif /* local variables moved into u.bg */
  68294. pIn3 = &aMem[pOp->p3];
  68295. assert( pIn3->flags & MEM_Int );
  68296. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68297. u.bg.pC = p->apCsr[pOp->p1];
  68298. assert( u.bg.pC!=0 );
  68299. assert( u.bg.pC->isTable );
  68300. assert( u.bg.pC->pseudoTableReg==0 );
  68301. u.bg.pCrsr = u.bg.pC->pCursor;
  68302. if( ALWAYS(u.bg.pCrsr!=0) ){
  68303. u.bg.res = 0;
  68304. u.bg.iKey = pIn3->u.i;
  68305. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  68306. u.bg.pC->lastRowid = pIn3->u.i;
  68307. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  68308. u.bg.pC->nullRow = 0;
  68309. u.bg.pC->cacheStatus = CACHE_STALE;
  68310. u.bg.pC->deferredMoveto = 0;
  68311. if( u.bg.res!=0 ){
  68312. pc = pOp->p2 - 1;
  68313. assert( u.bg.pC->rowidIsValid==0 );
  68314. }
  68315. u.bg.pC->seekResult = u.bg.res;
  68316. }else{
  68317. /* This happens when an attempt to open a read cursor on the
  68318. ** sqlite_master table returns SQLITE_EMPTY.
  68319. */
  68320. pc = pOp->p2 - 1;
  68321. assert( u.bg.pC->rowidIsValid==0 );
  68322. u.bg.pC->seekResult = 0;
  68323. }
  68324. break;
  68325. }
  68326. /* Opcode: Sequence P1 P2 * * *
  68327. **
  68328. ** Find the next available sequence number for cursor P1.
  68329. ** Write the sequence number into register P2.
  68330. ** The sequence number on the cursor is incremented after this
  68331. ** instruction.
  68332. */
  68333. case OP_Sequence: { /* out2-prerelease */
  68334. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68335. assert( p->apCsr[pOp->p1]!=0 );
  68336. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  68337. break;
  68338. }
  68339. /* Opcode: NewRowid P1 P2 P3 * *
  68340. **
  68341. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  68342. ** The record number is not previously used as a key in the database
  68343. ** table that cursor P1 points to. The new record number is written
  68344. ** written to register P2.
  68345. **
  68346. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  68347. ** the largest previously generated record number. No new record numbers are
  68348. ** allowed to be less than this value. When this value reaches its maximum,
  68349. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  68350. ** generated record number. This P3 mechanism is used to help implement the
  68351. ** AUTOINCREMENT feature.
  68352. */
  68353. case OP_NewRowid: { /* out2-prerelease */
  68354. #if 0 /* local variables moved into u.bh */
  68355. i64 v; /* The new rowid */
  68356. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  68357. int res; /* Result of an sqlite3BtreeLast() */
  68358. int cnt; /* Counter to limit the number of searches */
  68359. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  68360. VdbeFrame *pFrame; /* Root frame of VDBE */
  68361. #endif /* local variables moved into u.bh */
  68362. u.bh.v = 0;
  68363. u.bh.res = 0;
  68364. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68365. u.bh.pC = p->apCsr[pOp->p1];
  68366. assert( u.bh.pC!=0 );
  68367. if( NEVER(u.bh.pC->pCursor==0) ){
  68368. /* The zero initialization above is all that is needed */
  68369. }else{
  68370. /* The next rowid or record number (different terms for the same
  68371. ** thing) is obtained in a two-step algorithm.
  68372. **
  68373. ** First we attempt to find the largest existing rowid and add one
  68374. ** to that. But if the largest existing rowid is already the maximum
  68375. ** positive integer, we have to fall through to the second
  68376. ** probabilistic algorithm
  68377. **
  68378. ** The second algorithm is to select a rowid at random and see if
  68379. ** it already exists in the table. If it does not exist, we have
  68380. ** succeeded. If the random rowid does exist, we select a new one
  68381. ** and try again, up to 100 times.
  68382. */
  68383. assert( u.bh.pC->isTable );
  68384. #ifdef SQLITE_32BIT_ROWID
  68385. # define MAX_ROWID 0x7fffffff
  68386. #else
  68387. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  68388. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  68389. ** to provide the constant while making all compilers happy.
  68390. */
  68391. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  68392. #endif
  68393. if( !u.bh.pC->useRandomRowid ){
  68394. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  68395. if( u.bh.v==0 ){
  68396. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  68397. if( rc!=SQLITE_OK ){
  68398. goto abort_due_to_error;
  68399. }
  68400. if( u.bh.res ){
  68401. u.bh.v = 1; /* IMP: R-61914-48074 */
  68402. }else{
  68403. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  68404. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  68405. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  68406. if( u.bh.v>=MAX_ROWID ){
  68407. u.bh.pC->useRandomRowid = 1;
  68408. }else{
  68409. u.bh.v++; /* IMP: R-29538-34987 */
  68410. }
  68411. }
  68412. }
  68413. #ifndef SQLITE_OMIT_AUTOINCREMENT
  68414. if( pOp->p3 ){
  68415. /* Assert that P3 is a valid memory cell. */
  68416. assert( pOp->p3>0 );
  68417. if( p->pFrame ){
  68418. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  68419. /* Assert that P3 is a valid memory cell. */
  68420. assert( pOp->p3<=u.bh.pFrame->nMem );
  68421. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  68422. }else{
  68423. /* Assert that P3 is a valid memory cell. */
  68424. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68425. u.bh.pMem = &aMem[pOp->p3];
  68426. memAboutToChange(p, u.bh.pMem);
  68427. }
  68428. assert( memIsValid(u.bh.pMem) );
  68429. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  68430. sqlite3VdbeMemIntegerify(u.bh.pMem);
  68431. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  68432. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  68433. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  68434. goto abort_due_to_error;
  68435. }
  68436. if( u.bh.v<u.bh.pMem->u.i+1 ){
  68437. u.bh.v = u.bh.pMem->u.i + 1;
  68438. }
  68439. u.bh.pMem->u.i = u.bh.v;
  68440. }
  68441. #endif
  68442. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  68443. }
  68444. if( u.bh.pC->useRandomRowid ){
  68445. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  68446. ** largest possible integer (9223372036854775807) then the database
  68447. ** engine starts picking positive candidate ROWIDs at random until
  68448. ** it finds one that is not previously used. */
  68449. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  68450. ** an AUTOINCREMENT table. */
  68451. /* on the first attempt, simply do one more than previous */
  68452. u.bh.v = lastRowid;
  68453. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  68454. u.bh.v++; /* ensure non-zero */
  68455. u.bh.cnt = 0;
  68456. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  68457. 0, &u.bh.res))==SQLITE_OK)
  68458. && (u.bh.res==0)
  68459. && (++u.bh.cnt<100)){
  68460. /* collision - try another random rowid */
  68461. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  68462. if( u.bh.cnt<5 ){
  68463. /* try "small" random rowids for the initial attempts */
  68464. u.bh.v &= 0xffffff;
  68465. }else{
  68466. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  68467. }
  68468. u.bh.v++; /* ensure non-zero */
  68469. }
  68470. if( rc==SQLITE_OK && u.bh.res==0 ){
  68471. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  68472. goto abort_due_to_error;
  68473. }
  68474. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  68475. }
  68476. u.bh.pC->rowidIsValid = 0;
  68477. u.bh.pC->deferredMoveto = 0;
  68478. u.bh.pC->cacheStatus = CACHE_STALE;
  68479. }
  68480. pOut->u.i = u.bh.v;
  68481. break;
  68482. }
  68483. /* Opcode: Insert P1 P2 P3 P4 P5
  68484. **
  68485. ** Write an entry into the table of cursor P1. A new entry is
  68486. ** created if it doesn't already exist or the data for an existing
  68487. ** entry is overwritten. The data is the value MEM_Blob stored in register
  68488. ** number P2. The key is stored in register P3. The key must
  68489. ** be a MEM_Int.
  68490. **
  68491. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  68492. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  68493. ** then rowid is stored for subsequent return by the
  68494. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  68495. **
  68496. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  68497. ** the last seek operation (OP_NotExists) was a success, then this
  68498. ** operation will not attempt to find the appropriate row before doing
  68499. ** the insert but will instead overwrite the row that the cursor is
  68500. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  68501. ** has already positioned the cursor correctly. This is an optimization
  68502. ** that boosts performance by avoiding redundant seeks.
  68503. **
  68504. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  68505. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  68506. ** is part of an INSERT operation. The difference is only important to
  68507. ** the update hook.
  68508. **
  68509. ** Parameter P4 may point to a string containing the table-name, or
  68510. ** may be NULL. If it is not NULL, then the update-hook
  68511. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  68512. **
  68513. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  68514. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  68515. ** and register P2 becomes ephemeral. If the cursor is changed, the
  68516. ** value of register P2 will then change. Make sure this does not
  68517. ** cause any problems.)
  68518. **
  68519. ** This instruction only works on tables. The equivalent instruction
  68520. ** for indices is OP_IdxInsert.
  68521. */
  68522. /* Opcode: InsertInt P1 P2 P3 P4 P5
  68523. **
  68524. ** This works exactly like OP_Insert except that the key is the
  68525. ** integer value P3, not the value of the integer stored in register P3.
  68526. */
  68527. case OP_Insert:
  68528. case OP_InsertInt: {
  68529. #if 0 /* local variables moved into u.bi */
  68530. Mem *pData; /* MEM cell holding data for the record to be inserted */
  68531. Mem *pKey; /* MEM cell holding key for the record */
  68532. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  68533. VdbeCursor *pC; /* Cursor to table into which insert is written */
  68534. int nZero; /* Number of zero-bytes to append */
  68535. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  68536. const char *zDb; /* database name - used by the update hook */
  68537. const char *zTbl; /* Table name - used by the opdate hook */
  68538. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  68539. #endif /* local variables moved into u.bi */
  68540. u.bi.pData = &aMem[pOp->p2];
  68541. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68542. assert( memIsValid(u.bi.pData) );
  68543. u.bi.pC = p->apCsr[pOp->p1];
  68544. assert( u.bi.pC!=0 );
  68545. assert( u.bi.pC->pCursor!=0 );
  68546. assert( u.bi.pC->pseudoTableReg==0 );
  68547. assert( u.bi.pC->isTable );
  68548. REGISTER_TRACE(pOp->p2, u.bi.pData);
  68549. if( pOp->opcode==OP_Insert ){
  68550. u.bi.pKey = &aMem[pOp->p3];
  68551. assert( u.bi.pKey->flags & MEM_Int );
  68552. assert( memIsValid(u.bi.pKey) );
  68553. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  68554. u.bi.iKey = u.bi.pKey->u.i;
  68555. }else{
  68556. assert( pOp->opcode==OP_InsertInt );
  68557. u.bi.iKey = pOp->p3;
  68558. }
  68559. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  68560. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  68561. if( u.bi.pData->flags & MEM_Null ){
  68562. u.bi.pData->z = 0;
  68563. u.bi.pData->n = 0;
  68564. }else{
  68565. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  68566. }
  68567. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  68568. if( u.bi.pData->flags & MEM_Zero ){
  68569. u.bi.nZero = u.bi.pData->u.nZero;
  68570. }else{
  68571. u.bi.nZero = 0;
  68572. }
  68573. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  68574. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  68575. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  68576. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  68577. );
  68578. u.bi.pC->rowidIsValid = 0;
  68579. u.bi.pC->deferredMoveto = 0;
  68580. u.bi.pC->cacheStatus = CACHE_STALE;
  68581. /* Invoke the update-hook if required. */
  68582. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68583. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  68584. u.bi.zTbl = pOp->p4.z;
  68585. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  68586. assert( u.bi.pC->isTable );
  68587. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  68588. assert( u.bi.pC->iDb>=0 );
  68589. }
  68590. break;
  68591. }
  68592. /* Opcode: Delete P1 P2 * P4 *
  68593. **
  68594. ** Delete the record at which the P1 cursor is currently pointing.
  68595. **
  68596. ** The cursor will be left pointing at either the next or the previous
  68597. ** record in the table. If it is left pointing at the next record, then
  68598. ** the next Next instruction will be a no-op. Hence it is OK to delete
  68599. ** a record from within an Next loop.
  68600. **
  68601. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  68602. ** incremented (otherwise not).
  68603. **
  68604. ** P1 must not be pseudo-table. It has to be a real table with
  68605. ** multiple rows.
  68606. **
  68607. ** If P4 is not NULL, then it is the name of the table that P1 is
  68608. ** pointing to. The update hook will be invoked, if it exists.
  68609. ** If P4 is not NULL then the P1 cursor must have been positioned
  68610. ** using OP_NotFound prior to invoking this opcode.
  68611. */
  68612. case OP_Delete: {
  68613. #if 0 /* local variables moved into u.bj */
  68614. i64 iKey;
  68615. VdbeCursor *pC;
  68616. #endif /* local variables moved into u.bj */
  68617. u.bj.iKey = 0;
  68618. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68619. u.bj.pC = p->apCsr[pOp->p1];
  68620. assert( u.bj.pC!=0 );
  68621. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  68622. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  68623. ** row being deleted.
  68624. */
  68625. if( db->xUpdateCallback && pOp->p4.z ){
  68626. assert( u.bj.pC->isTable );
  68627. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  68628. u.bj.iKey = u.bj.pC->lastRowid;
  68629. }
  68630. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  68631. ** OP_Column on the same table without any intervening operations that
  68632. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  68633. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  68634. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  68635. ** to guard against future changes to the code generator.
  68636. **/
  68637. assert( u.bj.pC->deferredMoveto==0 );
  68638. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  68639. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  68640. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  68641. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  68642. u.bj.pC->cacheStatus = CACHE_STALE;
  68643. /* Invoke the update-hook if required. */
  68644. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68645. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  68646. const char *zTbl = pOp->p4.z;
  68647. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  68648. assert( u.bj.pC->iDb>=0 );
  68649. }
  68650. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  68651. break;
  68652. }
  68653. /* Opcode: ResetCount * * * * *
  68654. **
  68655. ** The value of the change counter is copied to the database handle
  68656. ** change counter (returned by subsequent calls to sqlite3_changes()).
  68657. ** Then the VMs internal change counter resets to 0.
  68658. ** This is used by trigger programs.
  68659. */
  68660. case OP_ResetCount: {
  68661. sqlite3VdbeSetChanges(db, p->nChange);
  68662. p->nChange = 0;
  68663. break;
  68664. }
  68665. /* Opcode: SorterCompare P1 P2 P3
  68666. **
  68667. ** P1 is a sorter cursor. This instruction compares the record blob in
  68668. ** register P3 with the entry that the sorter cursor currently points to.
  68669. ** If, excluding the rowid fields at the end, the two records are a match,
  68670. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  68671. */
  68672. case OP_SorterCompare: {
  68673. #if 0 /* local variables moved into u.bk */
  68674. VdbeCursor *pC;
  68675. int res;
  68676. #endif /* local variables moved into u.bk */
  68677. u.bk.pC = p->apCsr[pOp->p1];
  68678. assert( isSorter(u.bk.pC) );
  68679. pIn3 = &aMem[pOp->p3];
  68680. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  68681. if( u.bk.res ){
  68682. pc = pOp->p2-1;
  68683. }
  68684. break;
  68685. };
  68686. /* Opcode: SorterData P1 P2 * * *
  68687. **
  68688. ** Write into register P2 the current sorter data for sorter cursor P1.
  68689. */
  68690. case OP_SorterData: {
  68691. #if 0 /* local variables moved into u.bl */
  68692. VdbeCursor *pC;
  68693. #endif /* local variables moved into u.bl */
  68694. pOut = &aMem[pOp->p2];
  68695. u.bl.pC = p->apCsr[pOp->p1];
  68696. assert( u.bl.pC->isSorter );
  68697. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  68698. break;
  68699. }
  68700. /* Opcode: RowData P1 P2 * * *
  68701. **
  68702. ** Write into register P2 the complete row data for cursor P1.
  68703. ** There is no interpretation of the data.
  68704. ** It is just copied onto the P2 register exactly as
  68705. ** it is found in the database file.
  68706. **
  68707. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68708. ** of a real table, not a pseudo-table.
  68709. */
  68710. /* Opcode: RowKey P1 P2 * * *
  68711. **
  68712. ** Write into register P2 the complete row key for cursor P1.
  68713. ** There is no interpretation of the data.
  68714. ** The key is copied onto the P3 register exactly as
  68715. ** it is found in the database file.
  68716. **
  68717. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68718. ** of a real table, not a pseudo-table.
  68719. */
  68720. case OP_RowKey:
  68721. case OP_RowData: {
  68722. #if 0 /* local variables moved into u.bm */
  68723. VdbeCursor *pC;
  68724. BtCursor *pCrsr;
  68725. u32 n;
  68726. i64 n64;
  68727. #endif /* local variables moved into u.bm */
  68728. pOut = &aMem[pOp->p2];
  68729. memAboutToChange(p, pOut);
  68730. /* Note that RowKey and RowData are really exactly the same instruction */
  68731. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68732. u.bm.pC = p->apCsr[pOp->p1];
  68733. assert( u.bm.pC->isSorter==0 );
  68734. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  68735. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  68736. assert( u.bm.pC!=0 );
  68737. assert( u.bm.pC->nullRow==0 );
  68738. assert( u.bm.pC->pseudoTableReg==0 );
  68739. assert( u.bm.pC->pCursor!=0 );
  68740. u.bm.pCrsr = u.bm.pC->pCursor;
  68741. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  68742. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  68743. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  68744. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  68745. ** a no-op and can never fail. But we leave it in place as a safety.
  68746. */
  68747. assert( u.bm.pC->deferredMoveto==0 );
  68748. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  68749. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  68750. if( u.bm.pC->isIndex ){
  68751. assert( !u.bm.pC->isTable );
  68752. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  68753. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  68754. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68755. goto too_big;
  68756. }
  68757. u.bm.n = (u32)u.bm.n64;
  68758. }else{
  68759. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  68760. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  68761. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68762. goto too_big;
  68763. }
  68764. }
  68765. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  68766. goto no_mem;
  68767. }
  68768. pOut->n = u.bm.n;
  68769. MemSetTypeFlag(pOut, MEM_Blob);
  68770. if( u.bm.pC->isIndex ){
  68771. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  68772. }else{
  68773. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  68774. }
  68775. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  68776. UPDATE_MAX_BLOBSIZE(pOut);
  68777. break;
  68778. }
  68779. /* Opcode: Rowid P1 P2 * * *
  68780. **
  68781. ** Store in register P2 an integer which is the key of the table entry that
  68782. ** P1 is currently point to.
  68783. **
  68784. ** P1 can be either an ordinary table or a virtual table. There used to
  68785. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  68786. ** one opcode now works for both table types.
  68787. */
  68788. case OP_Rowid: { /* out2-prerelease */
  68789. #if 0 /* local variables moved into u.bn */
  68790. VdbeCursor *pC;
  68791. i64 v;
  68792. sqlite3_vtab *pVtab;
  68793. const sqlite3_module *pModule;
  68794. #endif /* local variables moved into u.bn */
  68795. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68796. u.bn.pC = p->apCsr[pOp->p1];
  68797. assert( u.bn.pC!=0 );
  68798. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  68799. if( u.bn.pC->nullRow ){
  68800. pOut->flags = MEM_Null;
  68801. break;
  68802. }else if( u.bn.pC->deferredMoveto ){
  68803. u.bn.v = u.bn.pC->movetoTarget;
  68804. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68805. }else if( u.bn.pC->pVtabCursor ){
  68806. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  68807. u.bn.pModule = u.bn.pVtab->pModule;
  68808. assert( u.bn.pModule->xRowid );
  68809. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  68810. sqlite3VtabImportErrmsg(p, u.bn.pVtab);
  68811. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  68812. }else{
  68813. assert( u.bn.pC->pCursor!=0 );
  68814. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  68815. if( rc ) goto abort_due_to_error;
  68816. if( u.bn.pC->rowidIsValid ){
  68817. u.bn.v = u.bn.pC->lastRowid;
  68818. }else{
  68819. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  68820. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  68821. }
  68822. }
  68823. pOut->u.i = u.bn.v;
  68824. break;
  68825. }
  68826. /* Opcode: NullRow P1 * * * *
  68827. **
  68828. ** Move the cursor P1 to a null row. Any OP_Column operations
  68829. ** that occur while the cursor is on the null row will always
  68830. ** write a NULL.
  68831. */
  68832. case OP_NullRow: {
  68833. #if 0 /* local variables moved into u.bo */
  68834. VdbeCursor *pC;
  68835. #endif /* local variables moved into u.bo */
  68836. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68837. u.bo.pC = p->apCsr[pOp->p1];
  68838. assert( u.bo.pC!=0 );
  68839. u.bo.pC->nullRow = 1;
  68840. u.bo.pC->rowidIsValid = 0;
  68841. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  68842. if( u.bo.pC->pCursor ){
  68843. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  68844. }
  68845. break;
  68846. }
  68847. /* Opcode: Last P1 P2 * * *
  68848. **
  68849. ** The next use of the Rowid or Column or Next instruction for P1
  68850. ** will refer to the last entry in the database table or index.
  68851. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68852. ** If P2 is 0 or if the table or index is not empty, fall through
  68853. ** to the following instruction.
  68854. */
  68855. case OP_Last: { /* jump */
  68856. #if 0 /* local variables moved into u.bp */
  68857. VdbeCursor *pC;
  68858. BtCursor *pCrsr;
  68859. int res;
  68860. #endif /* local variables moved into u.bp */
  68861. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68862. u.bp.pC = p->apCsr[pOp->p1];
  68863. assert( u.bp.pC!=0 );
  68864. u.bp.pCrsr = u.bp.pC->pCursor;
  68865. u.bp.res = 0;
  68866. if( ALWAYS(u.bp.pCrsr!=0) ){
  68867. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  68868. }
  68869. u.bp.pC->nullRow = (u8)u.bp.res;
  68870. u.bp.pC->deferredMoveto = 0;
  68871. u.bp.pC->rowidIsValid = 0;
  68872. u.bp.pC->cacheStatus = CACHE_STALE;
  68873. if( pOp->p2>0 && u.bp.res ){
  68874. pc = pOp->p2 - 1;
  68875. }
  68876. break;
  68877. }
  68878. /* Opcode: Sort P1 P2 * * *
  68879. **
  68880. ** This opcode does exactly the same thing as OP_Rewind except that
  68881. ** it increments an undocumented global variable used for testing.
  68882. **
  68883. ** Sorting is accomplished by writing records into a sorting index,
  68884. ** then rewinding that index and playing it back from beginning to
  68885. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  68886. ** rewinding so that the global variable will be incremented and
  68887. ** regression tests can determine whether or not the optimizer is
  68888. ** correctly optimizing out sorts.
  68889. */
  68890. case OP_SorterSort: /* jump */
  68891. case OP_Sort: { /* jump */
  68892. #ifdef SQLITE_TEST
  68893. sqlite3_sort_count++;
  68894. sqlite3_search_count--;
  68895. #endif
  68896. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  68897. /* Fall through into OP_Rewind */
  68898. }
  68899. /* Opcode: Rewind P1 P2 * * *
  68900. **
  68901. ** The next use of the Rowid or Column or Next instruction for P1
  68902. ** will refer to the first entry in the database table or index.
  68903. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68904. ** If P2 is 0 or if the table or index is not empty, fall through
  68905. ** to the following instruction.
  68906. */
  68907. case OP_Rewind: { /* jump */
  68908. #if 0 /* local variables moved into u.bq */
  68909. VdbeCursor *pC;
  68910. BtCursor *pCrsr;
  68911. int res;
  68912. #endif /* local variables moved into u.bq */
  68913. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68914. u.bq.pC = p->apCsr[pOp->p1];
  68915. assert( u.bq.pC!=0 );
  68916. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  68917. u.bq.res = 1;
  68918. if( isSorter(u.bq.pC) ){
  68919. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  68920. }else{
  68921. u.bq.pCrsr = u.bq.pC->pCursor;
  68922. assert( u.bq.pCrsr );
  68923. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  68924. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  68925. u.bq.pC->deferredMoveto = 0;
  68926. u.bq.pC->cacheStatus = CACHE_STALE;
  68927. u.bq.pC->rowidIsValid = 0;
  68928. }
  68929. u.bq.pC->nullRow = (u8)u.bq.res;
  68930. assert( pOp->p2>0 && pOp->p2<p->nOp );
  68931. if( u.bq.res ){
  68932. pc = pOp->p2 - 1;
  68933. }
  68934. break;
  68935. }
  68936. /* Opcode: Next P1 P2 * P4 P5
  68937. **
  68938. ** Advance cursor P1 so that it points to the next key/data pair in its
  68939. ** table or index. If there are no more key/value pairs then fall through
  68940. ** to the following instruction. But if the cursor advance was successful,
  68941. ** jump immediately to P2.
  68942. **
  68943. ** The P1 cursor must be for a real table, not a pseudo-table.
  68944. **
  68945. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68946. ** sqlite3BtreeNext().
  68947. **
  68948. ** If P5 is positive and the jump is taken, then event counter
  68949. ** number P5-1 in the prepared statement is incremented.
  68950. **
  68951. ** See also: Prev
  68952. */
  68953. /* Opcode: Prev P1 P2 * * P5
  68954. **
  68955. ** Back up cursor P1 so that it points to the previous key/data pair in its
  68956. ** table or index. If there is no previous key/value pairs then fall through
  68957. ** to the following instruction. But if the cursor backup was successful,
  68958. ** jump immediately to P2.
  68959. **
  68960. ** The P1 cursor must be for a real table, not a pseudo-table.
  68961. **
  68962. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68963. ** sqlite3BtreePrevious().
  68964. **
  68965. ** If P5 is positive and the jump is taken, then event counter
  68966. ** number P5-1 in the prepared statement is incremented.
  68967. */
  68968. case OP_SorterNext: /* jump */
  68969. case OP_Prev: /* jump */
  68970. case OP_Next: { /* jump */
  68971. #if 0 /* local variables moved into u.br */
  68972. VdbeCursor *pC;
  68973. int res;
  68974. #endif /* local variables moved into u.br */
  68975. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68976. assert( pOp->p5<ArraySize(p->aCounter) );
  68977. u.br.pC = p->apCsr[pOp->p1];
  68978. if( u.br.pC==0 ){
  68979. break; /* See ticket #2273 */
  68980. }
  68981. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  68982. if( isSorter(u.br.pC) ){
  68983. assert( pOp->opcode==OP_SorterNext );
  68984. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  68985. }else{
  68986. /* u.br.res = 1; // Always initialized by the xAdvance() call */
  68987. assert( u.br.pC->deferredMoveto==0 );
  68988. assert( u.br.pC->pCursor );
  68989. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  68990. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  68991. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  68992. }
  68993. u.br.pC->nullRow = (u8)u.br.res;
  68994. u.br.pC->cacheStatus = CACHE_STALE;
  68995. if( u.br.res==0 ){
  68996. pc = pOp->p2 - 1;
  68997. p->aCounter[pOp->p5]++;
  68998. #ifdef SQLITE_TEST
  68999. sqlite3_search_count++;
  69000. #endif
  69001. }
  69002. u.br.pC->rowidIsValid = 0;
  69003. goto check_for_interrupt;
  69004. }
  69005. /* Opcode: IdxInsert P1 P2 P3 * P5
  69006. **
  69007. ** Register P2 holds an SQL index key made using the
  69008. ** MakeRecord instructions. This opcode writes that key
  69009. ** into the index P1. Data for the entry is nil.
  69010. **
  69011. ** P3 is a flag that provides a hint to the b-tree layer that this
  69012. ** insert is likely to be an append.
  69013. **
  69014. ** This instruction only works for indices. The equivalent instruction
  69015. ** for tables is OP_Insert.
  69016. */
  69017. case OP_SorterInsert: /* in2 */
  69018. case OP_IdxInsert: { /* in2 */
  69019. #if 0 /* local variables moved into u.bs */
  69020. VdbeCursor *pC;
  69021. BtCursor *pCrsr;
  69022. int nKey;
  69023. const char *zKey;
  69024. #endif /* local variables moved into u.bs */
  69025. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69026. u.bs.pC = p->apCsr[pOp->p1];
  69027. assert( u.bs.pC!=0 );
  69028. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  69029. pIn2 = &aMem[pOp->p2];
  69030. assert( pIn2->flags & MEM_Blob );
  69031. u.bs.pCrsr = u.bs.pC->pCursor;
  69032. if( ALWAYS(u.bs.pCrsr!=0) ){
  69033. assert( u.bs.pC->isTable==0 );
  69034. rc = ExpandBlob(pIn2);
  69035. if( rc==SQLITE_OK ){
  69036. if( isSorter(u.bs.pC) ){
  69037. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  69038. }else{
  69039. u.bs.nKey = pIn2->n;
  69040. u.bs.zKey = pIn2->z;
  69041. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  69042. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  69043. );
  69044. assert( u.bs.pC->deferredMoveto==0 );
  69045. u.bs.pC->cacheStatus = CACHE_STALE;
  69046. }
  69047. }
  69048. }
  69049. break;
  69050. }
  69051. /* Opcode: IdxDelete P1 P2 P3 * *
  69052. **
  69053. ** The content of P3 registers starting at register P2 form
  69054. ** an unpacked index key. This opcode removes that entry from the
  69055. ** index opened by cursor P1.
  69056. */
  69057. case OP_IdxDelete: {
  69058. #if 0 /* local variables moved into u.bt */
  69059. VdbeCursor *pC;
  69060. BtCursor *pCrsr;
  69061. int res;
  69062. UnpackedRecord r;
  69063. #endif /* local variables moved into u.bt */
  69064. assert( pOp->p3>0 );
  69065. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  69066. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69067. u.bt.pC = p->apCsr[pOp->p1];
  69068. assert( u.bt.pC!=0 );
  69069. u.bt.pCrsr = u.bt.pC->pCursor;
  69070. if( ALWAYS(u.bt.pCrsr!=0) ){
  69071. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  69072. u.bt.r.nField = (u16)pOp->p3;
  69073. u.bt.r.flags = 0;
  69074. u.bt.r.aMem = &aMem[pOp->p2];
  69075. #ifdef SQLITE_DEBUG
  69076. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  69077. #endif
  69078. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  69079. if( rc==SQLITE_OK && u.bt.res==0 ){
  69080. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  69081. }
  69082. assert( u.bt.pC->deferredMoveto==0 );
  69083. u.bt.pC->cacheStatus = CACHE_STALE;
  69084. }
  69085. break;
  69086. }
  69087. /* Opcode: IdxRowid P1 P2 * * *
  69088. **
  69089. ** Write into register P2 an integer which is the last entry in the record at
  69090. ** the end of the index key pointed to by cursor P1. This integer should be
  69091. ** the rowid of the table entry to which this index entry points.
  69092. **
  69093. ** See also: Rowid, MakeRecord.
  69094. */
  69095. case OP_IdxRowid: { /* out2-prerelease */
  69096. #if 0 /* local variables moved into u.bu */
  69097. BtCursor *pCrsr;
  69098. VdbeCursor *pC;
  69099. i64 rowid;
  69100. #endif /* local variables moved into u.bu */
  69101. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69102. u.bu.pC = p->apCsr[pOp->p1];
  69103. assert( u.bu.pC!=0 );
  69104. u.bu.pCrsr = u.bu.pC->pCursor;
  69105. pOut->flags = MEM_Null;
  69106. if( ALWAYS(u.bu.pCrsr!=0) ){
  69107. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  69108. if( NEVER(rc) ) goto abort_due_to_error;
  69109. assert( u.bu.pC->deferredMoveto==0 );
  69110. assert( u.bu.pC->isTable==0 );
  69111. if( !u.bu.pC->nullRow ){
  69112. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  69113. if( rc!=SQLITE_OK ){
  69114. goto abort_due_to_error;
  69115. }
  69116. pOut->u.i = u.bu.rowid;
  69117. pOut->flags = MEM_Int;
  69118. }
  69119. }
  69120. break;
  69121. }
  69122. /* Opcode: IdxGE P1 P2 P3 P4 P5
  69123. **
  69124. ** The P4 register values beginning with P3 form an unpacked index
  69125. ** key that omits the ROWID. Compare this key value against the index
  69126. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  69127. **
  69128. ** If the P1 index entry is greater than or equal to the key value
  69129. ** then jump to P2. Otherwise fall through to the next instruction.
  69130. **
  69131. ** If P5 is non-zero then the key value is increased by an epsilon
  69132. ** prior to the comparison. This make the opcode work like IdxGT except
  69133. ** that if the key from register P3 is a prefix of the key in the cursor,
  69134. ** the result is false whereas it would be true with IdxGT.
  69135. */
  69136. /* Opcode: IdxLT P1 P2 P3 P4 P5
  69137. **
  69138. ** The P4 register values beginning with P3 form an unpacked index
  69139. ** key that omits the ROWID. Compare this key value against the index
  69140. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  69141. **
  69142. ** If the P1 index entry is less than the key value then jump to P2.
  69143. ** Otherwise fall through to the next instruction.
  69144. **
  69145. ** If P5 is non-zero then the key value is increased by an epsilon prior
  69146. ** to the comparison. This makes the opcode work like IdxLE.
  69147. */
  69148. case OP_IdxLT: /* jump */
  69149. case OP_IdxGE: { /* jump */
  69150. #if 0 /* local variables moved into u.bv */
  69151. VdbeCursor *pC;
  69152. int res;
  69153. UnpackedRecord r;
  69154. #endif /* local variables moved into u.bv */
  69155. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69156. u.bv.pC = p->apCsr[pOp->p1];
  69157. assert( u.bv.pC!=0 );
  69158. assert( u.bv.pC->isOrdered );
  69159. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  69160. assert( u.bv.pC->deferredMoveto==0 );
  69161. assert( pOp->p5==0 || pOp->p5==1 );
  69162. assert( pOp->p4type==P4_INT32 );
  69163. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  69164. u.bv.r.nField = (u16)pOp->p4.i;
  69165. if( pOp->p5 ){
  69166. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  69167. }else{
  69168. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  69169. }
  69170. u.bv.r.aMem = &aMem[pOp->p3];
  69171. #ifdef SQLITE_DEBUG
  69172. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  69173. #endif
  69174. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  69175. if( pOp->opcode==OP_IdxLT ){
  69176. u.bv.res = -u.bv.res;
  69177. }else{
  69178. assert( pOp->opcode==OP_IdxGE );
  69179. u.bv.res++;
  69180. }
  69181. if( u.bv.res>0 ){
  69182. pc = pOp->p2 - 1 ;
  69183. }
  69184. }
  69185. break;
  69186. }
  69187. /* Opcode: Destroy P1 P2 P3 * *
  69188. **
  69189. ** Delete an entire database table or index whose root page in the database
  69190. ** file is given by P1.
  69191. **
  69192. ** The table being destroyed is in the main database file if P3==0. If
  69193. ** P3==1 then the table to be clear is in the auxiliary database file
  69194. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69195. **
  69196. ** If AUTOVACUUM is enabled then it is possible that another root page
  69197. ** might be moved into the newly deleted root page in order to keep all
  69198. ** root pages contiguous at the beginning of the database. The former
  69199. ** value of the root page that moved - its value before the move occurred -
  69200. ** is stored in register P2. If no page
  69201. ** movement was required (because the table being dropped was already
  69202. ** the last one in the database) then a zero is stored in register P2.
  69203. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  69204. **
  69205. ** See also: Clear
  69206. */
  69207. case OP_Destroy: { /* out2-prerelease */
  69208. #if 0 /* local variables moved into u.bw */
  69209. int iMoved;
  69210. int iCnt;
  69211. Vdbe *pVdbe;
  69212. int iDb;
  69213. #endif /* local variables moved into u.bw */
  69214. assert( p->readOnly==0 );
  69215. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69216. u.bw.iCnt = 0;
  69217. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  69218. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
  69219. && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
  69220. ){
  69221. u.bw.iCnt++;
  69222. }
  69223. }
  69224. #else
  69225. u.bw.iCnt = db->nVdbeRead;
  69226. #endif
  69227. pOut->flags = MEM_Null;
  69228. if( u.bw.iCnt>1 ){
  69229. rc = SQLITE_LOCKED;
  69230. p->errorAction = OE_Abort;
  69231. }else{
  69232. u.bw.iDb = pOp->p3;
  69233. assert( u.bw.iCnt==1 );
  69234. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  69235. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  69236. pOut->flags = MEM_Int;
  69237. pOut->u.i = u.bw.iMoved;
  69238. #ifndef SQLITE_OMIT_AUTOVACUUM
  69239. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  69240. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  69241. /* All OP_Destroy operations occur on the same btree */
  69242. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  69243. resetSchemaOnFault = u.bw.iDb+1;
  69244. }
  69245. #endif
  69246. }
  69247. break;
  69248. }
  69249. /* Opcode: Clear P1 P2 P3
  69250. **
  69251. ** Delete all contents of the database table or index whose root page
  69252. ** in the database file is given by P1. But, unlike Destroy, do not
  69253. ** remove the table or index from the database file.
  69254. **
  69255. ** The table being clear is in the main database file if P2==0. If
  69256. ** P2==1 then the table to be clear is in the auxiliary database file
  69257. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69258. **
  69259. ** If the P3 value is non-zero, then the table referred to must be an
  69260. ** intkey table (an SQL table, not an index). In this case the row change
  69261. ** count is incremented by the number of rows in the table being cleared.
  69262. ** If P3 is greater than zero, then the value stored in register P3 is
  69263. ** also incremented by the number of rows in the table being cleared.
  69264. **
  69265. ** See also: Destroy
  69266. */
  69267. case OP_Clear: {
  69268. #if 0 /* local variables moved into u.bx */
  69269. int nChange;
  69270. #endif /* local variables moved into u.bx */
  69271. u.bx.nChange = 0;
  69272. assert( p->readOnly==0 );
  69273. assert( pOp->p1!=1 );
  69274. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  69275. rc = sqlite3BtreeClearTable(
  69276. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  69277. );
  69278. if( pOp->p3 ){
  69279. p->nChange += u.bx.nChange;
  69280. if( pOp->p3>0 ){
  69281. assert( memIsValid(&aMem[pOp->p3]) );
  69282. memAboutToChange(p, &aMem[pOp->p3]);
  69283. aMem[pOp->p3].u.i += u.bx.nChange;
  69284. }
  69285. }
  69286. break;
  69287. }
  69288. /* Opcode: CreateTable P1 P2 * * *
  69289. **
  69290. ** Allocate a new table in the main database file if P1==0 or in the
  69291. ** auxiliary database file if P1==1 or in an attached database if
  69292. ** P1>1. Write the root page number of the new table into
  69293. ** register P2
  69294. **
  69295. ** The difference between a table and an index is this: A table must
  69296. ** have a 4-byte integer key and can have arbitrary data. An index
  69297. ** has an arbitrary key but no data.
  69298. **
  69299. ** See also: CreateIndex
  69300. */
  69301. /* Opcode: CreateIndex P1 P2 * * *
  69302. **
  69303. ** Allocate a new index in the main database file if P1==0 or in the
  69304. ** auxiliary database file if P1==1 or in an attached database if
  69305. ** P1>1. Write the root page number of the new table into
  69306. ** register P2.
  69307. **
  69308. ** See documentation on OP_CreateTable for additional information.
  69309. */
  69310. case OP_CreateIndex: /* out2-prerelease */
  69311. case OP_CreateTable: { /* out2-prerelease */
  69312. #if 0 /* local variables moved into u.by */
  69313. int pgno;
  69314. int flags;
  69315. Db *pDb;
  69316. #endif /* local variables moved into u.by */
  69317. u.by.pgno = 0;
  69318. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69319. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  69320. assert( p->readOnly==0 );
  69321. u.by.pDb = &db->aDb[pOp->p1];
  69322. assert( u.by.pDb->pBt!=0 );
  69323. if( pOp->opcode==OP_CreateTable ){
  69324. /* u.by.flags = BTREE_INTKEY; */
  69325. u.by.flags = BTREE_INTKEY;
  69326. }else{
  69327. u.by.flags = BTREE_BLOBKEY;
  69328. }
  69329. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  69330. pOut->u.i = u.by.pgno;
  69331. break;
  69332. }
  69333. /* Opcode: ParseSchema P1 * * P4 *
  69334. **
  69335. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  69336. ** that match the WHERE clause P4.
  69337. **
  69338. ** This opcode invokes the parser to create a new virtual machine,
  69339. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  69340. */
  69341. case OP_ParseSchema: {
  69342. #if 0 /* local variables moved into u.bz */
  69343. int iDb;
  69344. const char *zMaster;
  69345. char *zSql;
  69346. InitData initData;
  69347. #endif /* local variables moved into u.bz */
  69348. /* Any prepared statement that invokes this opcode will hold mutexes
  69349. ** on every btree. This is a prerequisite for invoking
  69350. ** sqlite3InitCallback().
  69351. */
  69352. #ifdef SQLITE_DEBUG
  69353. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  69354. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  69355. }
  69356. #endif
  69357. u.bz.iDb = pOp->p1;
  69358. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  69359. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  69360. /* Used to be a conditional */ {
  69361. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  69362. u.bz.initData.db = db;
  69363. u.bz.initData.iDb = pOp->p1;
  69364. u.bz.initData.pzErrMsg = &p->zErrMsg;
  69365. u.bz.zSql = sqlite3MPrintf(db,
  69366. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  69367. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  69368. if( u.bz.zSql==0 ){
  69369. rc = SQLITE_NOMEM;
  69370. }else{
  69371. assert( db->init.busy==0 );
  69372. db->init.busy = 1;
  69373. u.bz.initData.rc = SQLITE_OK;
  69374. assert( !db->mallocFailed );
  69375. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  69376. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  69377. sqlite3DbFree(db, u.bz.zSql);
  69378. db->init.busy = 0;
  69379. }
  69380. }
  69381. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  69382. if( rc==SQLITE_NOMEM ){
  69383. goto no_mem;
  69384. }
  69385. break;
  69386. }
  69387. #if !defined(SQLITE_OMIT_ANALYZE)
  69388. /* Opcode: LoadAnalysis P1 * * * *
  69389. **
  69390. ** Read the sqlite_stat1 table for database P1 and load the content
  69391. ** of that table into the internal index hash table. This will cause
  69392. ** the analysis to be used when preparing all subsequent queries.
  69393. */
  69394. case OP_LoadAnalysis: {
  69395. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69396. rc = sqlite3AnalysisLoad(db, pOp->p1);
  69397. break;
  69398. }
  69399. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  69400. /* Opcode: DropTable P1 * * P4 *
  69401. **
  69402. ** Remove the internal (in-memory) data structures that describe
  69403. ** the table named P4 in database P1. This is called after a table
  69404. ** is dropped in order to keep the internal representation of the
  69405. ** schema consistent with what is on disk.
  69406. */
  69407. case OP_DropTable: {
  69408. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  69409. break;
  69410. }
  69411. /* Opcode: DropIndex P1 * * P4 *
  69412. **
  69413. ** Remove the internal (in-memory) data structures that describe
  69414. ** the index named P4 in database P1. This is called after an index
  69415. ** is dropped in order to keep the internal representation of the
  69416. ** schema consistent with what is on disk.
  69417. */
  69418. case OP_DropIndex: {
  69419. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  69420. break;
  69421. }
  69422. /* Opcode: DropTrigger P1 * * P4 *
  69423. **
  69424. ** Remove the internal (in-memory) data structures that describe
  69425. ** the trigger named P4 in database P1. This is called after a trigger
  69426. ** is dropped in order to keep the internal representation of the
  69427. ** schema consistent with what is on disk.
  69428. */
  69429. case OP_DropTrigger: {
  69430. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  69431. break;
  69432. }
  69433. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69434. /* Opcode: IntegrityCk P1 P2 P3 * P5
  69435. **
  69436. ** Do an analysis of the currently open database. Store in
  69437. ** register P1 the text of an error message describing any problems.
  69438. ** If no problems are found, store a NULL in register P1.
  69439. **
  69440. ** The register P3 contains the maximum number of allowed errors.
  69441. ** At most reg(P3) errors will be reported.
  69442. ** In other words, the analysis stops as soon as reg(P1) errors are
  69443. ** seen. Reg(P1) is updated with the number of errors remaining.
  69444. **
  69445. ** The root page numbers of all tables in the database are integer
  69446. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  69447. ** total.
  69448. **
  69449. ** If P5 is not zero, the check is done on the auxiliary database
  69450. ** file, not the main database file.
  69451. **
  69452. ** This opcode is used to implement the integrity_check pragma.
  69453. */
  69454. case OP_IntegrityCk: {
  69455. #if 0 /* local variables moved into u.ca */
  69456. int nRoot; /* Number of tables to check. (Number of root pages.) */
  69457. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  69458. int j; /* Loop counter */
  69459. int nErr; /* Number of errors reported */
  69460. char *z; /* Text of the error report */
  69461. Mem *pnErr; /* Register keeping track of errors remaining */
  69462. #endif /* local variables moved into u.ca */
  69463. assert( p->bIsReader );
  69464. u.ca.nRoot = pOp->p2;
  69465. assert( u.ca.nRoot>0 );
  69466. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  69467. if( u.ca.aRoot==0 ) goto no_mem;
  69468. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69469. u.ca.pnErr = &aMem[pOp->p3];
  69470. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  69471. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  69472. pIn1 = &aMem[pOp->p1];
  69473. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  69474. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  69475. }
  69476. u.ca.aRoot[u.ca.j] = 0;
  69477. assert( pOp->p5<db->nDb );
  69478. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  69479. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  69480. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  69481. sqlite3DbFree(db, u.ca.aRoot);
  69482. u.ca.pnErr->u.i -= u.ca.nErr;
  69483. sqlite3VdbeMemSetNull(pIn1);
  69484. if( u.ca.nErr==0 ){
  69485. assert( u.ca.z==0 );
  69486. }else if( u.ca.z==0 ){
  69487. goto no_mem;
  69488. }else{
  69489. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  69490. }
  69491. UPDATE_MAX_BLOBSIZE(pIn1);
  69492. sqlite3VdbeChangeEncoding(pIn1, encoding);
  69493. break;
  69494. }
  69495. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69496. /* Opcode: RowSetAdd P1 P2 * * *
  69497. **
  69498. ** Insert the integer value held by register P2 into a boolean index
  69499. ** held in register P1.
  69500. **
  69501. ** An assertion fails if P2 is not an integer.
  69502. */
  69503. case OP_RowSetAdd: { /* in1, in2 */
  69504. pIn1 = &aMem[pOp->p1];
  69505. pIn2 = &aMem[pOp->p2];
  69506. assert( (pIn2->flags & MEM_Int)!=0 );
  69507. if( (pIn1->flags & MEM_RowSet)==0 ){
  69508. sqlite3VdbeMemSetRowSet(pIn1);
  69509. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69510. }
  69511. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  69512. break;
  69513. }
  69514. /* Opcode: RowSetRead P1 P2 P3 * *
  69515. **
  69516. ** Extract the smallest value from boolean index P1 and put that value into
  69517. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  69518. ** unchanged and jump to instruction P2.
  69519. */
  69520. case OP_RowSetRead: { /* jump, in1, out3 */
  69521. #if 0 /* local variables moved into u.cb */
  69522. i64 val;
  69523. #endif /* local variables moved into u.cb */
  69524. pIn1 = &aMem[pOp->p1];
  69525. if( (pIn1->flags & MEM_RowSet)==0
  69526. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  69527. ){
  69528. /* The boolean index is empty */
  69529. sqlite3VdbeMemSetNull(pIn1);
  69530. pc = pOp->p2 - 1;
  69531. }else{
  69532. /* A value was pulled from the index */
  69533. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  69534. }
  69535. goto check_for_interrupt;
  69536. }
  69537. /* Opcode: RowSetTest P1 P2 P3 P4
  69538. **
  69539. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  69540. ** contains a RowSet object and that RowSet object contains
  69541. ** the value held in P3, jump to register P2. Otherwise, insert the
  69542. ** integer in P3 into the RowSet and continue on to the
  69543. ** next opcode.
  69544. **
  69545. ** The RowSet object is optimized for the case where successive sets
  69546. ** of integers, where each set contains no duplicates. Each set
  69547. ** of values is identified by a unique P4 value. The first set
  69548. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  69549. ** non-negative. For non-negative values of P4 only the lower 4
  69550. ** bits are significant.
  69551. **
  69552. ** This allows optimizations: (a) when P4==0 there is no need to test
  69553. ** the rowset object for P3, as it is guaranteed not to contain it,
  69554. ** (b) when P4==-1 there is no need to insert the value, as it will
  69555. ** never be tested for, and (c) when a value that is part of set X is
  69556. ** inserted, there is no need to search to see if the same value was
  69557. ** previously inserted as part of set X (only if it was previously
  69558. ** inserted as part of some other set).
  69559. */
  69560. case OP_RowSetTest: { /* jump, in1, in3 */
  69561. #if 0 /* local variables moved into u.cc */
  69562. int iSet;
  69563. int exists;
  69564. #endif /* local variables moved into u.cc */
  69565. pIn1 = &aMem[pOp->p1];
  69566. pIn3 = &aMem[pOp->p3];
  69567. u.cc.iSet = pOp->p4.i;
  69568. assert( pIn3->flags&MEM_Int );
  69569. /* If there is anything other than a rowset object in memory cell P1,
  69570. ** delete it now and initialize P1 with an empty rowset
  69571. */
  69572. if( (pIn1->flags & MEM_RowSet)==0 ){
  69573. sqlite3VdbeMemSetRowSet(pIn1);
  69574. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69575. }
  69576. assert( pOp->p4type==P4_INT32 );
  69577. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  69578. if( u.cc.iSet ){
  69579. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  69580. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  69581. pIn3->u.i);
  69582. if( u.cc.exists ){
  69583. pc = pOp->p2 - 1;
  69584. break;
  69585. }
  69586. }
  69587. if( u.cc.iSet>=0 ){
  69588. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  69589. }
  69590. break;
  69591. }
  69592. #ifndef SQLITE_OMIT_TRIGGER
  69593. /* Opcode: Program P1 P2 P3 P4 *
  69594. **
  69595. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  69596. **
  69597. ** P1 contains the address of the memory cell that contains the first memory
  69598. ** cell in an array of values used as arguments to the sub-program. P2
  69599. ** contains the address to jump to if the sub-program throws an IGNORE
  69600. ** exception using the RAISE() function. Register P3 contains the address
  69601. ** of a memory cell in this (the parent) VM that is used to allocate the
  69602. ** memory required by the sub-vdbe at runtime.
  69603. **
  69604. ** P4 is a pointer to the VM containing the trigger program.
  69605. */
  69606. case OP_Program: { /* jump */
  69607. #if 0 /* local variables moved into u.cd */
  69608. int nMem; /* Number of memory registers for sub-program */
  69609. int nByte; /* Bytes of runtime space required for sub-program */
  69610. Mem *pRt; /* Register to allocate runtime space */
  69611. Mem *pMem; /* Used to iterate through memory cells */
  69612. Mem *pEnd; /* Last memory cell in new array */
  69613. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  69614. SubProgram *pProgram; /* Sub-program to execute */
  69615. void *t; /* Token identifying trigger */
  69616. #endif /* local variables moved into u.cd */
  69617. u.cd.pProgram = pOp->p4.pProgram;
  69618. u.cd.pRt = &aMem[pOp->p3];
  69619. assert( u.cd.pProgram->nOp>0 );
  69620. /* If the p5 flag is clear, then recursive invocation of triggers is
  69621. ** disabled for backwards compatibility (p5 is set if this sub-program
  69622. ** is really a trigger, not a foreign key action, and the flag set
  69623. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  69624. **
  69625. ** It is recursive invocation of triggers, at the SQL level, that is
  69626. ** disabled. In some cases a single trigger may generate more than one
  69627. ** SubProgram (if the trigger may be executed with more than one different
  69628. ** ON CONFLICT algorithm). SubProgram structures associated with a
  69629. ** single trigger all have the same value for the SubProgram.token
  69630. ** variable. */
  69631. if( pOp->p5 ){
  69632. u.cd.t = u.cd.pProgram->token;
  69633. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  69634. if( u.cd.pFrame ) break;
  69635. }
  69636. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  69637. rc = SQLITE_ERROR;
  69638. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  69639. break;
  69640. }
  69641. /* Register u.cd.pRt is used to store the memory required to save the state
  69642. ** of the current program, and the memory required at runtime to execute
  69643. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  69644. ** is already allocated. Otherwise, it must be initialized. */
  69645. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  69646. /* SubProgram.nMem is set to the number of memory cells used by the
  69647. ** program stored in SubProgram.aOp. As well as these, one memory
  69648. ** cell is required for each cursor used by the program. Set local
  69649. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  69650. */
  69651. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  69652. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  69653. + u.cd.nMem * sizeof(Mem)
  69654. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  69655. + u.cd.pProgram->nOnce * sizeof(u8);
  69656. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  69657. if( !u.cd.pFrame ){
  69658. goto no_mem;
  69659. }
  69660. sqlite3VdbeMemRelease(u.cd.pRt);
  69661. u.cd.pRt->flags = MEM_Frame;
  69662. u.cd.pRt->u.pFrame = u.cd.pFrame;
  69663. u.cd.pFrame->v = p;
  69664. u.cd.pFrame->nChildMem = u.cd.nMem;
  69665. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  69666. u.cd.pFrame->pc = pc;
  69667. u.cd.pFrame->aMem = p->aMem;
  69668. u.cd.pFrame->nMem = p->nMem;
  69669. u.cd.pFrame->apCsr = p->apCsr;
  69670. u.cd.pFrame->nCursor = p->nCursor;
  69671. u.cd.pFrame->aOp = p->aOp;
  69672. u.cd.pFrame->nOp = p->nOp;
  69673. u.cd.pFrame->token = u.cd.pProgram->token;
  69674. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  69675. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  69676. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  69677. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  69678. u.cd.pMem->flags = MEM_Invalid;
  69679. u.cd.pMem->db = db;
  69680. }
  69681. }else{
  69682. u.cd.pFrame = u.cd.pRt->u.pFrame;
  69683. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  69684. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  69685. assert( pc==u.cd.pFrame->pc );
  69686. }
  69687. p->nFrame++;
  69688. u.cd.pFrame->pParent = p->pFrame;
  69689. u.cd.pFrame->lastRowid = lastRowid;
  69690. u.cd.pFrame->nChange = p->nChange;
  69691. p->nChange = 0;
  69692. p->pFrame = u.cd.pFrame;
  69693. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  69694. p->nMem = u.cd.pFrame->nChildMem;
  69695. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  69696. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  69697. p->aOp = aOp = u.cd.pProgram->aOp;
  69698. p->nOp = u.cd.pProgram->nOp;
  69699. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  69700. p->nOnceFlag = u.cd.pProgram->nOnce;
  69701. pc = -1;
  69702. memset(p->aOnceFlag, 0, p->nOnceFlag);
  69703. break;
  69704. }
  69705. /* Opcode: Param P1 P2 * * *
  69706. **
  69707. ** This opcode is only ever present in sub-programs called via the
  69708. ** OP_Program instruction. Copy a value currently stored in a memory
  69709. ** cell of the calling (parent) frame to cell P2 in the current frames
  69710. ** address space. This is used by trigger programs to access the new.*
  69711. ** and old.* values.
  69712. **
  69713. ** The address of the cell in the parent frame is determined by adding
  69714. ** the value of the P1 argument to the value of the P1 argument to the
  69715. ** calling OP_Program instruction.
  69716. */
  69717. case OP_Param: { /* out2-prerelease */
  69718. #if 0 /* local variables moved into u.ce */
  69719. VdbeFrame *pFrame;
  69720. Mem *pIn;
  69721. #endif /* local variables moved into u.ce */
  69722. u.ce.pFrame = p->pFrame;
  69723. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  69724. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  69725. break;
  69726. }
  69727. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  69728. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69729. /* Opcode: FkCounter P1 P2 * * *
  69730. **
  69731. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  69732. ** If P1 is non-zero, the database constraint counter is incremented
  69733. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  69734. ** statement counter is incremented (immediate foreign key constraints).
  69735. */
  69736. case OP_FkCounter: {
  69737. if( db->flags & SQLITE_DeferFKs ){
  69738. db->nDeferredImmCons += pOp->p2;
  69739. }else if( pOp->p1 ){
  69740. db->nDeferredCons += pOp->p2;
  69741. }else{
  69742. p->nFkConstraint += pOp->p2;
  69743. }
  69744. break;
  69745. }
  69746. /* Opcode: FkIfZero P1 P2 * * *
  69747. **
  69748. ** This opcode tests if a foreign key constraint-counter is currently zero.
  69749. ** If so, jump to instruction P2. Otherwise, fall through to the next
  69750. ** instruction.
  69751. **
  69752. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  69753. ** is zero (the one that counts deferred constraint violations). If P1 is
  69754. ** zero, the jump is taken if the statement constraint-counter is zero
  69755. ** (immediate foreign key constraint violations).
  69756. */
  69757. case OP_FkIfZero: { /* jump */
  69758. if( pOp->p1 ){
  69759. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69760. }else{
  69761. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69762. }
  69763. break;
  69764. }
  69765. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  69766. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69767. /* Opcode: MemMax P1 P2 * * *
  69768. **
  69769. ** P1 is a register in the root frame of this VM (the root frame is
  69770. ** different from the current frame if this instruction is being executed
  69771. ** within a sub-program). Set the value of register P1 to the maximum of
  69772. ** its current value and the value in register P2.
  69773. **
  69774. ** This instruction throws an error if the memory cell is not initially
  69775. ** an integer.
  69776. */
  69777. case OP_MemMax: { /* in2 */
  69778. #if 0 /* local variables moved into u.cf */
  69779. Mem *pIn1;
  69780. VdbeFrame *pFrame;
  69781. #endif /* local variables moved into u.cf */
  69782. if( p->pFrame ){
  69783. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  69784. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  69785. }else{
  69786. u.cf.pIn1 = &aMem[pOp->p1];
  69787. }
  69788. assert( memIsValid(u.cf.pIn1) );
  69789. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  69790. pIn2 = &aMem[pOp->p2];
  69791. sqlite3VdbeMemIntegerify(pIn2);
  69792. if( u.cf.pIn1->u.i<pIn2->u.i){
  69793. u.cf.pIn1->u.i = pIn2->u.i;
  69794. }
  69795. break;
  69796. }
  69797. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  69798. /* Opcode: IfPos P1 P2 * * *
  69799. **
  69800. ** If the value of register P1 is 1 or greater, jump to P2.
  69801. **
  69802. ** It is illegal to use this instruction on a register that does
  69803. ** not contain an integer. An assertion fault will result if you try.
  69804. */
  69805. case OP_IfPos: { /* jump, in1 */
  69806. pIn1 = &aMem[pOp->p1];
  69807. assert( pIn1->flags&MEM_Int );
  69808. if( pIn1->u.i>0 ){
  69809. pc = pOp->p2 - 1;
  69810. }
  69811. break;
  69812. }
  69813. /* Opcode: IfNeg P1 P2 * * *
  69814. **
  69815. ** If the value of register P1 is less than zero, jump to P2.
  69816. **
  69817. ** It is illegal to use this instruction on a register that does
  69818. ** not contain an integer. An assertion fault will result if you try.
  69819. */
  69820. case OP_IfNeg: { /* jump, in1 */
  69821. pIn1 = &aMem[pOp->p1];
  69822. assert( pIn1->flags&MEM_Int );
  69823. if( pIn1->u.i<0 ){
  69824. pc = pOp->p2 - 1;
  69825. }
  69826. break;
  69827. }
  69828. /* Opcode: IfZero P1 P2 P3 * *
  69829. **
  69830. ** The register P1 must contain an integer. Add literal P3 to the
  69831. ** value in register P1. If the result is exactly 0, jump to P2.
  69832. **
  69833. ** It is illegal to use this instruction on a register that does
  69834. ** not contain an integer. An assertion fault will result if you try.
  69835. */
  69836. case OP_IfZero: { /* jump, in1 */
  69837. pIn1 = &aMem[pOp->p1];
  69838. assert( pIn1->flags&MEM_Int );
  69839. pIn1->u.i += pOp->p3;
  69840. if( pIn1->u.i==0 ){
  69841. pc = pOp->p2 - 1;
  69842. }
  69843. break;
  69844. }
  69845. /* Opcode: AggStep * P2 P3 P4 P5
  69846. **
  69847. ** Execute the step function for an aggregate. The
  69848. ** function has P5 arguments. P4 is a pointer to the FuncDef
  69849. ** structure that specifies the function. Use register
  69850. ** P3 as the accumulator.
  69851. **
  69852. ** The P5 arguments are taken from register P2 and its
  69853. ** successors.
  69854. */
  69855. case OP_AggStep: {
  69856. #if 0 /* local variables moved into u.cg */
  69857. int n;
  69858. int i;
  69859. Mem *pMem;
  69860. Mem *pRec;
  69861. sqlite3_context ctx;
  69862. sqlite3_value **apVal;
  69863. #endif /* local variables moved into u.cg */
  69864. u.cg.n = pOp->p5;
  69865. assert( u.cg.n>=0 );
  69866. u.cg.pRec = &aMem[pOp->p2];
  69867. u.cg.apVal = p->apArg;
  69868. assert( u.cg.apVal || u.cg.n==0 );
  69869. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  69870. assert( memIsValid(u.cg.pRec) );
  69871. u.cg.apVal[u.cg.i] = u.cg.pRec;
  69872. memAboutToChange(p, u.cg.pRec);
  69873. sqlite3VdbeMemStoreType(u.cg.pRec);
  69874. }
  69875. u.cg.ctx.pFunc = pOp->p4.pFunc;
  69876. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69877. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  69878. u.cg.pMem->n++;
  69879. u.cg.ctx.s.flags = MEM_Null;
  69880. u.cg.ctx.s.z = 0;
  69881. u.cg.ctx.s.zMalloc = 0;
  69882. u.cg.ctx.s.xDel = 0;
  69883. u.cg.ctx.s.db = db;
  69884. u.cg.ctx.isError = 0;
  69885. u.cg.ctx.pColl = 0;
  69886. u.cg.ctx.skipFlag = 0;
  69887. if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  69888. assert( pOp>p->aOp );
  69889. assert( pOp[-1].p4type==P4_COLLSEQ );
  69890. assert( pOp[-1].opcode==OP_CollSeq );
  69891. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  69892. }
  69893. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  69894. if( u.cg.ctx.isError ){
  69895. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  69896. rc = u.cg.ctx.isError;
  69897. }
  69898. if( u.cg.ctx.skipFlag ){
  69899. assert( pOp[-1].opcode==OP_CollSeq );
  69900. u.cg.i = pOp[-1].p1;
  69901. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  69902. }
  69903. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  69904. break;
  69905. }
  69906. /* Opcode: AggFinal P1 P2 * P4 *
  69907. **
  69908. ** Execute the finalizer function for an aggregate. P1 is
  69909. ** the memory location that is the accumulator for the aggregate.
  69910. **
  69911. ** P2 is the number of arguments that the step function takes and
  69912. ** P4 is a pointer to the FuncDef for this function. The P2
  69913. ** argument is not used by this opcode. It is only there to disambiguate
  69914. ** functions that can take varying numbers of arguments. The
  69915. ** P4 argument is only needed for the degenerate case where
  69916. ** the step function was not previously called.
  69917. */
  69918. case OP_AggFinal: {
  69919. #if 0 /* local variables moved into u.ch */
  69920. Mem *pMem;
  69921. #endif /* local variables moved into u.ch */
  69922. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69923. u.ch.pMem = &aMem[pOp->p1];
  69924. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  69925. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  69926. if( rc ){
  69927. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  69928. }
  69929. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  69930. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  69931. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  69932. goto too_big;
  69933. }
  69934. break;
  69935. }
  69936. #ifndef SQLITE_OMIT_WAL
  69937. /* Opcode: Checkpoint P1 P2 P3 * *
  69938. **
  69939. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  69940. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  69941. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  69942. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  69943. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  69944. ** in the WAL that have been checkpointed after the checkpoint
  69945. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  69946. ** mem[P3+2] are initialized to -1.
  69947. */
  69948. case OP_Checkpoint: {
  69949. #if 0 /* local variables moved into u.ci */
  69950. int i; /* Loop counter */
  69951. int aRes[3]; /* Results */
  69952. Mem *pMem; /* Write results here */
  69953. #endif /* local variables moved into u.ci */
  69954. assert( p->readOnly==0 );
  69955. u.ci.aRes[0] = 0;
  69956. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  69957. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  69958. || pOp->p2==SQLITE_CHECKPOINT_FULL
  69959. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  69960. );
  69961. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  69962. if( rc==SQLITE_BUSY ){
  69963. rc = SQLITE_OK;
  69964. u.ci.aRes[0] = 1;
  69965. }
  69966. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  69967. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  69968. }
  69969. break;
  69970. };
  69971. #endif
  69972. #ifndef SQLITE_OMIT_PRAGMA
  69973. /* Opcode: JournalMode P1 P2 P3 * P5
  69974. **
  69975. ** Change the journal mode of database P1 to P3. P3 must be one of the
  69976. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  69977. ** modes (delete, truncate, persist, off and memory), this is a simple
  69978. ** operation. No IO is required.
  69979. **
  69980. ** If changing into or out of WAL mode the procedure is more complicated.
  69981. **
  69982. ** Write a string containing the final journal-mode to register P2.
  69983. */
  69984. case OP_JournalMode: { /* out2-prerelease */
  69985. #if 0 /* local variables moved into u.cj */
  69986. Btree *pBt; /* Btree to change journal mode of */
  69987. Pager *pPager; /* Pager associated with pBt */
  69988. int eNew; /* New journal mode */
  69989. int eOld; /* The old journal mode */
  69990. #ifndef SQLITE_OMIT_WAL
  69991. const char *zFilename; /* Name of database file for pPager */
  69992. #endif
  69993. #endif /* local variables moved into u.cj */
  69994. u.cj.eNew = pOp->p3;
  69995. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  69996. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  69997. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  69998. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  69999. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  70000. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  70001. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  70002. );
  70003. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70004. assert( p->readOnly==0 );
  70005. u.cj.pBt = db->aDb[pOp->p1].pBt;
  70006. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  70007. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  70008. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  70009. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  70010. #ifndef SQLITE_OMIT_WAL
  70011. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  70012. /* Do not allow a transition to journal_mode=WAL for a database
  70013. ** in temporary storage or if the VFS does not support shared memory
  70014. */
  70015. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  70016. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  70017. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  70018. ){
  70019. u.cj.eNew = u.cj.eOld;
  70020. }
  70021. if( (u.cj.eNew!=u.cj.eOld)
  70022. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  70023. ){
  70024. if( !db->autoCommit || db->nVdbeRead>1 ){
  70025. rc = SQLITE_ERROR;
  70026. sqlite3SetString(&p->zErrMsg, db,
  70027. "cannot change %s wal mode from within a transaction",
  70028. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  70029. );
  70030. break;
  70031. }else{
  70032. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  70033. /* If leaving WAL mode, close the log file. If successful, the call
  70034. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  70035. ** file. An EXCLUSIVE lock may still be held on the database file
  70036. ** after a successful return.
  70037. */
  70038. rc = sqlite3PagerCloseWal(u.cj.pPager);
  70039. if( rc==SQLITE_OK ){
  70040. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  70041. }
  70042. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  70043. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  70044. ** as an intermediate */
  70045. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  70046. }
  70047. /* Open a transaction on the database file. Regardless of the journal
  70048. ** mode, this transaction always uses a rollback journal.
  70049. */
  70050. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  70051. if( rc==SQLITE_OK ){
  70052. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  70053. }
  70054. }
  70055. }
  70056. #endif /* ifndef SQLITE_OMIT_WAL */
  70057. if( rc ){
  70058. u.cj.eNew = u.cj.eOld;
  70059. }
  70060. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  70061. pOut = &aMem[pOp->p2];
  70062. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  70063. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  70064. pOut->n = sqlite3Strlen30(pOut->z);
  70065. pOut->enc = SQLITE_UTF8;
  70066. sqlite3VdbeChangeEncoding(pOut, encoding);
  70067. break;
  70068. };
  70069. #endif /* SQLITE_OMIT_PRAGMA */
  70070. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  70071. /* Opcode: Vacuum * * * * *
  70072. **
  70073. ** Vacuum the entire database. This opcode will cause other virtual
  70074. ** machines to be created and run. It may not be called from within
  70075. ** a transaction.
  70076. */
  70077. case OP_Vacuum: {
  70078. assert( p->readOnly==0 );
  70079. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  70080. break;
  70081. }
  70082. #endif
  70083. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  70084. /* Opcode: IncrVacuum P1 P2 * * *
  70085. **
  70086. ** Perform a single step of the incremental vacuum procedure on
  70087. ** the P1 database. If the vacuum has finished, jump to instruction
  70088. ** P2. Otherwise, fall through to the next instruction.
  70089. */
  70090. case OP_IncrVacuum: { /* jump */
  70091. #if 0 /* local variables moved into u.ck */
  70092. Btree *pBt;
  70093. #endif /* local variables moved into u.ck */
  70094. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70095. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  70096. assert( p->readOnly==0 );
  70097. u.ck.pBt = db->aDb[pOp->p1].pBt;
  70098. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  70099. if( rc==SQLITE_DONE ){
  70100. pc = pOp->p2 - 1;
  70101. rc = SQLITE_OK;
  70102. }
  70103. break;
  70104. }
  70105. #endif
  70106. /* Opcode: Expire P1 * * * *
  70107. **
  70108. ** Cause precompiled statements to become expired. An expired statement
  70109. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  70110. ** (via sqlite3_step()).
  70111. **
  70112. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  70113. ** then only the currently executing statement is affected.
  70114. */
  70115. case OP_Expire: {
  70116. if( !pOp->p1 ){
  70117. sqlite3ExpirePreparedStatements(db);
  70118. }else{
  70119. p->expired = 1;
  70120. }
  70121. break;
  70122. }
  70123. #ifndef SQLITE_OMIT_SHARED_CACHE
  70124. /* Opcode: TableLock P1 P2 P3 P4 *
  70125. **
  70126. ** Obtain a lock on a particular table. This instruction is only used when
  70127. ** the shared-cache feature is enabled.
  70128. **
  70129. ** P1 is the index of the database in sqlite3.aDb[] of the database
  70130. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  70131. ** a write lock if P3==1.
  70132. **
  70133. ** P2 contains the root-page of the table to lock.
  70134. **
  70135. ** P4 contains a pointer to the name of the table being locked. This is only
  70136. ** used to generate an error message if the lock cannot be obtained.
  70137. */
  70138. case OP_TableLock: {
  70139. u8 isWriteLock = (u8)pOp->p3;
  70140. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  70141. int p1 = pOp->p1;
  70142. assert( p1>=0 && p1<db->nDb );
  70143. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  70144. assert( isWriteLock==0 || isWriteLock==1 );
  70145. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  70146. if( (rc&0xFF)==SQLITE_LOCKED ){
  70147. const char *z = pOp->p4.z;
  70148. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  70149. }
  70150. }
  70151. break;
  70152. }
  70153. #endif /* SQLITE_OMIT_SHARED_CACHE */
  70154. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70155. /* Opcode: VBegin * * * P4 *
  70156. **
  70157. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  70158. ** xBegin method for that table.
  70159. **
  70160. ** Also, whether or not P4 is set, check that this is not being called from
  70161. ** within a callback to a virtual table xSync() method. If it is, the error
  70162. ** code will be set to SQLITE_LOCKED.
  70163. */
  70164. case OP_VBegin: {
  70165. #if 0 /* local variables moved into u.cl */
  70166. VTable *pVTab;
  70167. #endif /* local variables moved into u.cl */
  70168. u.cl.pVTab = pOp->p4.pVtab;
  70169. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  70170. if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
  70171. break;
  70172. }
  70173. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70174. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70175. /* Opcode: VCreate P1 * * P4 *
  70176. **
  70177. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  70178. ** for that table.
  70179. */
  70180. case OP_VCreate: {
  70181. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  70182. break;
  70183. }
  70184. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70185. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70186. /* Opcode: VDestroy P1 * * P4 *
  70187. **
  70188. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  70189. ** of that table.
  70190. */
  70191. case OP_VDestroy: {
  70192. p->inVtabMethod = 2;
  70193. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  70194. p->inVtabMethod = 0;
  70195. break;
  70196. }
  70197. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70198. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70199. /* Opcode: VOpen P1 * * P4 *
  70200. **
  70201. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70202. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  70203. ** table and stores that cursor in P1.
  70204. */
  70205. case OP_VOpen: {
  70206. #if 0 /* local variables moved into u.cm */
  70207. VdbeCursor *pCur;
  70208. sqlite3_vtab_cursor *pVtabCursor;
  70209. sqlite3_vtab *pVtab;
  70210. sqlite3_module *pModule;
  70211. #endif /* local variables moved into u.cm */
  70212. assert( p->bIsReader );
  70213. u.cm.pCur = 0;
  70214. u.cm.pVtabCursor = 0;
  70215. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  70216. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  70217. assert(u.cm.pVtab && u.cm.pModule);
  70218. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  70219. sqlite3VtabImportErrmsg(p, u.cm.pVtab);
  70220. if( SQLITE_OK==rc ){
  70221. /* Initialize sqlite3_vtab_cursor base class */
  70222. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  70223. /* Initialize vdbe cursor object */
  70224. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  70225. if( u.cm.pCur ){
  70226. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  70227. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  70228. }else{
  70229. db->mallocFailed = 1;
  70230. u.cm.pModule->xClose(u.cm.pVtabCursor);
  70231. }
  70232. }
  70233. break;
  70234. }
  70235. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70236. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70237. /* Opcode: VFilter P1 P2 P3 P4 *
  70238. **
  70239. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  70240. ** the filtered result set is empty.
  70241. **
  70242. ** P4 is either NULL or a string that was generated by the xBestIndex
  70243. ** method of the module. The interpretation of the P4 string is left
  70244. ** to the module implementation.
  70245. **
  70246. ** This opcode invokes the xFilter method on the virtual table specified
  70247. ** by P1. The integer query plan parameter to xFilter is stored in register
  70248. ** P3. Register P3+1 stores the argc parameter to be passed to the
  70249. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  70250. ** additional parameters which are passed to
  70251. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  70252. **
  70253. ** A jump is made to P2 if the result set after filtering would be empty.
  70254. */
  70255. case OP_VFilter: { /* jump */
  70256. #if 0 /* local variables moved into u.cn */
  70257. int nArg;
  70258. int iQuery;
  70259. const sqlite3_module *pModule;
  70260. Mem *pQuery;
  70261. Mem *pArgc;
  70262. sqlite3_vtab_cursor *pVtabCursor;
  70263. sqlite3_vtab *pVtab;
  70264. VdbeCursor *pCur;
  70265. int res;
  70266. int i;
  70267. Mem **apArg;
  70268. #endif /* local variables moved into u.cn */
  70269. u.cn.pQuery = &aMem[pOp->p3];
  70270. u.cn.pArgc = &u.cn.pQuery[1];
  70271. u.cn.pCur = p->apCsr[pOp->p1];
  70272. assert( memIsValid(u.cn.pQuery) );
  70273. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  70274. assert( u.cn.pCur->pVtabCursor );
  70275. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  70276. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  70277. u.cn.pModule = u.cn.pVtab->pModule;
  70278. /* Grab the index number and argc parameters */
  70279. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  70280. u.cn.nArg = (int)u.cn.pArgc->u.i;
  70281. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  70282. /* Invoke the xFilter method */
  70283. {
  70284. u.cn.res = 0;
  70285. u.cn.apArg = p->apArg;
  70286. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  70287. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  70288. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  70289. }
  70290. p->inVtabMethod = 1;
  70291. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  70292. p->inVtabMethod = 0;
  70293. sqlite3VtabImportErrmsg(p, u.cn.pVtab);
  70294. if( rc==SQLITE_OK ){
  70295. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  70296. }
  70297. if( u.cn.res ){
  70298. pc = pOp->p2 - 1;
  70299. }
  70300. }
  70301. u.cn.pCur->nullRow = 0;
  70302. break;
  70303. }
  70304. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70305. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70306. /* Opcode: VColumn P1 P2 P3 * *
  70307. **
  70308. ** Store the value of the P2-th column of
  70309. ** the row of the virtual-table that the
  70310. ** P1 cursor is pointing to into register P3.
  70311. */
  70312. case OP_VColumn: {
  70313. #if 0 /* local variables moved into u.co */
  70314. sqlite3_vtab *pVtab;
  70315. const sqlite3_module *pModule;
  70316. Mem *pDest;
  70317. sqlite3_context sContext;
  70318. #endif /* local variables moved into u.co */
  70319. VdbeCursor *pCur = p->apCsr[pOp->p1];
  70320. assert( pCur->pVtabCursor );
  70321. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70322. u.co.pDest = &aMem[pOp->p3];
  70323. memAboutToChange(p, u.co.pDest);
  70324. if( pCur->nullRow ){
  70325. sqlite3VdbeMemSetNull(u.co.pDest);
  70326. break;
  70327. }
  70328. u.co.pVtab = pCur->pVtabCursor->pVtab;
  70329. u.co.pModule = u.co.pVtab->pModule;
  70330. assert( u.co.pModule->xColumn );
  70331. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  70332. /* The output cell may already have a buffer allocated. Move
  70333. ** the current contents to u.co.sContext.s so in case the user-function
  70334. ** can use the already allocated buffer instead of allocating a
  70335. ** new one.
  70336. */
  70337. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  70338. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  70339. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  70340. sqlite3VtabImportErrmsg(p, u.co.pVtab);
  70341. if( u.co.sContext.isError ){
  70342. rc = u.co.sContext.isError;
  70343. }
  70344. /* Copy the result of the function to the P3 register. We
  70345. ** do this regardless of whether or not an error occurred to ensure any
  70346. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  70347. */
  70348. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  70349. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  70350. REGISTER_TRACE(pOp->p3, u.co.pDest);
  70351. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  70352. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  70353. goto too_big;
  70354. }
  70355. break;
  70356. }
  70357. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70358. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70359. /* Opcode: VNext P1 P2 * * *
  70360. **
  70361. ** Advance virtual table P1 to the next row in its result set and
  70362. ** jump to instruction P2. Or, if the virtual table has reached
  70363. ** the end of its result set, then fall through to the next instruction.
  70364. */
  70365. case OP_VNext: { /* jump */
  70366. #if 0 /* local variables moved into u.cp */
  70367. sqlite3_vtab *pVtab;
  70368. const sqlite3_module *pModule;
  70369. int res;
  70370. VdbeCursor *pCur;
  70371. #endif /* local variables moved into u.cp */
  70372. u.cp.res = 0;
  70373. u.cp.pCur = p->apCsr[pOp->p1];
  70374. assert( u.cp.pCur->pVtabCursor );
  70375. if( u.cp.pCur->nullRow ){
  70376. break;
  70377. }
  70378. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  70379. u.cp.pModule = u.cp.pVtab->pModule;
  70380. assert( u.cp.pModule->xNext );
  70381. /* Invoke the xNext() method of the module. There is no way for the
  70382. ** underlying implementation to return an error if one occurs during
  70383. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  70384. ** data is available) and the error code returned when xColumn or
  70385. ** some other method is next invoked on the save virtual table cursor.
  70386. */
  70387. p->inVtabMethod = 1;
  70388. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  70389. p->inVtabMethod = 0;
  70390. sqlite3VtabImportErrmsg(p, u.cp.pVtab);
  70391. if( rc==SQLITE_OK ){
  70392. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  70393. }
  70394. if( !u.cp.res ){
  70395. /* If there is data, jump to P2 */
  70396. pc = pOp->p2 - 1;
  70397. }
  70398. goto check_for_interrupt;
  70399. }
  70400. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70401. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70402. /* Opcode: VRename P1 * * P4 *
  70403. **
  70404. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70405. ** This opcode invokes the corresponding xRename method. The value
  70406. ** in register P1 is passed as the zName argument to the xRename method.
  70407. */
  70408. case OP_VRename: {
  70409. #if 0 /* local variables moved into u.cq */
  70410. sqlite3_vtab *pVtab;
  70411. Mem *pName;
  70412. #endif /* local variables moved into u.cq */
  70413. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  70414. u.cq.pName = &aMem[pOp->p1];
  70415. assert( u.cq.pVtab->pModule->xRename );
  70416. assert( memIsValid(u.cq.pName) );
  70417. assert( p->readOnly==0 );
  70418. REGISTER_TRACE(pOp->p1, u.cq.pName);
  70419. assert( u.cq.pName->flags & MEM_Str );
  70420. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  70421. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  70422. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  70423. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  70424. if( rc==SQLITE_OK ){
  70425. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  70426. sqlite3VtabImportErrmsg(p, u.cq.pVtab);
  70427. p->expired = 0;
  70428. }
  70429. break;
  70430. }
  70431. #endif
  70432. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70433. /* Opcode: VUpdate P1 P2 P3 P4 *
  70434. **
  70435. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70436. ** This opcode invokes the corresponding xUpdate method. P2 values
  70437. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  70438. ** invocation. The value in register (P3+P2-1) corresponds to the
  70439. ** p2th element of the argv array passed to xUpdate.
  70440. **
  70441. ** The xUpdate method will do a DELETE or an INSERT or both.
  70442. ** The argv[0] element (which corresponds to memory cell P3)
  70443. ** is the rowid of a row to delete. If argv[0] is NULL then no
  70444. ** deletion occurs. The argv[1] element is the rowid of the new
  70445. ** row. This can be NULL to have the virtual table select the new
  70446. ** rowid for itself. The subsequent elements in the array are
  70447. ** the values of columns in the new row.
  70448. **
  70449. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  70450. ** a row to delete.
  70451. **
  70452. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  70453. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  70454. ** is set to the value of the rowid for the row just inserted.
  70455. */
  70456. case OP_VUpdate: {
  70457. #if 0 /* local variables moved into u.cr */
  70458. sqlite3_vtab *pVtab;
  70459. sqlite3_module *pModule;
  70460. int nArg;
  70461. int i;
  70462. sqlite_int64 rowid;
  70463. Mem **apArg;
  70464. Mem *pX;
  70465. #endif /* local variables moved into u.cr */
  70466. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  70467. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  70468. );
  70469. assert( p->readOnly==0 );
  70470. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  70471. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  70472. u.cr.nArg = pOp->p2;
  70473. assert( pOp->p4type==P4_VTAB );
  70474. if( ALWAYS(u.cr.pModule->xUpdate) ){
  70475. u8 vtabOnConflict = db->vtabOnConflict;
  70476. u.cr.apArg = p->apArg;
  70477. u.cr.pX = &aMem[pOp->p3];
  70478. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  70479. assert( memIsValid(u.cr.pX) );
  70480. memAboutToChange(p, u.cr.pX);
  70481. sqlite3VdbeMemStoreType(u.cr.pX);
  70482. u.cr.apArg[u.cr.i] = u.cr.pX;
  70483. u.cr.pX++;
  70484. }
  70485. db->vtabOnConflict = pOp->p5;
  70486. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  70487. db->vtabOnConflict = vtabOnConflict;
  70488. sqlite3VtabImportErrmsg(p, u.cr.pVtab);
  70489. if( rc==SQLITE_OK && pOp->p1 ){
  70490. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  70491. db->lastRowid = lastRowid = u.cr.rowid;
  70492. }
  70493. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  70494. if( pOp->p5==OE_Ignore ){
  70495. rc = SQLITE_OK;
  70496. }else{
  70497. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  70498. }
  70499. }else{
  70500. p->nChange++;
  70501. }
  70502. }
  70503. break;
  70504. }
  70505. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70506. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70507. /* Opcode: Pagecount P1 P2 * * *
  70508. **
  70509. ** Write the current number of pages in database P1 to memory cell P2.
  70510. */
  70511. case OP_Pagecount: { /* out2-prerelease */
  70512. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  70513. break;
  70514. }
  70515. #endif
  70516. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70517. /* Opcode: MaxPgcnt P1 P2 P3 * *
  70518. **
  70519. ** Try to set the maximum page count for database P1 to the value in P3.
  70520. ** Do not let the maximum page count fall below the current page count and
  70521. ** do not change the maximum page count value if P3==0.
  70522. **
  70523. ** Store the maximum page count after the change in register P2.
  70524. */
  70525. case OP_MaxPgcnt: { /* out2-prerelease */
  70526. unsigned int newMax;
  70527. Btree *pBt;
  70528. pBt = db->aDb[pOp->p1].pBt;
  70529. newMax = 0;
  70530. if( pOp->p3 ){
  70531. newMax = sqlite3BtreeLastPage(pBt);
  70532. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  70533. }
  70534. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  70535. break;
  70536. }
  70537. #endif
  70538. #ifndef SQLITE_OMIT_TRACE
  70539. /* Opcode: Trace * * * P4 *
  70540. **
  70541. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  70542. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  70543. */
  70544. case OP_Trace: {
  70545. #if 0 /* local variables moved into u.cs */
  70546. char *zTrace;
  70547. char *z;
  70548. #endif /* local variables moved into u.cs */
  70549. if( db->xTrace
  70550. && !p->doingRerun
  70551. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70552. ){
  70553. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  70554. db->xTrace(db->pTraceArg, u.cs.z);
  70555. sqlite3DbFree(db, u.cs.z);
  70556. }
  70557. #ifdef SQLITE_DEBUG
  70558. if( (db->flags & SQLITE_SqlTrace)!=0
  70559. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70560. ){
  70561. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  70562. }
  70563. #endif /* SQLITE_DEBUG */
  70564. break;
  70565. }
  70566. #endif
  70567. /* Opcode: Noop * * * * *
  70568. **
  70569. ** Do nothing. This instruction is often useful as a jump
  70570. ** destination.
  70571. */
  70572. /*
  70573. ** The magic Explain opcode are only inserted when explain==2 (which
  70574. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  70575. ** This opcode records information from the optimizer. It is the
  70576. ** the same as a no-op. This opcodesnever appears in a real VM program.
  70577. */
  70578. default: { /* This is really OP_Noop and OP_Explain */
  70579. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  70580. break;
  70581. }
  70582. /*****************************************************************************
  70583. ** The cases of the switch statement above this line should all be indented
  70584. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  70585. ** readability. From this point on down, the normal indentation rules are
  70586. ** restored.
  70587. *****************************************************************************/
  70588. }
  70589. #ifdef VDBE_PROFILE
  70590. {
  70591. u64 elapsed = sqlite3Hwtime() - start;
  70592. pOp->cycles += elapsed;
  70593. pOp->cnt++;
  70594. #if 0
  70595. fprintf(stdout, "%10llu ", elapsed);
  70596. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  70597. #endif
  70598. }
  70599. #endif
  70600. /* The following code adds nothing to the actual functionality
  70601. ** of the program. It is only here for testing and debugging.
  70602. ** On the other hand, it does burn CPU cycles every time through
  70603. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  70604. */
  70605. #ifndef NDEBUG
  70606. assert( pc>=-1 && pc<p->nOp );
  70607. #ifdef SQLITE_DEBUG
  70608. if( p->trace ){
  70609. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  70610. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  70611. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  70612. }
  70613. if( pOp->opflags & OPFLG_OUT3 ){
  70614. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  70615. }
  70616. }
  70617. #endif /* SQLITE_DEBUG */
  70618. #endif /* NDEBUG */
  70619. } /* The end of the for(;;) loop the loops through opcodes */
  70620. /* If we reach this point, it means that execution is finished with
  70621. ** an error of some kind.
  70622. */
  70623. vdbe_error_halt:
  70624. assert( rc );
  70625. p->rc = rc;
  70626. testcase( sqlite3GlobalConfig.xLog!=0 );
  70627. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  70628. pc, p->zSql, p->zErrMsg);
  70629. sqlite3VdbeHalt(p);
  70630. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  70631. rc = SQLITE_ERROR;
  70632. if( resetSchemaOnFault>0 ){
  70633. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  70634. }
  70635. /* This is the only way out of this procedure. We have to
  70636. ** release the mutexes on btrees that were acquired at the
  70637. ** top. */
  70638. vdbe_return:
  70639. db->lastRowid = lastRowid;
  70640. testcase( nVmStep>0 );
  70641. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  70642. sqlite3VdbeLeave(p);
  70643. return rc;
  70644. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  70645. ** is encountered.
  70646. */
  70647. too_big:
  70648. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  70649. rc = SQLITE_TOOBIG;
  70650. goto vdbe_error_halt;
  70651. /* Jump to here if a malloc() fails.
  70652. */
  70653. no_mem:
  70654. db->mallocFailed = 1;
  70655. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  70656. rc = SQLITE_NOMEM;
  70657. goto vdbe_error_halt;
  70658. /* Jump to here for any other kind of fatal error. The "rc" variable
  70659. ** should hold the error number.
  70660. */
  70661. abort_due_to_error:
  70662. assert( p->zErrMsg==0 );
  70663. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  70664. if( rc!=SQLITE_IOERR_NOMEM ){
  70665. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70666. }
  70667. goto vdbe_error_halt;
  70668. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  70669. ** flag.
  70670. */
  70671. abort_due_to_interrupt:
  70672. assert( db->u1.isInterrupted );
  70673. rc = SQLITE_INTERRUPT;
  70674. p->rc = rc;
  70675. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70676. goto vdbe_error_halt;
  70677. }
  70678. /************** End of vdbe.c ************************************************/
  70679. /************** Begin file vdbeblob.c ****************************************/
  70680. /*
  70681. ** 2007 May 1
  70682. **
  70683. ** The author disclaims copyright to this source code. In place of
  70684. ** a legal notice, here is a blessing:
  70685. **
  70686. ** May you do good and not evil.
  70687. ** May you find forgiveness for yourself and forgive others.
  70688. ** May you share freely, never taking more than you give.
  70689. **
  70690. *************************************************************************
  70691. **
  70692. ** This file contains code used to implement incremental BLOB I/O.
  70693. */
  70694. #ifndef SQLITE_OMIT_INCRBLOB
  70695. /*
  70696. ** Valid sqlite3_blob* handles point to Incrblob structures.
  70697. */
  70698. typedef struct Incrblob Incrblob;
  70699. struct Incrblob {
  70700. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  70701. int nByte; /* Size of open blob, in bytes */
  70702. int iOffset; /* Byte offset of blob in cursor data */
  70703. int iCol; /* Table column this handle is open on */
  70704. BtCursor *pCsr; /* Cursor pointing at blob row */
  70705. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  70706. sqlite3 *db; /* The associated database */
  70707. };
  70708. /*
  70709. ** This function is used by both blob_open() and blob_reopen(). It seeks
  70710. ** the b-tree cursor associated with blob handle p to point to row iRow.
  70711. ** If successful, SQLITE_OK is returned and subsequent calls to
  70712. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  70713. **
  70714. ** If an error occurs, or if the specified row does not exist or does not
  70715. ** contain a value of type TEXT or BLOB in the column nominated when the
  70716. ** blob handle was opened, then an error code is returned and *pzErr may
  70717. ** be set to point to a buffer containing an error message. It is the
  70718. ** responsibility of the caller to free the error message buffer using
  70719. ** sqlite3DbFree().
  70720. **
  70721. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  70722. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  70723. ** immediately return SQLITE_ABORT.
  70724. */
  70725. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  70726. int rc; /* Error code */
  70727. char *zErr = 0; /* Error message */
  70728. Vdbe *v = (Vdbe *)p->pStmt;
  70729. /* Set the value of the SQL statements only variable to integer iRow.
  70730. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  70731. ** triggering asserts related to mutexes.
  70732. */
  70733. assert( v->aVar[0].flags&MEM_Int );
  70734. v->aVar[0].u.i = iRow;
  70735. rc = sqlite3_step(p->pStmt);
  70736. if( rc==SQLITE_ROW ){
  70737. u32 type = v->apCsr[0]->aType[p->iCol];
  70738. if( type<12 ){
  70739. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  70740. type==0?"null": type==7?"real": "integer"
  70741. );
  70742. rc = SQLITE_ERROR;
  70743. sqlite3_finalize(p->pStmt);
  70744. p->pStmt = 0;
  70745. }else{
  70746. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  70747. p->nByte = sqlite3VdbeSerialTypeLen(type);
  70748. p->pCsr = v->apCsr[0]->pCursor;
  70749. sqlite3BtreeEnterCursor(p->pCsr);
  70750. sqlite3BtreeCacheOverflow(p->pCsr);
  70751. sqlite3BtreeLeaveCursor(p->pCsr);
  70752. }
  70753. }
  70754. if( rc==SQLITE_ROW ){
  70755. rc = SQLITE_OK;
  70756. }else if( p->pStmt ){
  70757. rc = sqlite3_finalize(p->pStmt);
  70758. p->pStmt = 0;
  70759. if( rc==SQLITE_OK ){
  70760. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  70761. rc = SQLITE_ERROR;
  70762. }else{
  70763. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  70764. }
  70765. }
  70766. assert( rc!=SQLITE_OK || zErr==0 );
  70767. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  70768. *pzErr = zErr;
  70769. return rc;
  70770. }
  70771. /*
  70772. ** Open a blob handle.
  70773. */
  70774. SQLITE_API int sqlite3_blob_open(
  70775. sqlite3* db, /* The database connection */
  70776. const char *zDb, /* The attached database containing the blob */
  70777. const char *zTable, /* The table containing the blob */
  70778. const char *zColumn, /* The column containing the blob */
  70779. sqlite_int64 iRow, /* The row containing the glob */
  70780. int flags, /* True -> read/write access, false -> read-only */
  70781. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  70782. ){
  70783. int nAttempt = 0;
  70784. int iCol; /* Index of zColumn in row-record */
  70785. /* This VDBE program seeks a btree cursor to the identified
  70786. ** db/table/row entry. The reason for using a vdbe program instead
  70787. ** of writing code to use the b-tree layer directly is that the
  70788. ** vdbe program will take advantage of the various transaction,
  70789. ** locking and error handling infrastructure built into the vdbe.
  70790. **
  70791. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  70792. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  70793. ** uses it to implement the blob_read(), blob_write() and
  70794. ** blob_bytes() functions.
  70795. **
  70796. ** The sqlite3_blob_close() function finalizes the vdbe program,
  70797. ** which closes the b-tree cursor and (possibly) commits the
  70798. ** transaction.
  70799. */
  70800. static const VdbeOpList openBlob[] = {
  70801. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  70802. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  70803. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  70804. /* One of the following two instructions is replaced by an OP_Noop. */
  70805. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  70806. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  70807. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  70808. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  70809. {OP_Column, 0, 0, 1}, /* 7 */
  70810. {OP_ResultRow, 1, 0, 0}, /* 8 */
  70811. {OP_Goto, 0, 5, 0}, /* 9 */
  70812. {OP_Close, 0, 0, 0}, /* 10 */
  70813. {OP_Halt, 0, 0, 0}, /* 11 */
  70814. };
  70815. int rc = SQLITE_OK;
  70816. char *zErr = 0;
  70817. Table *pTab;
  70818. Parse *pParse = 0;
  70819. Incrblob *pBlob = 0;
  70820. flags = !!flags; /* flags = (flags ? 1 : 0); */
  70821. *ppBlob = 0;
  70822. sqlite3_mutex_enter(db->mutex);
  70823. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  70824. if( !pBlob ) goto blob_open_out;
  70825. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  70826. if( !pParse ) goto blob_open_out;
  70827. do {
  70828. memset(pParse, 0, sizeof(Parse));
  70829. pParse->db = db;
  70830. sqlite3DbFree(db, zErr);
  70831. zErr = 0;
  70832. sqlite3BtreeEnterAll(db);
  70833. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  70834. if( pTab && IsVirtual(pTab) ){
  70835. pTab = 0;
  70836. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  70837. }
  70838. #ifndef SQLITE_OMIT_VIEW
  70839. if( pTab && pTab->pSelect ){
  70840. pTab = 0;
  70841. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  70842. }
  70843. #endif
  70844. if( !pTab ){
  70845. if( pParse->zErrMsg ){
  70846. sqlite3DbFree(db, zErr);
  70847. zErr = pParse->zErrMsg;
  70848. pParse->zErrMsg = 0;
  70849. }
  70850. rc = SQLITE_ERROR;
  70851. sqlite3BtreeLeaveAll(db);
  70852. goto blob_open_out;
  70853. }
  70854. /* Now search pTab for the exact column. */
  70855. for(iCol=0; iCol<pTab->nCol; iCol++) {
  70856. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  70857. break;
  70858. }
  70859. }
  70860. if( iCol==pTab->nCol ){
  70861. sqlite3DbFree(db, zErr);
  70862. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  70863. rc = SQLITE_ERROR;
  70864. sqlite3BtreeLeaveAll(db);
  70865. goto blob_open_out;
  70866. }
  70867. /* If the value is being opened for writing, check that the
  70868. ** column is not indexed, and that it is not part of a foreign key.
  70869. ** It is against the rules to open a column to which either of these
  70870. ** descriptions applies for writing. */
  70871. if( flags ){
  70872. const char *zFault = 0;
  70873. Index *pIdx;
  70874. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70875. if( db->flags&SQLITE_ForeignKeys ){
  70876. /* Check that the column is not part of an FK child key definition. It
  70877. ** is not necessary to check if it is part of a parent key, as parent
  70878. ** key columns must be indexed. The check below will pick up this
  70879. ** case. */
  70880. FKey *pFKey;
  70881. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  70882. int j;
  70883. for(j=0; j<pFKey->nCol; j++){
  70884. if( pFKey->aCol[j].iFrom==iCol ){
  70885. zFault = "foreign key";
  70886. }
  70887. }
  70888. }
  70889. }
  70890. #endif
  70891. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70892. int j;
  70893. for(j=0; j<pIdx->nColumn; j++){
  70894. if( pIdx->aiColumn[j]==iCol ){
  70895. zFault = "indexed";
  70896. }
  70897. }
  70898. }
  70899. if( zFault ){
  70900. sqlite3DbFree(db, zErr);
  70901. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  70902. rc = SQLITE_ERROR;
  70903. sqlite3BtreeLeaveAll(db);
  70904. goto blob_open_out;
  70905. }
  70906. }
  70907. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  70908. assert( pBlob->pStmt || db->mallocFailed );
  70909. if( pBlob->pStmt ){
  70910. Vdbe *v = (Vdbe *)pBlob->pStmt;
  70911. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70912. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  70913. /* Configure the OP_Transaction */
  70914. sqlite3VdbeChangeP1(v, 0, iDb);
  70915. sqlite3VdbeChangeP2(v, 0, flags);
  70916. /* Configure the OP_VerifyCookie */
  70917. sqlite3VdbeChangeP1(v, 1, iDb);
  70918. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  70919. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  70920. /* Make sure a mutex is held on the table to be accessed */
  70921. sqlite3VdbeUsesBtree(v, iDb);
  70922. /* Configure the OP_TableLock instruction */
  70923. #ifdef SQLITE_OMIT_SHARED_CACHE
  70924. sqlite3VdbeChangeToNoop(v, 2);
  70925. #else
  70926. sqlite3VdbeChangeP1(v, 2, iDb);
  70927. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  70928. sqlite3VdbeChangeP3(v, 2, flags);
  70929. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  70930. #endif
  70931. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  70932. ** parameter of the other to pTab->tnum. */
  70933. sqlite3VdbeChangeToNoop(v, 4 - flags);
  70934. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  70935. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  70936. /* Configure the number of columns. Configure the cursor to
  70937. ** think that the table has one more column than it really
  70938. ** does. An OP_Column to retrieve this imaginary column will
  70939. ** always return an SQL NULL. This is useful because it means
  70940. ** we can invoke OP_Column to fill in the vdbe cursors type
  70941. ** and offset cache without causing any IO.
  70942. */
  70943. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  70944. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  70945. if( !db->mallocFailed ){
  70946. pParse->nVar = 1;
  70947. pParse->nMem = 1;
  70948. pParse->nTab = 1;
  70949. sqlite3VdbeMakeReady(v, pParse);
  70950. }
  70951. }
  70952. pBlob->flags = flags;
  70953. pBlob->iCol = iCol;
  70954. pBlob->db = db;
  70955. sqlite3BtreeLeaveAll(db);
  70956. if( db->mallocFailed ){
  70957. goto blob_open_out;
  70958. }
  70959. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  70960. rc = blobSeekToRow(pBlob, iRow, &zErr);
  70961. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  70962. blob_open_out:
  70963. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  70964. *ppBlob = (sqlite3_blob *)pBlob;
  70965. }else{
  70966. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  70967. sqlite3DbFree(db, pBlob);
  70968. }
  70969. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  70970. sqlite3DbFree(db, zErr);
  70971. sqlite3StackFree(db, pParse);
  70972. rc = sqlite3ApiExit(db, rc);
  70973. sqlite3_mutex_leave(db->mutex);
  70974. return rc;
  70975. }
  70976. /*
  70977. ** Close a blob handle that was previously created using
  70978. ** sqlite3_blob_open().
  70979. */
  70980. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  70981. Incrblob *p = (Incrblob *)pBlob;
  70982. int rc;
  70983. sqlite3 *db;
  70984. if( p ){
  70985. db = p->db;
  70986. sqlite3_mutex_enter(db->mutex);
  70987. rc = sqlite3_finalize(p->pStmt);
  70988. sqlite3DbFree(db, p);
  70989. sqlite3_mutex_leave(db->mutex);
  70990. }else{
  70991. rc = SQLITE_OK;
  70992. }
  70993. return rc;
  70994. }
  70995. /*
  70996. ** Perform a read or write operation on a blob
  70997. */
  70998. static int blobReadWrite(
  70999. sqlite3_blob *pBlob,
  71000. void *z,
  71001. int n,
  71002. int iOffset,
  71003. int (*xCall)(BtCursor*, u32, u32, void*)
  71004. ){
  71005. int rc;
  71006. Incrblob *p = (Incrblob *)pBlob;
  71007. Vdbe *v;
  71008. sqlite3 *db;
  71009. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71010. db = p->db;
  71011. sqlite3_mutex_enter(db->mutex);
  71012. v = (Vdbe*)p->pStmt;
  71013. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  71014. /* Request is out of range. Return a transient error. */
  71015. rc = SQLITE_ERROR;
  71016. sqlite3Error(db, SQLITE_ERROR, 0);
  71017. }else if( v==0 ){
  71018. /* If there is no statement handle, then the blob-handle has
  71019. ** already been invalidated. Return SQLITE_ABORT in this case.
  71020. */
  71021. rc = SQLITE_ABORT;
  71022. }else{
  71023. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  71024. ** returned, clean-up the statement handle.
  71025. */
  71026. assert( db == v->db );
  71027. sqlite3BtreeEnterCursor(p->pCsr);
  71028. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  71029. sqlite3BtreeLeaveCursor(p->pCsr);
  71030. if( rc==SQLITE_ABORT ){
  71031. sqlite3VdbeFinalize(v);
  71032. p->pStmt = 0;
  71033. }else{
  71034. db->errCode = rc;
  71035. v->rc = rc;
  71036. }
  71037. }
  71038. rc = sqlite3ApiExit(db, rc);
  71039. sqlite3_mutex_leave(db->mutex);
  71040. return rc;
  71041. }
  71042. /*
  71043. ** Read data from a blob handle.
  71044. */
  71045. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  71046. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  71047. }
  71048. /*
  71049. ** Write data to a blob handle.
  71050. */
  71051. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  71052. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  71053. }
  71054. /*
  71055. ** Query a blob handle for the size of the data.
  71056. **
  71057. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  71058. ** so no mutex is required for access.
  71059. */
  71060. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  71061. Incrblob *p = (Incrblob *)pBlob;
  71062. return (p && p->pStmt) ? p->nByte : 0;
  71063. }
  71064. /*
  71065. ** Move an existing blob handle to point to a different row of the same
  71066. ** database table.
  71067. **
  71068. ** If an error occurs, or if the specified row does not exist or does not
  71069. ** contain a blob or text value, then an error code is returned and the
  71070. ** database handle error code and message set. If this happens, then all
  71071. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  71072. ** immediately return SQLITE_ABORT.
  71073. */
  71074. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  71075. int rc;
  71076. Incrblob *p = (Incrblob *)pBlob;
  71077. sqlite3 *db;
  71078. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71079. db = p->db;
  71080. sqlite3_mutex_enter(db->mutex);
  71081. if( p->pStmt==0 ){
  71082. /* If there is no statement handle, then the blob-handle has
  71083. ** already been invalidated. Return SQLITE_ABORT in this case.
  71084. */
  71085. rc = SQLITE_ABORT;
  71086. }else{
  71087. char *zErr;
  71088. rc = blobSeekToRow(p, iRow, &zErr);
  71089. if( rc!=SQLITE_OK ){
  71090. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  71091. sqlite3DbFree(db, zErr);
  71092. }
  71093. assert( rc!=SQLITE_SCHEMA );
  71094. }
  71095. rc = sqlite3ApiExit(db, rc);
  71096. assert( rc==SQLITE_OK || p->pStmt==0 );
  71097. sqlite3_mutex_leave(db->mutex);
  71098. return rc;
  71099. }
  71100. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  71101. /************** End of vdbeblob.c ********************************************/
  71102. /************** Begin file vdbesort.c ****************************************/
  71103. /*
  71104. ** 2011 July 9
  71105. **
  71106. ** The author disclaims copyright to this source code. In place of
  71107. ** a legal notice, here is a blessing:
  71108. **
  71109. ** May you do good and not evil.
  71110. ** May you find forgiveness for yourself and forgive others.
  71111. ** May you share freely, never taking more than you give.
  71112. **
  71113. *************************************************************************
  71114. ** This file contains code for the VdbeSorter object, used in concert with
  71115. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  71116. ** example, by CREATE INDEX statements on tables too large to fit in main
  71117. ** memory).
  71118. */
  71119. typedef struct VdbeSorterIter VdbeSorterIter;
  71120. typedef struct SorterRecord SorterRecord;
  71121. typedef struct FileWriter FileWriter;
  71122. /*
  71123. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  71124. **
  71125. ** As keys are added to the sorter, they are written to disk in a series
  71126. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  71127. ** the same as the cache-size allowed for temporary databases. In order
  71128. ** to allow the caller to extract keys from the sorter in sorted order,
  71129. ** all PMAs currently stored on disk must be merged together. This comment
  71130. ** describes the data structure used to do so. The structure supports
  71131. ** merging any number of arrays in a single pass with no redundant comparison
  71132. ** operations.
  71133. **
  71134. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  71135. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  71136. ** the purposes of the paragraphs below, we assume that the array is actually
  71137. ** N elements in size, where N is the smallest power of 2 greater to or equal
  71138. ** to the number of iterators being merged. The extra aIter[] elements are
  71139. ** treated as if they are empty (always at EOF).
  71140. **
  71141. ** The aTree[] array is also N elements in size. The value of N is stored in
  71142. ** the VdbeSorter.nTree variable.
  71143. **
  71144. ** The final (N/2) elements of aTree[] contain the results of comparing
  71145. ** pairs of iterator keys together. Element i contains the result of
  71146. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  71147. ** aTree element is set to the index of it.
  71148. **
  71149. ** For the purposes of this comparison, EOF is considered greater than any
  71150. ** other key value. If the keys are equal (only possible with two EOF
  71151. ** values), it doesn't matter which index is stored.
  71152. **
  71153. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  71154. ** above contains the index of the smallest of each block of 4 iterators.
  71155. ** And so on. So that aTree[1] contains the index of the iterator that
  71156. ** currently points to the smallest key value. aTree[0] is unused.
  71157. **
  71158. ** Example:
  71159. **
  71160. ** aIter[0] -> Banana
  71161. ** aIter[1] -> Feijoa
  71162. ** aIter[2] -> Elderberry
  71163. ** aIter[3] -> Currant
  71164. ** aIter[4] -> Grapefruit
  71165. ** aIter[5] -> Apple
  71166. ** aIter[6] -> Durian
  71167. ** aIter[7] -> EOF
  71168. **
  71169. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  71170. **
  71171. ** The current element is "Apple" (the value of the key indicated by
  71172. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  71173. ** be advanced to the next key in its segment. Say the next key is
  71174. ** "Eggplant":
  71175. **
  71176. ** aIter[5] -> Eggplant
  71177. **
  71178. ** The contents of aTree[] are updated first by comparing the new iterator
  71179. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  71180. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  71181. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  71182. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  71183. ** so the value written into element 1 of the array is 0. As follows:
  71184. **
  71185. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  71186. **
  71187. ** In other words, each time we advance to the next sorter element, log2(N)
  71188. ** key comparison operations are required, where N is the number of segments
  71189. ** being merged (rounded up to the next power of 2).
  71190. */
  71191. struct VdbeSorter {
  71192. i64 iWriteOff; /* Current write offset within file pTemp1 */
  71193. i64 iReadOff; /* Current read offset within file pTemp1 */
  71194. int nInMemory; /* Current size of pRecord list as PMA */
  71195. int nTree; /* Used size of aTree/aIter (power of 2) */
  71196. int nPMA; /* Number of PMAs stored in pTemp1 */
  71197. int mnPmaSize; /* Minimum PMA size, in bytes */
  71198. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  71199. VdbeSorterIter *aIter; /* Array of iterators to merge */
  71200. int *aTree; /* Current state of incremental merge */
  71201. sqlite3_file *pTemp1; /* PMA file 1 */
  71202. SorterRecord *pRecord; /* Head of in-memory record list */
  71203. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  71204. };
  71205. /*
  71206. ** The following type is an iterator for a PMA. It caches the current key in
  71207. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  71208. */
  71209. struct VdbeSorterIter {
  71210. i64 iReadOff; /* Current read offset */
  71211. i64 iEof; /* 1 byte past EOF for this iterator */
  71212. int nAlloc; /* Bytes of space at aAlloc */
  71213. int nKey; /* Number of bytes in key */
  71214. sqlite3_file *pFile; /* File iterator is reading from */
  71215. u8 *aAlloc; /* Allocated space */
  71216. u8 *aKey; /* Pointer to current key */
  71217. u8 *aBuffer; /* Current read buffer */
  71218. int nBuffer; /* Size of read buffer in bytes */
  71219. };
  71220. /*
  71221. ** An instance of this structure is used to organize the stream of records
  71222. ** being written to files by the merge-sort code into aligned, page-sized
  71223. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  71224. ** faster on many operating systems.
  71225. */
  71226. struct FileWriter {
  71227. int eFWErr; /* Non-zero if in an error state */
  71228. u8 *aBuffer; /* Pointer to write buffer */
  71229. int nBuffer; /* Size of write buffer in bytes */
  71230. int iBufStart; /* First byte of buffer to write */
  71231. int iBufEnd; /* Last byte of buffer to write */
  71232. i64 iWriteOff; /* Offset of start of buffer in file */
  71233. sqlite3_file *pFile; /* File to write to */
  71234. };
  71235. /*
  71236. ** A structure to store a single record. All in-memory records are connected
  71237. ** together into a linked list headed at VdbeSorter.pRecord using the
  71238. ** SorterRecord.pNext pointer.
  71239. */
  71240. struct SorterRecord {
  71241. void *pVal;
  71242. int nVal;
  71243. SorterRecord *pNext;
  71244. };
  71245. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  71246. #define SORTER_MIN_WORKING 10
  71247. /* Maximum number of segments to merge in a single pass. */
  71248. #define SORTER_MAX_MERGE_COUNT 16
  71249. /*
  71250. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  71251. ** argument. All structure fields are set to zero before returning.
  71252. */
  71253. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  71254. sqlite3DbFree(db, pIter->aAlloc);
  71255. sqlite3DbFree(db, pIter->aBuffer);
  71256. memset(pIter, 0, sizeof(VdbeSorterIter));
  71257. }
  71258. /*
  71259. ** Read nByte bytes of data from the stream of data iterated by object p.
  71260. ** If successful, set *ppOut to point to a buffer containing the data
  71261. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  71262. ** error code.
  71263. **
  71264. ** The buffer indicated by *ppOut may only be considered valid until the
  71265. ** next call to this function.
  71266. */
  71267. static int vdbeSorterIterRead(
  71268. sqlite3 *db, /* Database handle (for malloc) */
  71269. VdbeSorterIter *p, /* Iterator */
  71270. int nByte, /* Bytes of data to read */
  71271. u8 **ppOut /* OUT: Pointer to buffer containing data */
  71272. ){
  71273. int iBuf; /* Offset within buffer to read from */
  71274. int nAvail; /* Bytes of data available in buffer */
  71275. assert( p->aBuffer );
  71276. /* If there is no more data to be read from the buffer, read the next
  71277. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  71278. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  71279. iBuf = p->iReadOff % p->nBuffer;
  71280. if( iBuf==0 ){
  71281. int nRead; /* Bytes to read from disk */
  71282. int rc; /* sqlite3OsRead() return code */
  71283. /* Determine how many bytes of data to read. */
  71284. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  71285. nRead = p->nBuffer;
  71286. }else{
  71287. nRead = (int)(p->iEof - p->iReadOff);
  71288. }
  71289. assert( nRead>0 );
  71290. /* Read data from the file. Return early if an error occurs. */
  71291. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  71292. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71293. if( rc!=SQLITE_OK ) return rc;
  71294. }
  71295. nAvail = p->nBuffer - iBuf;
  71296. if( nByte<=nAvail ){
  71297. /* The requested data is available in the in-memory buffer. In this
  71298. ** case there is no need to make a copy of the data, just return a
  71299. ** pointer into the buffer to the caller. */
  71300. *ppOut = &p->aBuffer[iBuf];
  71301. p->iReadOff += nByte;
  71302. }else{
  71303. /* The requested data is not all available in the in-memory buffer.
  71304. ** In this case, allocate space at p->aAlloc[] to copy the requested
  71305. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  71306. int nRem; /* Bytes remaining to copy */
  71307. /* Extend the p->aAlloc[] allocation if required. */
  71308. if( p->nAlloc<nByte ){
  71309. int nNew = p->nAlloc*2;
  71310. while( nByte>nNew ) nNew = nNew*2;
  71311. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  71312. if( !p->aAlloc ) return SQLITE_NOMEM;
  71313. p->nAlloc = nNew;
  71314. }
  71315. /* Copy as much data as is available in the buffer into the start of
  71316. ** p->aAlloc[]. */
  71317. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  71318. p->iReadOff += nAvail;
  71319. nRem = nByte - nAvail;
  71320. /* The following loop copies up to p->nBuffer bytes per iteration into
  71321. ** the p->aAlloc[] buffer. */
  71322. while( nRem>0 ){
  71323. int rc; /* vdbeSorterIterRead() return code */
  71324. int nCopy; /* Number of bytes to copy */
  71325. u8 *aNext; /* Pointer to buffer to copy data from */
  71326. nCopy = nRem;
  71327. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  71328. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  71329. if( rc!=SQLITE_OK ) return rc;
  71330. assert( aNext!=p->aAlloc );
  71331. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  71332. nRem -= nCopy;
  71333. }
  71334. *ppOut = p->aAlloc;
  71335. }
  71336. return SQLITE_OK;
  71337. }
  71338. /*
  71339. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  71340. ** the value read.
  71341. */
  71342. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  71343. int iBuf;
  71344. iBuf = p->iReadOff % p->nBuffer;
  71345. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  71346. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  71347. }else{
  71348. u8 aVarint[16], *a;
  71349. int i = 0, rc;
  71350. do{
  71351. rc = vdbeSorterIterRead(db, p, 1, &a);
  71352. if( rc ) return rc;
  71353. aVarint[(i++)&0xf] = a[0];
  71354. }while( (a[0]&0x80)!=0 );
  71355. sqlite3GetVarint(aVarint, pnOut);
  71356. }
  71357. return SQLITE_OK;
  71358. }
  71359. /*
  71360. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  71361. ** no error occurs, or an SQLite error code if one does.
  71362. */
  71363. static int vdbeSorterIterNext(
  71364. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  71365. VdbeSorterIter *pIter /* Iterator to advance */
  71366. ){
  71367. int rc; /* Return Code */
  71368. u64 nRec = 0; /* Size of record in bytes */
  71369. if( pIter->iReadOff>=pIter->iEof ){
  71370. /* This is an EOF condition */
  71371. vdbeSorterIterZero(db, pIter);
  71372. return SQLITE_OK;
  71373. }
  71374. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  71375. if( rc==SQLITE_OK ){
  71376. pIter->nKey = (int)nRec;
  71377. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  71378. }
  71379. return rc;
  71380. }
  71381. /*
  71382. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  71383. ** starting at offset iStart and ending at offset iEof-1. This function
  71384. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  71385. ** PMA is empty).
  71386. */
  71387. static int vdbeSorterIterInit(
  71388. sqlite3 *db, /* Database handle */
  71389. const VdbeSorter *pSorter, /* Sorter object */
  71390. i64 iStart, /* Start offset in pFile */
  71391. VdbeSorterIter *pIter, /* Iterator to populate */
  71392. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  71393. ){
  71394. int rc = SQLITE_OK;
  71395. int nBuf;
  71396. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71397. assert( pSorter->iWriteOff>iStart );
  71398. assert( pIter->aAlloc==0 );
  71399. assert( pIter->aBuffer==0 );
  71400. pIter->pFile = pSorter->pTemp1;
  71401. pIter->iReadOff = iStart;
  71402. pIter->nAlloc = 128;
  71403. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  71404. pIter->nBuffer = nBuf;
  71405. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  71406. if( !pIter->aBuffer ){
  71407. rc = SQLITE_NOMEM;
  71408. }else{
  71409. int iBuf;
  71410. iBuf = iStart % nBuf;
  71411. if( iBuf ){
  71412. int nRead = nBuf - iBuf;
  71413. if( (iStart + nRead) > pSorter->iWriteOff ){
  71414. nRead = (int)(pSorter->iWriteOff - iStart);
  71415. }
  71416. rc = sqlite3OsRead(
  71417. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  71418. );
  71419. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71420. }
  71421. if( rc==SQLITE_OK ){
  71422. u64 nByte; /* Size of PMA in bytes */
  71423. pIter->iEof = pSorter->iWriteOff;
  71424. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  71425. pIter->iEof = pIter->iReadOff + nByte;
  71426. *pnByte += nByte;
  71427. }
  71428. }
  71429. if( rc==SQLITE_OK ){
  71430. rc = vdbeSorterIterNext(db, pIter);
  71431. }
  71432. return rc;
  71433. }
  71434. /*
  71435. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  71436. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  71437. ** used by the comparison. If an error occurs, return an SQLite error code.
  71438. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  71439. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  71440. **
  71441. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  71442. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  71443. ** is true and key1 contains even a single NULL value, it is considered to
  71444. ** be less than key2. Even if key2 also contains NULL values.
  71445. **
  71446. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  71447. ** has been allocated and contains an unpacked record that is used as key2.
  71448. */
  71449. static void vdbeSorterCompare(
  71450. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  71451. int bOmitRowid, /* Ignore rowid field at end of keys */
  71452. const void *pKey1, int nKey1, /* Left side of comparison */
  71453. const void *pKey2, int nKey2, /* Right side of comparison */
  71454. int *pRes /* OUT: Result of comparison */
  71455. ){
  71456. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  71457. VdbeSorter *pSorter = pCsr->pSorter;
  71458. UnpackedRecord *r2 = pSorter->pUnpacked;
  71459. int i;
  71460. if( pKey2 ){
  71461. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  71462. }
  71463. if( bOmitRowid ){
  71464. r2->nField = pKeyInfo->nField;
  71465. assert( r2->nField>0 );
  71466. for(i=0; i<r2->nField; i++){
  71467. if( r2->aMem[i].flags & MEM_Null ){
  71468. *pRes = -1;
  71469. return;
  71470. }
  71471. }
  71472. r2->flags |= UNPACKED_PREFIX_MATCH;
  71473. }
  71474. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  71475. }
  71476. /*
  71477. ** This function is called to compare two iterator keys when merging
  71478. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  71479. ** value to recalculate.
  71480. */
  71481. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  71482. VdbeSorter *pSorter = pCsr->pSorter;
  71483. int i1;
  71484. int i2;
  71485. int iRes;
  71486. VdbeSorterIter *p1;
  71487. VdbeSorterIter *p2;
  71488. assert( iOut<pSorter->nTree && iOut>0 );
  71489. if( iOut>=(pSorter->nTree/2) ){
  71490. i1 = (iOut - pSorter->nTree/2) * 2;
  71491. i2 = i1 + 1;
  71492. }else{
  71493. i1 = pSorter->aTree[iOut*2];
  71494. i2 = pSorter->aTree[iOut*2+1];
  71495. }
  71496. p1 = &pSorter->aIter[i1];
  71497. p2 = &pSorter->aIter[i2];
  71498. if( p1->pFile==0 ){
  71499. iRes = i2;
  71500. }else if( p2->pFile==0 ){
  71501. iRes = i1;
  71502. }else{
  71503. int res;
  71504. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  71505. vdbeSorterCompare(
  71506. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  71507. );
  71508. if( res<=0 ){
  71509. iRes = i1;
  71510. }else{
  71511. iRes = i2;
  71512. }
  71513. }
  71514. pSorter->aTree[iOut] = iRes;
  71515. return SQLITE_OK;
  71516. }
  71517. /*
  71518. ** Initialize the temporary index cursor just opened as a sorter cursor.
  71519. */
  71520. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  71521. int pgsz; /* Page size of main database */
  71522. int mxCache; /* Cache size */
  71523. VdbeSorter *pSorter; /* The new sorter */
  71524. char *d; /* Dummy */
  71525. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  71526. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  71527. if( pSorter==0 ){
  71528. return SQLITE_NOMEM;
  71529. }
  71530. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  71531. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  71532. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  71533. if( !sqlite3TempInMemory(db) ){
  71534. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71535. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  71536. mxCache = db->aDb[0].pSchema->cache_size;
  71537. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  71538. pSorter->mxPmaSize = mxCache * pgsz;
  71539. }
  71540. return SQLITE_OK;
  71541. }
  71542. /*
  71543. ** Free the list of sorted records starting at pRecord.
  71544. */
  71545. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  71546. SorterRecord *p;
  71547. SorterRecord *pNext;
  71548. for(p=pRecord; p; p=pNext){
  71549. pNext = p->pNext;
  71550. sqlite3DbFree(db, p);
  71551. }
  71552. }
  71553. /*
  71554. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  71555. */
  71556. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  71557. VdbeSorter *pSorter = pCsr->pSorter;
  71558. if( pSorter ){
  71559. if( pSorter->aIter ){
  71560. int i;
  71561. for(i=0; i<pSorter->nTree; i++){
  71562. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  71563. }
  71564. sqlite3DbFree(db, pSorter->aIter);
  71565. }
  71566. if( pSorter->pTemp1 ){
  71567. sqlite3OsCloseFree(pSorter->pTemp1);
  71568. }
  71569. vdbeSorterRecordFree(db, pSorter->pRecord);
  71570. sqlite3DbFree(db, pSorter->pUnpacked);
  71571. sqlite3DbFree(db, pSorter);
  71572. pCsr->pSorter = 0;
  71573. }
  71574. }
  71575. /*
  71576. ** Allocate space for a file-handle and open a temporary file. If successful,
  71577. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  71578. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  71579. */
  71580. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  71581. int dummy;
  71582. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  71583. SQLITE_OPEN_TEMP_JOURNAL |
  71584. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  71585. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  71586. );
  71587. }
  71588. /*
  71589. ** Merge the two sorted lists p1 and p2 into a single list.
  71590. ** Set *ppOut to the head of the new list.
  71591. */
  71592. static void vdbeSorterMerge(
  71593. const VdbeCursor *pCsr, /* For pKeyInfo */
  71594. SorterRecord *p1, /* First list to merge */
  71595. SorterRecord *p2, /* Second list to merge */
  71596. SorterRecord **ppOut /* OUT: Head of merged list */
  71597. ){
  71598. SorterRecord *pFinal = 0;
  71599. SorterRecord **pp = &pFinal;
  71600. void *pVal2 = p2 ? p2->pVal : 0;
  71601. while( p1 && p2 ){
  71602. int res;
  71603. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  71604. if( res<=0 ){
  71605. *pp = p1;
  71606. pp = &p1->pNext;
  71607. p1 = p1->pNext;
  71608. pVal2 = 0;
  71609. }else{
  71610. *pp = p2;
  71611. pp = &p2->pNext;
  71612. p2 = p2->pNext;
  71613. if( p2==0 ) break;
  71614. pVal2 = p2->pVal;
  71615. }
  71616. }
  71617. *pp = p1 ? p1 : p2;
  71618. *ppOut = pFinal;
  71619. }
  71620. /*
  71621. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  71622. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  71623. ** occurs.
  71624. */
  71625. static int vdbeSorterSort(const VdbeCursor *pCsr){
  71626. int i;
  71627. SorterRecord **aSlot;
  71628. SorterRecord *p;
  71629. VdbeSorter *pSorter = pCsr->pSorter;
  71630. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  71631. if( !aSlot ){
  71632. return SQLITE_NOMEM;
  71633. }
  71634. p = pSorter->pRecord;
  71635. while( p ){
  71636. SorterRecord *pNext = p->pNext;
  71637. p->pNext = 0;
  71638. for(i=0; aSlot[i]; i++){
  71639. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  71640. aSlot[i] = 0;
  71641. }
  71642. aSlot[i] = p;
  71643. p = pNext;
  71644. }
  71645. p = 0;
  71646. for(i=0; i<64; i++){
  71647. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  71648. }
  71649. pSorter->pRecord = p;
  71650. sqlite3_free(aSlot);
  71651. return SQLITE_OK;
  71652. }
  71653. /*
  71654. ** Initialize a file-writer object.
  71655. */
  71656. static void fileWriterInit(
  71657. sqlite3 *db, /* Database (for malloc) */
  71658. sqlite3_file *pFile, /* File to write to */
  71659. FileWriter *p, /* Object to populate */
  71660. i64 iStart /* Offset of pFile to begin writing at */
  71661. ){
  71662. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71663. memset(p, 0, sizeof(FileWriter));
  71664. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  71665. if( !p->aBuffer ){
  71666. p->eFWErr = SQLITE_NOMEM;
  71667. }else{
  71668. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  71669. p->iWriteOff = iStart - p->iBufStart;
  71670. p->nBuffer = nBuf;
  71671. p->pFile = pFile;
  71672. }
  71673. }
  71674. /*
  71675. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  71676. ** if successful, or an SQLite error code if an error occurs.
  71677. */
  71678. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  71679. int nRem = nData;
  71680. while( nRem>0 && p->eFWErr==0 ){
  71681. int nCopy = nRem;
  71682. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  71683. nCopy = p->nBuffer - p->iBufEnd;
  71684. }
  71685. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  71686. p->iBufEnd += nCopy;
  71687. if( p->iBufEnd==p->nBuffer ){
  71688. p->eFWErr = sqlite3OsWrite(p->pFile,
  71689. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  71690. p->iWriteOff + p->iBufStart
  71691. );
  71692. p->iBufStart = p->iBufEnd = 0;
  71693. p->iWriteOff += p->nBuffer;
  71694. }
  71695. assert( p->iBufEnd<p->nBuffer );
  71696. nRem -= nCopy;
  71697. }
  71698. }
  71699. /*
  71700. ** Flush any buffered data to disk and clean up the file-writer object.
  71701. ** The results of using the file-writer after this call are undefined.
  71702. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  71703. ** required. Otherwise, return an SQLite error code.
  71704. **
  71705. ** Before returning, set *piEof to the offset immediately following the
  71706. ** last byte written to the file.
  71707. */
  71708. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  71709. int rc;
  71710. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  71711. p->eFWErr = sqlite3OsWrite(p->pFile,
  71712. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  71713. p->iWriteOff + p->iBufStart
  71714. );
  71715. }
  71716. *piEof = (p->iWriteOff + p->iBufEnd);
  71717. sqlite3DbFree(db, p->aBuffer);
  71718. rc = p->eFWErr;
  71719. memset(p, 0, sizeof(FileWriter));
  71720. return rc;
  71721. }
  71722. /*
  71723. ** Write value iVal encoded as a varint to the file-write object. Return
  71724. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  71725. */
  71726. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  71727. int nByte;
  71728. u8 aByte[10];
  71729. nByte = sqlite3PutVarint(aByte, iVal);
  71730. fileWriterWrite(p, aByte, nByte);
  71731. }
  71732. /*
  71733. ** Write the current contents of the in-memory linked-list to a PMA. Return
  71734. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  71735. **
  71736. ** The format of a PMA is:
  71737. **
  71738. ** * A varint. This varint contains the total number of bytes of content
  71739. ** in the PMA (not including the varint itself).
  71740. **
  71741. ** * One or more records packed end-to-end in order of ascending keys.
  71742. ** Each record consists of a varint followed by a blob of data (the
  71743. ** key). The varint is the number of bytes in the blob of data.
  71744. */
  71745. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  71746. int rc = SQLITE_OK; /* Return code */
  71747. VdbeSorter *pSorter = pCsr->pSorter;
  71748. FileWriter writer;
  71749. memset(&writer, 0, sizeof(FileWriter));
  71750. if( pSorter->nInMemory==0 ){
  71751. assert( pSorter->pRecord==0 );
  71752. return rc;
  71753. }
  71754. rc = vdbeSorterSort(pCsr);
  71755. /* If the first temporary PMA file has not been opened, open it now. */
  71756. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  71757. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  71758. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  71759. assert( pSorter->iWriteOff==0 );
  71760. assert( pSorter->nPMA==0 );
  71761. }
  71762. if( rc==SQLITE_OK ){
  71763. SorterRecord *p;
  71764. SorterRecord *pNext = 0;
  71765. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  71766. pSorter->nPMA++;
  71767. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  71768. for(p=pSorter->pRecord; p; p=pNext){
  71769. pNext = p->pNext;
  71770. fileWriterWriteVarint(&writer, p->nVal);
  71771. fileWriterWrite(&writer, p->pVal, p->nVal);
  71772. sqlite3DbFree(db, p);
  71773. }
  71774. pSorter->pRecord = p;
  71775. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  71776. }
  71777. return rc;
  71778. }
  71779. /*
  71780. ** Add a record to the sorter.
  71781. */
  71782. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  71783. sqlite3 *db, /* Database handle */
  71784. const VdbeCursor *pCsr, /* Sorter cursor */
  71785. Mem *pVal /* Memory cell containing record */
  71786. ){
  71787. VdbeSorter *pSorter = pCsr->pSorter;
  71788. int rc = SQLITE_OK; /* Return Code */
  71789. SorterRecord *pNew; /* New list element */
  71790. assert( pSorter );
  71791. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  71792. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  71793. if( pNew==0 ){
  71794. rc = SQLITE_NOMEM;
  71795. }else{
  71796. pNew->pVal = (void *)&pNew[1];
  71797. memcpy(pNew->pVal, pVal->z, pVal->n);
  71798. pNew->nVal = pVal->n;
  71799. pNew->pNext = pSorter->pRecord;
  71800. pSorter->pRecord = pNew;
  71801. }
  71802. /* See if the contents of the sorter should now be written out. They
  71803. ** are written out when either of the following are true:
  71804. **
  71805. ** * The total memory allocated for the in-memory list is greater
  71806. ** than (page-size * cache-size), or
  71807. **
  71808. ** * The total memory allocated for the in-memory list is greater
  71809. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  71810. */
  71811. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  71812. (pSorter->nInMemory>pSorter->mxPmaSize)
  71813. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  71814. )){
  71815. #ifdef SQLITE_DEBUG
  71816. i64 nExpect = pSorter->iWriteOff
  71817. + sqlite3VarintLen(pSorter->nInMemory)
  71818. + pSorter->nInMemory;
  71819. #endif
  71820. rc = vdbeSorterListToPMA(db, pCsr);
  71821. pSorter->nInMemory = 0;
  71822. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  71823. }
  71824. return rc;
  71825. }
  71826. /*
  71827. ** Helper function for sqlite3VdbeSorterRewind().
  71828. */
  71829. static int vdbeSorterInitMerge(
  71830. sqlite3 *db, /* Database handle */
  71831. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  71832. i64 *pnByte /* Sum of bytes in all opened PMAs */
  71833. ){
  71834. VdbeSorter *pSorter = pCsr->pSorter;
  71835. int rc = SQLITE_OK; /* Return code */
  71836. int i; /* Used to iterator through aIter[] */
  71837. i64 nByte = 0; /* Total bytes in all opened PMAs */
  71838. /* Initialize the iterators. */
  71839. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  71840. VdbeSorterIter *pIter = &pSorter->aIter[i];
  71841. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  71842. pSorter->iReadOff = pIter->iEof;
  71843. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  71844. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  71845. }
  71846. /* Initialize the aTree[] array. */
  71847. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  71848. rc = vdbeSorterDoCompare(pCsr, i);
  71849. }
  71850. *pnByte = nByte;
  71851. return rc;
  71852. }
  71853. /*
  71854. ** Once the sorter has been populated, this function is called to prepare
  71855. ** for iterating through its contents in sorted order.
  71856. */
  71857. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  71858. VdbeSorter *pSorter = pCsr->pSorter;
  71859. int rc; /* Return code */
  71860. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  71861. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  71862. int nIter; /* Number of iterators used */
  71863. int nByte; /* Bytes of space required for aIter/aTree */
  71864. int N = 2; /* Power of 2 >= nIter */
  71865. assert( pSorter );
  71866. /* If no data has been written to disk, then do not do so now. Instead,
  71867. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  71868. ** from the in-memory list. */
  71869. if( pSorter->nPMA==0 ){
  71870. *pbEof = !pSorter->pRecord;
  71871. assert( pSorter->aTree==0 );
  71872. return vdbeSorterSort(pCsr);
  71873. }
  71874. /* Write the current in-memory list to a PMA. */
  71875. rc = vdbeSorterListToPMA(db, pCsr);
  71876. if( rc!=SQLITE_OK ) return rc;
  71877. /* Allocate space for aIter[] and aTree[]. */
  71878. nIter = pSorter->nPMA;
  71879. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  71880. assert( nIter>0 );
  71881. while( N<nIter ) N += N;
  71882. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  71883. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  71884. if( !pSorter->aIter ) return SQLITE_NOMEM;
  71885. pSorter->aTree = (int *)&pSorter->aIter[N];
  71886. pSorter->nTree = N;
  71887. do {
  71888. int iNew; /* Index of new, merged, PMA */
  71889. for(iNew=0;
  71890. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  71891. iNew++
  71892. ){
  71893. int rc2; /* Return code from fileWriterFinish() */
  71894. FileWriter writer; /* Object used to write to disk */
  71895. i64 nWrite; /* Number of bytes in new PMA */
  71896. memset(&writer, 0, sizeof(FileWriter));
  71897. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  71898. ** initialize an iterator for each of them and break out of the loop.
  71899. ** These iterators will be incrementally merged as the VDBE layer calls
  71900. ** sqlite3VdbeSorterNext().
  71901. **
  71902. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  71903. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  71904. ** are merged into a single PMA that is written to file pTemp2.
  71905. */
  71906. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  71907. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  71908. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  71909. break;
  71910. }
  71911. /* Open the second temp file, if it is not already open. */
  71912. if( pTemp2==0 ){
  71913. assert( iWrite2==0 );
  71914. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  71915. }
  71916. if( rc==SQLITE_OK ){
  71917. int bEof = 0;
  71918. fileWriterInit(db, pTemp2, &writer, iWrite2);
  71919. fileWriterWriteVarint(&writer, nWrite);
  71920. while( rc==SQLITE_OK && bEof==0 ){
  71921. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  71922. assert( pIter->pFile );
  71923. fileWriterWriteVarint(&writer, pIter->nKey);
  71924. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  71925. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  71926. }
  71927. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  71928. if( rc==SQLITE_OK ) rc = rc2;
  71929. }
  71930. }
  71931. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  71932. break;
  71933. }else{
  71934. sqlite3_file *pTmp = pSorter->pTemp1;
  71935. pSorter->nPMA = iNew;
  71936. pSorter->pTemp1 = pTemp2;
  71937. pTemp2 = pTmp;
  71938. pSorter->iWriteOff = iWrite2;
  71939. pSorter->iReadOff = 0;
  71940. iWrite2 = 0;
  71941. }
  71942. }while( rc==SQLITE_OK );
  71943. if( pTemp2 ){
  71944. sqlite3OsCloseFree(pTemp2);
  71945. }
  71946. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  71947. return rc;
  71948. }
  71949. /*
  71950. ** Advance to the next element in the sorter.
  71951. */
  71952. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  71953. VdbeSorter *pSorter = pCsr->pSorter;
  71954. int rc; /* Return code */
  71955. if( pSorter->aTree ){
  71956. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  71957. int i; /* Index of aTree[] to recalculate */
  71958. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  71959. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  71960. rc = vdbeSorterDoCompare(pCsr, i);
  71961. }
  71962. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  71963. }else{
  71964. SorterRecord *pFree = pSorter->pRecord;
  71965. pSorter->pRecord = pFree->pNext;
  71966. pFree->pNext = 0;
  71967. vdbeSorterRecordFree(db, pFree);
  71968. *pbEof = !pSorter->pRecord;
  71969. rc = SQLITE_OK;
  71970. }
  71971. return rc;
  71972. }
  71973. /*
  71974. ** Return a pointer to a buffer owned by the sorter that contains the
  71975. ** current key.
  71976. */
  71977. static void *vdbeSorterRowkey(
  71978. const VdbeSorter *pSorter, /* Sorter object */
  71979. int *pnKey /* OUT: Size of current key in bytes */
  71980. ){
  71981. void *pKey;
  71982. if( pSorter->aTree ){
  71983. VdbeSorterIter *pIter;
  71984. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  71985. *pnKey = pIter->nKey;
  71986. pKey = pIter->aKey;
  71987. }else{
  71988. *pnKey = pSorter->pRecord->nVal;
  71989. pKey = pSorter->pRecord->pVal;
  71990. }
  71991. return pKey;
  71992. }
  71993. /*
  71994. ** Copy the current sorter key into the memory cell pOut.
  71995. */
  71996. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  71997. VdbeSorter *pSorter = pCsr->pSorter;
  71998. void *pKey; int nKey; /* Sorter key to copy into pOut */
  71999. pKey = vdbeSorterRowkey(pSorter, &nKey);
  72000. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  72001. return SQLITE_NOMEM;
  72002. }
  72003. pOut->n = nKey;
  72004. MemSetTypeFlag(pOut, MEM_Blob);
  72005. memcpy(pOut->z, pKey, nKey);
  72006. return SQLITE_OK;
  72007. }
  72008. /*
  72009. ** Compare the key in memory cell pVal with the key that the sorter cursor
  72010. ** passed as the first argument currently points to. For the purposes of
  72011. ** the comparison, ignore the rowid field at the end of each record.
  72012. **
  72013. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  72014. ** Otherwise, set *pRes to a negative, zero or positive value if the
  72015. ** key in pVal is smaller than, equal to or larger than the current sorter
  72016. ** key.
  72017. */
  72018. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  72019. const VdbeCursor *pCsr, /* Sorter cursor */
  72020. Mem *pVal, /* Value to compare to current sorter key */
  72021. int *pRes /* OUT: Result of comparison */
  72022. ){
  72023. VdbeSorter *pSorter = pCsr->pSorter;
  72024. void *pKey; int nKey; /* Sorter key to compare pVal with */
  72025. pKey = vdbeSorterRowkey(pSorter, &nKey);
  72026. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  72027. return SQLITE_OK;
  72028. }
  72029. /************** End of vdbesort.c ********************************************/
  72030. /************** Begin file journal.c *****************************************/
  72031. /*
  72032. ** 2007 August 22
  72033. **
  72034. ** The author disclaims copyright to this source code. In place of
  72035. ** a legal notice, here is a blessing:
  72036. **
  72037. ** May you do good and not evil.
  72038. ** May you find forgiveness for yourself and forgive others.
  72039. ** May you share freely, never taking more than you give.
  72040. **
  72041. *************************************************************************
  72042. **
  72043. ** This file implements a special kind of sqlite3_file object used
  72044. ** by SQLite to create journal files if the atomic-write optimization
  72045. ** is enabled.
  72046. **
  72047. ** The distinctive characteristic of this sqlite3_file is that the
  72048. ** actual on disk file is created lazily. When the file is created,
  72049. ** the caller specifies a buffer size for an in-memory buffer to
  72050. ** be used to service read() and write() requests. The actual file
  72051. ** on disk is not created or populated until either:
  72052. **
  72053. ** 1) The in-memory representation grows too large for the allocated
  72054. ** buffer, or
  72055. ** 2) The sqlite3JournalCreate() function is called.
  72056. */
  72057. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  72058. /*
  72059. ** A JournalFile object is a subclass of sqlite3_file used by
  72060. ** as an open file handle for journal files.
  72061. */
  72062. struct JournalFile {
  72063. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  72064. int nBuf; /* Size of zBuf[] in bytes */
  72065. char *zBuf; /* Space to buffer journal writes */
  72066. int iSize; /* Amount of zBuf[] currently used */
  72067. int flags; /* xOpen flags */
  72068. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  72069. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  72070. const char *zJournal; /* Name of the journal file */
  72071. };
  72072. typedef struct JournalFile JournalFile;
  72073. /*
  72074. ** If it does not already exists, create and populate the on-disk file
  72075. ** for JournalFile p.
  72076. */
  72077. static int createFile(JournalFile *p){
  72078. int rc = SQLITE_OK;
  72079. if( !p->pReal ){
  72080. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  72081. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  72082. if( rc==SQLITE_OK ){
  72083. p->pReal = pReal;
  72084. if( p->iSize>0 ){
  72085. assert(p->iSize<=p->nBuf);
  72086. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  72087. }
  72088. if( rc!=SQLITE_OK ){
  72089. /* If an error occurred while writing to the file, close it before
  72090. ** returning. This way, SQLite uses the in-memory journal data to
  72091. ** roll back changes made to the internal page-cache before this
  72092. ** function was called. */
  72093. sqlite3OsClose(pReal);
  72094. p->pReal = 0;
  72095. }
  72096. }
  72097. }
  72098. return rc;
  72099. }
  72100. /*
  72101. ** Close the file.
  72102. */
  72103. static int jrnlClose(sqlite3_file *pJfd){
  72104. JournalFile *p = (JournalFile *)pJfd;
  72105. if( p->pReal ){
  72106. sqlite3OsClose(p->pReal);
  72107. }
  72108. sqlite3_free(p->zBuf);
  72109. return SQLITE_OK;
  72110. }
  72111. /*
  72112. ** Read data from the file.
  72113. */
  72114. static int jrnlRead(
  72115. sqlite3_file *pJfd, /* The journal file from which to read */
  72116. void *zBuf, /* Put the results here */
  72117. int iAmt, /* Number of bytes to read */
  72118. sqlite_int64 iOfst /* Begin reading at this offset */
  72119. ){
  72120. int rc = SQLITE_OK;
  72121. JournalFile *p = (JournalFile *)pJfd;
  72122. if( p->pReal ){
  72123. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  72124. }else if( (iAmt+iOfst)>p->iSize ){
  72125. rc = SQLITE_IOERR_SHORT_READ;
  72126. }else{
  72127. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  72128. }
  72129. return rc;
  72130. }
  72131. /*
  72132. ** Write data to the file.
  72133. */
  72134. static int jrnlWrite(
  72135. sqlite3_file *pJfd, /* The journal file into which to write */
  72136. const void *zBuf, /* Take data to be written from here */
  72137. int iAmt, /* Number of bytes to write */
  72138. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  72139. ){
  72140. int rc = SQLITE_OK;
  72141. JournalFile *p = (JournalFile *)pJfd;
  72142. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  72143. rc = createFile(p);
  72144. }
  72145. if( rc==SQLITE_OK ){
  72146. if( p->pReal ){
  72147. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  72148. }else{
  72149. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  72150. if( p->iSize<(iOfst+iAmt) ){
  72151. p->iSize = (iOfst+iAmt);
  72152. }
  72153. }
  72154. }
  72155. return rc;
  72156. }
  72157. /*
  72158. ** Truncate the file.
  72159. */
  72160. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  72161. int rc = SQLITE_OK;
  72162. JournalFile *p = (JournalFile *)pJfd;
  72163. if( p->pReal ){
  72164. rc = sqlite3OsTruncate(p->pReal, size);
  72165. }else if( size<p->iSize ){
  72166. p->iSize = size;
  72167. }
  72168. return rc;
  72169. }
  72170. /*
  72171. ** Sync the file.
  72172. */
  72173. static int jrnlSync(sqlite3_file *pJfd, int flags){
  72174. int rc;
  72175. JournalFile *p = (JournalFile *)pJfd;
  72176. if( p->pReal ){
  72177. rc = sqlite3OsSync(p->pReal, flags);
  72178. }else{
  72179. rc = SQLITE_OK;
  72180. }
  72181. return rc;
  72182. }
  72183. /*
  72184. ** Query the size of the file in bytes.
  72185. */
  72186. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  72187. int rc = SQLITE_OK;
  72188. JournalFile *p = (JournalFile *)pJfd;
  72189. if( p->pReal ){
  72190. rc = sqlite3OsFileSize(p->pReal, pSize);
  72191. }else{
  72192. *pSize = (sqlite_int64) p->iSize;
  72193. }
  72194. return rc;
  72195. }
  72196. /*
  72197. ** Table of methods for JournalFile sqlite3_file object.
  72198. */
  72199. static struct sqlite3_io_methods JournalFileMethods = {
  72200. 1, /* iVersion */
  72201. jrnlClose, /* xClose */
  72202. jrnlRead, /* xRead */
  72203. jrnlWrite, /* xWrite */
  72204. jrnlTruncate, /* xTruncate */
  72205. jrnlSync, /* xSync */
  72206. jrnlFileSize, /* xFileSize */
  72207. 0, /* xLock */
  72208. 0, /* xUnlock */
  72209. 0, /* xCheckReservedLock */
  72210. 0, /* xFileControl */
  72211. 0, /* xSectorSize */
  72212. 0, /* xDeviceCharacteristics */
  72213. 0, /* xShmMap */
  72214. 0, /* xShmLock */
  72215. 0, /* xShmBarrier */
  72216. 0 /* xShmUnmap */
  72217. };
  72218. /*
  72219. ** Open a journal file.
  72220. */
  72221. SQLITE_PRIVATE int sqlite3JournalOpen(
  72222. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  72223. const char *zName, /* Name of the journal file */
  72224. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  72225. int flags, /* Opening flags */
  72226. int nBuf /* Bytes buffered before opening the file */
  72227. ){
  72228. JournalFile *p = (JournalFile *)pJfd;
  72229. memset(p, 0, sqlite3JournalSize(pVfs));
  72230. if( nBuf>0 ){
  72231. p->zBuf = sqlite3MallocZero(nBuf);
  72232. if( !p->zBuf ){
  72233. return SQLITE_NOMEM;
  72234. }
  72235. }else{
  72236. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  72237. }
  72238. p->pMethod = &JournalFileMethods;
  72239. p->nBuf = nBuf;
  72240. p->flags = flags;
  72241. p->zJournal = zName;
  72242. p->pVfs = pVfs;
  72243. return SQLITE_OK;
  72244. }
  72245. /*
  72246. ** If the argument p points to a JournalFile structure, and the underlying
  72247. ** file has not yet been created, create it now.
  72248. */
  72249. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  72250. if( p->pMethods!=&JournalFileMethods ){
  72251. return SQLITE_OK;
  72252. }
  72253. return createFile((JournalFile *)p);
  72254. }
  72255. /*
  72256. ** The file-handle passed as the only argument is guaranteed to be an open
  72257. ** file. It may or may not be of class JournalFile. If the file is a
  72258. ** JournalFile, and the underlying file on disk has not yet been opened,
  72259. ** return 0. Otherwise, return 1.
  72260. */
  72261. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  72262. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  72263. }
  72264. /*
  72265. ** Return the number of bytes required to store a JournalFile that uses vfs
  72266. ** pVfs to create the underlying on-disk files.
  72267. */
  72268. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  72269. return (pVfs->szOsFile+sizeof(JournalFile));
  72270. }
  72271. #endif
  72272. /************** End of journal.c *********************************************/
  72273. /************** Begin file memjournal.c **************************************/
  72274. /*
  72275. ** 2008 October 7
  72276. **
  72277. ** The author disclaims copyright to this source code. In place of
  72278. ** a legal notice, here is a blessing:
  72279. **
  72280. ** May you do good and not evil.
  72281. ** May you find forgiveness for yourself and forgive others.
  72282. ** May you share freely, never taking more than you give.
  72283. **
  72284. *************************************************************************
  72285. **
  72286. ** This file contains code use to implement an in-memory rollback journal.
  72287. ** The in-memory rollback journal is used to journal transactions for
  72288. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  72289. */
  72290. /* Forward references to internal structures */
  72291. typedef struct MemJournal MemJournal;
  72292. typedef struct FilePoint FilePoint;
  72293. typedef struct FileChunk FileChunk;
  72294. /* Space to hold the rollback journal is allocated in increments of
  72295. ** this many bytes.
  72296. **
  72297. ** The size chosen is a little less than a power of two. That way,
  72298. ** the FileChunk object will have a size that almost exactly fills
  72299. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  72300. ** memory allocators.
  72301. */
  72302. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  72303. /*
  72304. ** The rollback journal is composed of a linked list of these structures.
  72305. */
  72306. struct FileChunk {
  72307. FileChunk *pNext; /* Next chunk in the journal */
  72308. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  72309. };
  72310. /*
  72311. ** An instance of this object serves as a cursor into the rollback journal.
  72312. ** The cursor can be either for reading or writing.
  72313. */
  72314. struct FilePoint {
  72315. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  72316. FileChunk *pChunk; /* Specific chunk into which cursor points */
  72317. };
  72318. /*
  72319. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  72320. ** is an instance of this class.
  72321. */
  72322. struct MemJournal {
  72323. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  72324. FileChunk *pFirst; /* Head of in-memory chunk-list */
  72325. FilePoint endpoint; /* Pointer to the end of the file */
  72326. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  72327. };
  72328. /*
  72329. ** Read data from the in-memory journal file. This is the implementation
  72330. ** of the sqlite3_vfs.xRead method.
  72331. */
  72332. static int memjrnlRead(
  72333. sqlite3_file *pJfd, /* The journal file from which to read */
  72334. void *zBuf, /* Put the results here */
  72335. int iAmt, /* Number of bytes to read */
  72336. sqlite_int64 iOfst /* Begin reading at this offset */
  72337. ){
  72338. MemJournal *p = (MemJournal *)pJfd;
  72339. u8 *zOut = zBuf;
  72340. int nRead = iAmt;
  72341. int iChunkOffset;
  72342. FileChunk *pChunk;
  72343. /* SQLite never tries to read past the end of a rollback journal file */
  72344. assert( iOfst+iAmt<=p->endpoint.iOffset );
  72345. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  72346. sqlite3_int64 iOff = 0;
  72347. for(pChunk=p->pFirst;
  72348. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  72349. pChunk=pChunk->pNext
  72350. ){
  72351. iOff += JOURNAL_CHUNKSIZE;
  72352. }
  72353. }else{
  72354. pChunk = p->readpoint.pChunk;
  72355. }
  72356. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  72357. do {
  72358. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  72359. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  72360. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  72361. zOut += nCopy;
  72362. nRead -= iSpace;
  72363. iChunkOffset = 0;
  72364. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  72365. p->readpoint.iOffset = iOfst+iAmt;
  72366. p->readpoint.pChunk = pChunk;
  72367. return SQLITE_OK;
  72368. }
  72369. /*
  72370. ** Write data to the file.
  72371. */
  72372. static int memjrnlWrite(
  72373. sqlite3_file *pJfd, /* The journal file into which to write */
  72374. const void *zBuf, /* Take data to be written from here */
  72375. int iAmt, /* Number of bytes to write */
  72376. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  72377. ){
  72378. MemJournal *p = (MemJournal *)pJfd;
  72379. int nWrite = iAmt;
  72380. u8 *zWrite = (u8 *)zBuf;
  72381. /* An in-memory journal file should only ever be appended to. Random
  72382. ** access writes are not required by sqlite.
  72383. */
  72384. assert( iOfst==p->endpoint.iOffset );
  72385. UNUSED_PARAMETER(iOfst);
  72386. while( nWrite>0 ){
  72387. FileChunk *pChunk = p->endpoint.pChunk;
  72388. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  72389. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  72390. if( iChunkOffset==0 ){
  72391. /* New chunk is required to extend the file. */
  72392. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  72393. if( !pNew ){
  72394. return SQLITE_IOERR_NOMEM;
  72395. }
  72396. pNew->pNext = 0;
  72397. if( pChunk ){
  72398. assert( p->pFirst );
  72399. pChunk->pNext = pNew;
  72400. }else{
  72401. assert( !p->pFirst );
  72402. p->pFirst = pNew;
  72403. }
  72404. p->endpoint.pChunk = pNew;
  72405. }
  72406. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  72407. zWrite += iSpace;
  72408. nWrite -= iSpace;
  72409. p->endpoint.iOffset += iSpace;
  72410. }
  72411. return SQLITE_OK;
  72412. }
  72413. /*
  72414. ** Truncate the file.
  72415. */
  72416. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  72417. MemJournal *p = (MemJournal *)pJfd;
  72418. FileChunk *pChunk;
  72419. assert(size==0);
  72420. UNUSED_PARAMETER(size);
  72421. pChunk = p->pFirst;
  72422. while( pChunk ){
  72423. FileChunk *pTmp = pChunk;
  72424. pChunk = pChunk->pNext;
  72425. sqlite3_free(pTmp);
  72426. }
  72427. sqlite3MemJournalOpen(pJfd);
  72428. return SQLITE_OK;
  72429. }
  72430. /*
  72431. ** Close the file.
  72432. */
  72433. static int memjrnlClose(sqlite3_file *pJfd){
  72434. memjrnlTruncate(pJfd, 0);
  72435. return SQLITE_OK;
  72436. }
  72437. /*
  72438. ** Sync the file.
  72439. **
  72440. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  72441. ** is never called in a working implementation. This implementation
  72442. ** exists purely as a contingency, in case some malfunction in some other
  72443. ** part of SQLite causes Sync to be called by mistake.
  72444. */
  72445. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  72446. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  72447. return SQLITE_OK;
  72448. }
  72449. /*
  72450. ** Query the size of the file in bytes.
  72451. */
  72452. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  72453. MemJournal *p = (MemJournal *)pJfd;
  72454. *pSize = (sqlite_int64) p->endpoint.iOffset;
  72455. return SQLITE_OK;
  72456. }
  72457. /*
  72458. ** Table of methods for MemJournal sqlite3_file object.
  72459. */
  72460. static const struct sqlite3_io_methods MemJournalMethods = {
  72461. 1, /* iVersion */
  72462. memjrnlClose, /* xClose */
  72463. memjrnlRead, /* xRead */
  72464. memjrnlWrite, /* xWrite */
  72465. memjrnlTruncate, /* xTruncate */
  72466. memjrnlSync, /* xSync */
  72467. memjrnlFileSize, /* xFileSize */
  72468. 0, /* xLock */
  72469. 0, /* xUnlock */
  72470. 0, /* xCheckReservedLock */
  72471. 0, /* xFileControl */
  72472. 0, /* xSectorSize */
  72473. 0, /* xDeviceCharacteristics */
  72474. 0, /* xShmMap */
  72475. 0, /* xShmLock */
  72476. 0, /* xShmBarrier */
  72477. 0, /* xShmUnmap */
  72478. 0, /* xFetch */
  72479. 0 /* xUnfetch */
  72480. };
  72481. /*
  72482. ** Open a journal file.
  72483. */
  72484. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  72485. MemJournal *p = (MemJournal *)pJfd;
  72486. assert( EIGHT_BYTE_ALIGNMENT(p) );
  72487. memset(p, 0, sqlite3MemJournalSize());
  72488. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  72489. }
  72490. /*
  72491. ** Return true if the file-handle passed as an argument is
  72492. ** an in-memory journal
  72493. */
  72494. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  72495. return pJfd->pMethods==&MemJournalMethods;
  72496. }
  72497. /*
  72498. ** Return the number of bytes required to store a MemJournal file descriptor.
  72499. */
  72500. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  72501. return sizeof(MemJournal);
  72502. }
  72503. /************** End of memjournal.c ******************************************/
  72504. /************** Begin file walker.c ******************************************/
  72505. /*
  72506. ** 2008 August 16
  72507. **
  72508. ** The author disclaims copyright to this source code. In place of
  72509. ** a legal notice, here is a blessing:
  72510. **
  72511. ** May you do good and not evil.
  72512. ** May you find forgiveness for yourself and forgive others.
  72513. ** May you share freely, never taking more than you give.
  72514. **
  72515. *************************************************************************
  72516. ** This file contains routines used for walking the parser tree for
  72517. ** an SQL statement.
  72518. */
  72519. /* #include <stdlib.h> */
  72520. /* #include <string.h> */
  72521. /*
  72522. ** Walk an expression tree. Invoke the callback once for each node
  72523. ** of the expression, while decending. (In other words, the callback
  72524. ** is invoked before visiting children.)
  72525. **
  72526. ** The return value from the callback should be one of the WRC_*
  72527. ** constants to specify how to proceed with the walk.
  72528. **
  72529. ** WRC_Continue Continue descending down the tree.
  72530. **
  72531. ** WRC_Prune Do not descend into child nodes. But allow
  72532. ** the walk to continue with sibling nodes.
  72533. **
  72534. ** WRC_Abort Do no more callbacks. Unwind the stack and
  72535. ** return the top-level walk call.
  72536. **
  72537. ** The return value from this routine is WRC_Abort to abandon the tree walk
  72538. ** and WRC_Continue to continue.
  72539. */
  72540. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  72541. int rc;
  72542. if( pExpr==0 ) return WRC_Continue;
  72543. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  72544. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  72545. rc = pWalker->xExprCallback(pWalker, pExpr);
  72546. if( rc==WRC_Continue
  72547. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  72548. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  72549. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  72550. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  72551. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  72552. }else{
  72553. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  72554. }
  72555. }
  72556. return rc & WRC_Abort;
  72557. }
  72558. /*
  72559. ** Call sqlite3WalkExpr() for every expression in list p or until
  72560. ** an abort request is seen.
  72561. */
  72562. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  72563. int i;
  72564. struct ExprList_item *pItem;
  72565. if( p ){
  72566. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  72567. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  72568. }
  72569. }
  72570. return WRC_Continue;
  72571. }
  72572. /*
  72573. ** Walk all expressions associated with SELECT statement p. Do
  72574. ** not invoke the SELECT callback on p, but do (of course) invoke
  72575. ** any expr callbacks and SELECT callbacks that come from subqueries.
  72576. ** Return WRC_Abort or WRC_Continue.
  72577. */
  72578. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  72579. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  72580. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  72581. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  72582. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  72583. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  72584. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  72585. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  72586. return WRC_Continue;
  72587. }
  72588. /*
  72589. ** Walk the parse trees associated with all subqueries in the
  72590. ** FROM clause of SELECT statement p. Do not invoke the select
  72591. ** callback on p, but do invoke it on each FROM clause subquery
  72592. ** and on any subqueries further down in the tree. Return
  72593. ** WRC_Abort or WRC_Continue;
  72594. */
  72595. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  72596. SrcList *pSrc;
  72597. int i;
  72598. struct SrcList_item *pItem;
  72599. pSrc = p->pSrc;
  72600. if( ALWAYS(pSrc) ){
  72601. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  72602. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  72603. return WRC_Abort;
  72604. }
  72605. }
  72606. }
  72607. return WRC_Continue;
  72608. }
  72609. /*
  72610. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  72611. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  72612. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  72613. ** either before or after the walk of expressions and FROM clause, depending
  72614. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  72615. **
  72616. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  72617. ** there is an abort request.
  72618. **
  72619. ** If the Walker does not have an xSelectCallback() then this routine
  72620. ** is a no-op returning WRC_Continue.
  72621. */
  72622. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  72623. int rc;
  72624. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  72625. rc = WRC_Continue;
  72626. pWalker->walkerDepth++;
  72627. while( p ){
  72628. if( !pWalker->bSelectDepthFirst ){
  72629. rc = pWalker->xSelectCallback(pWalker, p);
  72630. if( rc ) break;
  72631. }
  72632. if( sqlite3WalkSelectExpr(pWalker, p)
  72633. || sqlite3WalkSelectFrom(pWalker, p)
  72634. ){
  72635. pWalker->walkerDepth--;
  72636. return WRC_Abort;
  72637. }
  72638. if( pWalker->bSelectDepthFirst ){
  72639. rc = pWalker->xSelectCallback(pWalker, p);
  72640. /* Depth-first search is currently only used for
  72641. ** selectAddSubqueryTypeInfo() and that routine always returns
  72642. ** WRC_Continue (0). So the following branch is never taken. */
  72643. if( NEVER(rc) ) break;
  72644. }
  72645. p = p->pPrior;
  72646. }
  72647. pWalker->walkerDepth--;
  72648. return rc & WRC_Abort;
  72649. }
  72650. /************** End of walker.c **********************************************/
  72651. /************** Begin file resolve.c *****************************************/
  72652. /*
  72653. ** 2008 August 18
  72654. **
  72655. ** The author disclaims copyright to this source code. In place of
  72656. ** a legal notice, here is a blessing:
  72657. **
  72658. ** May you do good and not evil.
  72659. ** May you find forgiveness for yourself and forgive others.
  72660. ** May you share freely, never taking more than you give.
  72661. **
  72662. *************************************************************************
  72663. **
  72664. ** This file contains routines used for walking the parser tree and
  72665. ** resolve all identifiers by associating them with a particular
  72666. ** table and column.
  72667. */
  72668. /* #include <stdlib.h> */
  72669. /* #include <string.h> */
  72670. /*
  72671. ** Walk the expression tree pExpr and increase the aggregate function
  72672. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  72673. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  72674. ** outer query into an inner subquery.
  72675. **
  72676. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  72677. ** is a helper function - a callback for the tree walker.
  72678. */
  72679. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  72680. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  72681. return WRC_Continue;
  72682. }
  72683. static void incrAggFunctionDepth(Expr *pExpr, int N){
  72684. if( N>0 ){
  72685. Walker w;
  72686. memset(&w, 0, sizeof(w));
  72687. w.xExprCallback = incrAggDepth;
  72688. w.u.i = N;
  72689. sqlite3WalkExpr(&w, pExpr);
  72690. }
  72691. }
  72692. /*
  72693. ** Turn the pExpr expression into an alias for the iCol-th column of the
  72694. ** result set in pEList.
  72695. **
  72696. ** If the result set column is a simple column reference, then this routine
  72697. ** makes an exact copy. But for any other kind of expression, this
  72698. ** routine make a copy of the result set column as the argument to the
  72699. ** TK_AS operator. The TK_AS operator causes the expression to be
  72700. ** evaluated just once and then reused for each alias.
  72701. **
  72702. ** The reason for suppressing the TK_AS term when the expression is a simple
  72703. ** column reference is so that the column reference will be recognized as
  72704. ** usable by indices within the WHERE clause processing logic.
  72705. **
  72706. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  72707. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  72708. **
  72709. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  72710. **
  72711. ** Is equivalent to:
  72712. **
  72713. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  72714. **
  72715. ** The result of random()%5 in the GROUP BY clause is probably different
  72716. ** from the result in the result-set. On the other hand Standard SQL does
  72717. ** not allow the GROUP BY clause to contain references to result-set columns.
  72718. ** So this should never come up in well-formed queries.
  72719. **
  72720. ** If the reference is followed by a COLLATE operator, then make sure
  72721. ** the COLLATE operator is preserved. For example:
  72722. **
  72723. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  72724. **
  72725. ** Should be transformed into:
  72726. **
  72727. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  72728. **
  72729. ** The nSubquery parameter specifies how many levels of subquery the
  72730. ** alias is removed from the original expression. The usually value is
  72731. ** zero but it might be more if the alias is contained within a subquery
  72732. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  72733. ** structures must be increased by the nSubquery amount.
  72734. */
  72735. static void resolveAlias(
  72736. Parse *pParse, /* Parsing context */
  72737. ExprList *pEList, /* A result set */
  72738. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  72739. Expr *pExpr, /* Transform this into an alias to the result set */
  72740. const char *zType, /* "GROUP" or "ORDER" or "" */
  72741. int nSubquery /* Number of subqueries that the label is moving */
  72742. ){
  72743. Expr *pOrig; /* The iCol-th column of the result set */
  72744. Expr *pDup; /* Copy of pOrig */
  72745. sqlite3 *db; /* The database connection */
  72746. assert( iCol>=0 && iCol<pEList->nExpr );
  72747. pOrig = pEList->a[iCol].pExpr;
  72748. assert( pOrig!=0 );
  72749. assert( pOrig->flags & EP_Resolved );
  72750. db = pParse->db;
  72751. pDup = sqlite3ExprDup(db, pOrig, 0);
  72752. if( pDup==0 ) return;
  72753. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  72754. incrAggFunctionDepth(pDup, nSubquery);
  72755. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  72756. if( pDup==0 ) return;
  72757. ExprSetProperty(pDup, EP_Skip);
  72758. if( pEList->a[iCol].iAlias==0 ){
  72759. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  72760. }
  72761. pDup->iTable = pEList->a[iCol].iAlias;
  72762. }
  72763. if( pExpr->op==TK_COLLATE ){
  72764. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  72765. }
  72766. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  72767. ** prevents ExprDelete() from deleting the Expr structure itself,
  72768. ** allowing it to be repopulated by the memcpy() on the following line.
  72769. ** The pExpr->u.zToken might point into memory that will be freed by the
  72770. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  72771. ** make a copy of the token before doing the sqlite3DbFree().
  72772. */
  72773. ExprSetProperty(pExpr, EP_Static);
  72774. sqlite3ExprDelete(db, pExpr);
  72775. memcpy(pExpr, pDup, sizeof(*pExpr));
  72776. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  72777. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  72778. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  72779. pExpr->flags |= EP_MemToken;
  72780. }
  72781. sqlite3DbFree(db, pDup);
  72782. }
  72783. /*
  72784. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  72785. **
  72786. ** Return FALSE if the USING clause is NULL or if it does not contain
  72787. ** zCol.
  72788. */
  72789. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  72790. if( pUsing ){
  72791. int k;
  72792. for(k=0; k<pUsing->nId; k++){
  72793. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  72794. }
  72795. }
  72796. return 0;
  72797. }
  72798. /*
  72799. ** Subqueries stores the original database, table and column names for their
  72800. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  72801. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  72802. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  72803. ** match anything.
  72804. */
  72805. SQLITE_PRIVATE int sqlite3MatchSpanName(
  72806. const char *zSpan,
  72807. const char *zCol,
  72808. const char *zTab,
  72809. const char *zDb
  72810. ){
  72811. int n;
  72812. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  72813. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  72814. return 0;
  72815. }
  72816. zSpan += n+1;
  72817. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  72818. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  72819. return 0;
  72820. }
  72821. zSpan += n+1;
  72822. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  72823. return 0;
  72824. }
  72825. return 1;
  72826. }
  72827. /*
  72828. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  72829. ** that name in the set of source tables in pSrcList and make the pExpr
  72830. ** expression node refer back to that source column. The following changes
  72831. ** are made to pExpr:
  72832. **
  72833. ** pExpr->iDb Set the index in db->aDb[] of the database X
  72834. ** (even if X is implied).
  72835. ** pExpr->iTable Set to the cursor number for the table obtained
  72836. ** from pSrcList.
  72837. ** pExpr->pTab Points to the Table structure of X.Y (even if
  72838. ** X and/or Y are implied.)
  72839. ** pExpr->iColumn Set to the column number within the table.
  72840. ** pExpr->op Set to TK_COLUMN.
  72841. ** pExpr->pLeft Any expression this points to is deleted
  72842. ** pExpr->pRight Any expression this points to is deleted.
  72843. **
  72844. ** The zDb variable is the name of the database (the "X"). This value may be
  72845. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  72846. ** can be used. The zTable variable is the name of the table (the "Y"). This
  72847. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  72848. ** means that the form of the name is Z and that columns from any table
  72849. ** can be used.
  72850. **
  72851. ** If the name cannot be resolved unambiguously, leave an error message
  72852. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  72853. */
  72854. static int lookupName(
  72855. Parse *pParse, /* The parsing context */
  72856. const char *zDb, /* Name of the database containing table, or NULL */
  72857. const char *zTab, /* Name of table containing column, or NULL */
  72858. const char *zCol, /* Name of the column. */
  72859. NameContext *pNC, /* The name context used to resolve the name */
  72860. Expr *pExpr /* Make this EXPR node point to the selected column */
  72861. ){
  72862. int i, j; /* Loop counters */
  72863. int cnt = 0; /* Number of matching column names */
  72864. int cntTab = 0; /* Number of matching table names */
  72865. int nSubquery = 0; /* How many levels of subquery */
  72866. sqlite3 *db = pParse->db; /* The database connection */
  72867. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  72868. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  72869. NameContext *pTopNC = pNC; /* First namecontext in the list */
  72870. Schema *pSchema = 0; /* Schema of the expression */
  72871. int isTrigger = 0;
  72872. assert( pNC ); /* the name context cannot be NULL. */
  72873. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  72874. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  72875. /* Initialize the node to no-match */
  72876. pExpr->iTable = -1;
  72877. pExpr->pTab = 0;
  72878. ExprSetVVAProperty(pExpr, EP_NoReduce);
  72879. /* Translate the schema name in zDb into a pointer to the corresponding
  72880. ** schema. If not found, pSchema will remain NULL and nothing will match
  72881. ** resulting in an appropriate error message toward the end of this routine
  72882. */
  72883. if( zDb ){
  72884. testcase( pNC->ncFlags & NC_PartIdx );
  72885. testcase( pNC->ncFlags & NC_IsCheck );
  72886. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  72887. /* Silently ignore database qualifiers inside CHECK constraints and partial
  72888. ** indices. Do not raise errors because that might break legacy and
  72889. ** because it does not hurt anything to just ignore the database name. */
  72890. zDb = 0;
  72891. }else{
  72892. for(i=0; i<db->nDb; i++){
  72893. assert( db->aDb[i].zName );
  72894. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  72895. pSchema = db->aDb[i].pSchema;
  72896. break;
  72897. }
  72898. }
  72899. }
  72900. }
  72901. /* Start at the inner-most context and move outward until a match is found */
  72902. while( pNC && cnt==0 ){
  72903. ExprList *pEList;
  72904. SrcList *pSrcList = pNC->pSrcList;
  72905. if( pSrcList ){
  72906. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  72907. Table *pTab;
  72908. Column *pCol;
  72909. pTab = pItem->pTab;
  72910. assert( pTab!=0 && pTab->zName!=0 );
  72911. assert( pTab->nCol>0 );
  72912. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  72913. int hit = 0;
  72914. pEList = pItem->pSelect->pEList;
  72915. for(j=0; j<pEList->nExpr; j++){
  72916. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  72917. cnt++;
  72918. cntTab = 2;
  72919. pMatch = pItem;
  72920. pExpr->iColumn = j;
  72921. hit = 1;
  72922. }
  72923. }
  72924. if( hit || zTab==0 ) continue;
  72925. }
  72926. if( zDb && pTab->pSchema!=pSchema ){
  72927. continue;
  72928. }
  72929. if( zTab ){
  72930. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  72931. assert( zTabName!=0 );
  72932. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  72933. continue;
  72934. }
  72935. }
  72936. if( 0==(cntTab++) ){
  72937. pMatch = pItem;
  72938. }
  72939. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  72940. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  72941. /* If there has been exactly one prior match and this match
  72942. ** is for the right-hand table of a NATURAL JOIN or is in a
  72943. ** USING clause, then skip this match.
  72944. */
  72945. if( cnt==1 ){
  72946. if( pItem->jointype & JT_NATURAL ) continue;
  72947. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  72948. }
  72949. cnt++;
  72950. pMatch = pItem;
  72951. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  72952. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  72953. break;
  72954. }
  72955. }
  72956. }
  72957. if( pMatch ){
  72958. pExpr->iTable = pMatch->iCursor;
  72959. pExpr->pTab = pMatch->pTab;
  72960. pSchema = pExpr->pTab->pSchema;
  72961. }
  72962. } /* if( pSrcList ) */
  72963. #ifndef SQLITE_OMIT_TRIGGER
  72964. /* If we have not already resolved the name, then maybe
  72965. ** it is a new.* or old.* trigger argument reference
  72966. */
  72967. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  72968. int op = pParse->eTriggerOp;
  72969. Table *pTab = 0;
  72970. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  72971. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  72972. pExpr->iTable = 1;
  72973. pTab = pParse->pTriggerTab;
  72974. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  72975. pExpr->iTable = 0;
  72976. pTab = pParse->pTriggerTab;
  72977. }
  72978. if( pTab ){
  72979. int iCol;
  72980. pSchema = pTab->pSchema;
  72981. cntTab++;
  72982. for(iCol=0; iCol<pTab->nCol; iCol++){
  72983. Column *pCol = &pTab->aCol[iCol];
  72984. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  72985. if( iCol==pTab->iPKey ){
  72986. iCol = -1;
  72987. }
  72988. break;
  72989. }
  72990. }
  72991. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  72992. iCol = -1; /* IMP: R-44911-55124 */
  72993. }
  72994. if( iCol<pTab->nCol ){
  72995. cnt++;
  72996. if( iCol<0 ){
  72997. pExpr->affinity = SQLITE_AFF_INTEGER;
  72998. }else if( pExpr->iTable==0 ){
  72999. testcase( iCol==31 );
  73000. testcase( iCol==32 );
  73001. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  73002. }else{
  73003. testcase( iCol==31 );
  73004. testcase( iCol==32 );
  73005. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  73006. }
  73007. pExpr->iColumn = (i16)iCol;
  73008. pExpr->pTab = pTab;
  73009. isTrigger = 1;
  73010. }
  73011. }
  73012. }
  73013. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  73014. /*
  73015. ** Perhaps the name is a reference to the ROWID
  73016. */
  73017. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  73018. cnt = 1;
  73019. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  73020. pExpr->affinity = SQLITE_AFF_INTEGER;
  73021. }
  73022. /*
  73023. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  73024. ** might refer to an result-set alias. This happens, for example, when
  73025. ** we are resolving names in the WHERE clause of the following command:
  73026. **
  73027. ** SELECT a+b AS x FROM table WHERE x<10;
  73028. **
  73029. ** In cases like this, replace pExpr with a copy of the expression that
  73030. ** forms the result set entry ("a+b" in the example) and return immediately.
  73031. ** Note that the expression in the result set should have already been
  73032. ** resolved by the time the WHERE clause is resolved.
  73033. **
  73034. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  73035. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  73036. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  73037. ** is supported for backwards compatibility only. TO DO: Issue a warning
  73038. ** on sqlite3_log() whenever the capability is used.
  73039. */
  73040. if( (pEList = pNC->pEList)!=0
  73041. && zTab==0
  73042. && cnt==0
  73043. ){
  73044. for(j=0; j<pEList->nExpr; j++){
  73045. char *zAs = pEList->a[j].zName;
  73046. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  73047. Expr *pOrig;
  73048. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  73049. assert( pExpr->x.pList==0 );
  73050. assert( pExpr->x.pSelect==0 );
  73051. pOrig = pEList->a[j].pExpr;
  73052. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  73053. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  73054. return WRC_Abort;
  73055. }
  73056. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  73057. cnt = 1;
  73058. pMatch = 0;
  73059. assert( zTab==0 && zDb==0 );
  73060. goto lookupname_end;
  73061. }
  73062. }
  73063. }
  73064. /* Advance to the next name context. The loop will exit when either
  73065. ** we have a match (cnt>0) or when we run out of name contexts.
  73066. */
  73067. if( cnt==0 ){
  73068. pNC = pNC->pNext;
  73069. nSubquery++;
  73070. }
  73071. }
  73072. /*
  73073. ** If X and Y are NULL (in other words if only the column name Z is
  73074. ** supplied) and the value of Z is enclosed in double-quotes, then
  73075. ** Z is a string literal if it doesn't match any column names. In that
  73076. ** case, we need to return right away and not make any changes to
  73077. ** pExpr.
  73078. **
  73079. ** Because no reference was made to outer contexts, the pNC->nRef
  73080. ** fields are not changed in any context.
  73081. */
  73082. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  73083. pExpr->op = TK_STRING;
  73084. pExpr->pTab = 0;
  73085. return WRC_Prune;
  73086. }
  73087. /*
  73088. ** cnt==0 means there was not match. cnt>1 means there were two or
  73089. ** more matches. Either way, we have an error.
  73090. */
  73091. if( cnt!=1 ){
  73092. const char *zErr;
  73093. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  73094. if( zDb ){
  73095. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  73096. }else if( zTab ){
  73097. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  73098. }else{
  73099. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  73100. }
  73101. pParse->checkSchema = 1;
  73102. pTopNC->nErr++;
  73103. }
  73104. /* If a column from a table in pSrcList is referenced, then record
  73105. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  73106. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  73107. ** column number is greater than the number of bits in the bitmask
  73108. ** then set the high-order bit of the bitmask.
  73109. */
  73110. if( pExpr->iColumn>=0 && pMatch!=0 ){
  73111. int n = pExpr->iColumn;
  73112. testcase( n==BMS-1 );
  73113. if( n>=BMS ){
  73114. n = BMS-1;
  73115. }
  73116. assert( pMatch->iCursor==pExpr->iTable );
  73117. pMatch->colUsed |= ((Bitmask)1)<<n;
  73118. }
  73119. /* Clean up and return
  73120. */
  73121. sqlite3ExprDelete(db, pExpr->pLeft);
  73122. pExpr->pLeft = 0;
  73123. sqlite3ExprDelete(db, pExpr->pRight);
  73124. pExpr->pRight = 0;
  73125. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  73126. lookupname_end:
  73127. if( cnt==1 ){
  73128. assert( pNC!=0 );
  73129. if( pExpr->op!=TK_AS ){
  73130. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  73131. }
  73132. /* Increment the nRef value on all name contexts from TopNC up to
  73133. ** the point where the name matched. */
  73134. for(;;){
  73135. assert( pTopNC!=0 );
  73136. pTopNC->nRef++;
  73137. if( pTopNC==pNC ) break;
  73138. pTopNC = pTopNC->pNext;
  73139. }
  73140. return WRC_Prune;
  73141. } else {
  73142. return WRC_Abort;
  73143. }
  73144. }
  73145. /*
  73146. ** Allocate and return a pointer to an expression to load the column iCol
  73147. ** from datasource iSrc in SrcList pSrc.
  73148. */
  73149. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  73150. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  73151. if( p ){
  73152. struct SrcList_item *pItem = &pSrc->a[iSrc];
  73153. p->pTab = pItem->pTab;
  73154. p->iTable = pItem->iCursor;
  73155. if( p->pTab->iPKey==iCol ){
  73156. p->iColumn = -1;
  73157. }else{
  73158. p->iColumn = (ynVar)iCol;
  73159. testcase( iCol==BMS );
  73160. testcase( iCol==BMS-1 );
  73161. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  73162. }
  73163. ExprSetProperty(p, EP_Resolved);
  73164. }
  73165. return p;
  73166. }
  73167. /*
  73168. ** Report an error that an expression is not valid for a partial index WHERE
  73169. ** clause.
  73170. */
  73171. static void notValidPartIdxWhere(
  73172. Parse *pParse, /* Leave error message here */
  73173. NameContext *pNC, /* The name context */
  73174. const char *zMsg /* Type of error */
  73175. ){
  73176. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  73177. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  73178. zMsg);
  73179. }
  73180. }
  73181. #ifndef SQLITE_OMIT_CHECK
  73182. /*
  73183. ** Report an error that an expression is not valid for a CHECK constraint.
  73184. */
  73185. static void notValidCheckConstraint(
  73186. Parse *pParse, /* Leave error message here */
  73187. NameContext *pNC, /* The name context */
  73188. const char *zMsg /* Type of error */
  73189. ){
  73190. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  73191. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  73192. }
  73193. }
  73194. #else
  73195. # define notValidCheckConstraint(P,N,M)
  73196. #endif
  73197. /*
  73198. ** Expression p should encode a floating point value between 1.0 and 0.0.
  73199. ** Return 1024 times this value. Or return -1 if p is not a floating point
  73200. ** value between 1.0 and 0.0.
  73201. */
  73202. static int exprProbability(Expr *p){
  73203. double r = -1.0;
  73204. if( p->op!=TK_FLOAT ) return -1;
  73205. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  73206. assert( r>=0.0 );
  73207. if( r>1.0 ) return -1;
  73208. return (int)(r*1000.0);
  73209. }
  73210. /*
  73211. ** This routine is callback for sqlite3WalkExpr().
  73212. **
  73213. ** Resolve symbolic names into TK_COLUMN operators for the current
  73214. ** node in the expression tree. Return 0 to continue the search down
  73215. ** the tree or 2 to abort the tree walk.
  73216. **
  73217. ** This routine also does error checking and name resolution for
  73218. ** function names. The operator for aggregate functions is changed
  73219. ** to TK_AGG_FUNCTION.
  73220. */
  73221. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  73222. NameContext *pNC;
  73223. Parse *pParse;
  73224. pNC = pWalker->u.pNC;
  73225. assert( pNC!=0 );
  73226. pParse = pNC->pParse;
  73227. assert( pParse==pWalker->pParse );
  73228. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  73229. ExprSetProperty(pExpr, EP_Resolved);
  73230. #ifndef NDEBUG
  73231. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  73232. SrcList *pSrcList = pNC->pSrcList;
  73233. int i;
  73234. for(i=0; i<pNC->pSrcList->nSrc; i++){
  73235. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  73236. }
  73237. }
  73238. #endif
  73239. switch( pExpr->op ){
  73240. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  73241. /* The special operator TK_ROW means use the rowid for the first
  73242. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  73243. ** clause processing on UPDATE and DELETE statements.
  73244. */
  73245. case TK_ROW: {
  73246. SrcList *pSrcList = pNC->pSrcList;
  73247. struct SrcList_item *pItem;
  73248. assert( pSrcList && pSrcList->nSrc==1 );
  73249. pItem = pSrcList->a;
  73250. pExpr->op = TK_COLUMN;
  73251. pExpr->pTab = pItem->pTab;
  73252. pExpr->iTable = pItem->iCursor;
  73253. pExpr->iColumn = -1;
  73254. pExpr->affinity = SQLITE_AFF_INTEGER;
  73255. break;
  73256. }
  73257. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  73258. /* A lone identifier is the name of a column.
  73259. */
  73260. case TK_ID: {
  73261. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  73262. }
  73263. /* A table name and column name: ID.ID
  73264. ** Or a database, table and column: ID.ID.ID
  73265. */
  73266. case TK_DOT: {
  73267. const char *zColumn;
  73268. const char *zTable;
  73269. const char *zDb;
  73270. Expr *pRight;
  73271. /* if( pSrcList==0 ) break; */
  73272. pRight = pExpr->pRight;
  73273. if( pRight->op==TK_ID ){
  73274. zDb = 0;
  73275. zTable = pExpr->pLeft->u.zToken;
  73276. zColumn = pRight->u.zToken;
  73277. }else{
  73278. assert( pRight->op==TK_DOT );
  73279. zDb = pExpr->pLeft->u.zToken;
  73280. zTable = pRight->pLeft->u.zToken;
  73281. zColumn = pRight->pRight->u.zToken;
  73282. }
  73283. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  73284. }
  73285. /* Resolve function names
  73286. */
  73287. case TK_CONST_FUNC:
  73288. case TK_FUNCTION: {
  73289. ExprList *pList = pExpr->x.pList; /* The argument list */
  73290. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  73291. int no_such_func = 0; /* True if no such function exists */
  73292. int wrong_num_args = 0; /* True if wrong number of arguments */
  73293. int is_agg = 0; /* True if is an aggregate function */
  73294. int auth; /* Authorization to use the function */
  73295. int nId; /* Number of characters in function name */
  73296. const char *zId; /* The function name. */
  73297. FuncDef *pDef; /* Information about the function */
  73298. u8 enc = ENC(pParse->db); /* The database encoding */
  73299. testcase( pExpr->op==TK_CONST_FUNC );
  73300. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  73301. notValidPartIdxWhere(pParse, pNC, "functions");
  73302. zId = pExpr->u.zToken;
  73303. nId = sqlite3Strlen30(zId);
  73304. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  73305. if( pDef==0 ){
  73306. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  73307. if( pDef==0 ){
  73308. no_such_func = 1;
  73309. }else{
  73310. wrong_num_args = 1;
  73311. }
  73312. }else{
  73313. is_agg = pDef->xFunc==0;
  73314. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  73315. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  73316. if( n==2 ){
  73317. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  73318. if( pExpr->iTable<0 ){
  73319. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  73320. "constant between 0.0 and 1.0");
  73321. pNC->nErr++;
  73322. }
  73323. }else{
  73324. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  73325. ** likelihood(X, 0.0625).
  73326. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  73327. ** likelihood(X,0.0625). */
  73328. pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
  73329. }
  73330. }
  73331. }
  73332. #ifndef SQLITE_OMIT_AUTHORIZATION
  73333. if( pDef ){
  73334. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  73335. if( auth!=SQLITE_OK ){
  73336. if( auth==SQLITE_DENY ){
  73337. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  73338. pDef->zName);
  73339. pNC->nErr++;
  73340. }
  73341. pExpr->op = TK_NULL;
  73342. return WRC_Prune;
  73343. }
  73344. }
  73345. #endif
  73346. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  73347. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  73348. pNC->nErr++;
  73349. is_agg = 0;
  73350. }else if( no_such_func && pParse->db->init.busy==0 ){
  73351. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  73352. pNC->nErr++;
  73353. }else if( wrong_num_args ){
  73354. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  73355. nId, zId);
  73356. pNC->nErr++;
  73357. }
  73358. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  73359. sqlite3WalkExprList(pWalker, pList);
  73360. if( is_agg ){
  73361. NameContext *pNC2 = pNC;
  73362. pExpr->op = TK_AGG_FUNCTION;
  73363. pExpr->op2 = 0;
  73364. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  73365. pExpr->op2++;
  73366. pNC2 = pNC2->pNext;
  73367. }
  73368. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  73369. pNC->ncFlags |= NC_AllowAgg;
  73370. }
  73371. /* FIX ME: Compute pExpr->affinity based on the expected return
  73372. ** type of the function
  73373. */
  73374. return WRC_Prune;
  73375. }
  73376. #ifndef SQLITE_OMIT_SUBQUERY
  73377. case TK_SELECT:
  73378. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  73379. #endif
  73380. case TK_IN: {
  73381. testcase( pExpr->op==TK_IN );
  73382. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  73383. int nRef = pNC->nRef;
  73384. notValidCheckConstraint(pParse, pNC, "subqueries");
  73385. notValidPartIdxWhere(pParse, pNC, "subqueries");
  73386. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  73387. assert( pNC->nRef>=nRef );
  73388. if( nRef!=pNC->nRef ){
  73389. ExprSetProperty(pExpr, EP_VarSelect);
  73390. }
  73391. }
  73392. break;
  73393. }
  73394. case TK_VARIABLE: {
  73395. notValidCheckConstraint(pParse, pNC, "parameters");
  73396. notValidPartIdxWhere(pParse, pNC, "parameters");
  73397. break;
  73398. }
  73399. }
  73400. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  73401. }
  73402. /*
  73403. ** pEList is a list of expressions which are really the result set of the
  73404. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  73405. ** This routine checks to see if pE is a simple identifier which corresponds
  73406. ** to the AS-name of one of the terms of the expression list. If it is,
  73407. ** this routine return an integer between 1 and N where N is the number of
  73408. ** elements in pEList, corresponding to the matching entry. If there is
  73409. ** no match, or if pE is not a simple identifier, then this routine
  73410. ** return 0.
  73411. **
  73412. ** pEList has been resolved. pE has not.
  73413. */
  73414. static int resolveAsName(
  73415. Parse *pParse, /* Parsing context for error messages */
  73416. ExprList *pEList, /* List of expressions to scan */
  73417. Expr *pE /* Expression we are trying to match */
  73418. ){
  73419. int i; /* Loop counter */
  73420. UNUSED_PARAMETER(pParse);
  73421. if( pE->op==TK_ID ){
  73422. char *zCol = pE->u.zToken;
  73423. for(i=0; i<pEList->nExpr; i++){
  73424. char *zAs = pEList->a[i].zName;
  73425. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  73426. return i+1;
  73427. }
  73428. }
  73429. }
  73430. return 0;
  73431. }
  73432. /*
  73433. ** pE is a pointer to an expression which is a single term in the
  73434. ** ORDER BY of a compound SELECT. The expression has not been
  73435. ** name resolved.
  73436. **
  73437. ** At the point this routine is called, we already know that the
  73438. ** ORDER BY term is not an integer index into the result set. That
  73439. ** case is handled by the calling routine.
  73440. **
  73441. ** Attempt to match pE against result set columns in the left-most
  73442. ** SELECT statement. Return the index i of the matching column,
  73443. ** as an indication to the caller that it should sort by the i-th column.
  73444. ** The left-most column is 1. In other words, the value returned is the
  73445. ** same integer value that would be used in the SQL statement to indicate
  73446. ** the column.
  73447. **
  73448. ** If there is no match, return 0. Return -1 if an error occurs.
  73449. */
  73450. static int resolveOrderByTermToExprList(
  73451. Parse *pParse, /* Parsing context for error messages */
  73452. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  73453. Expr *pE /* The specific ORDER BY term */
  73454. ){
  73455. int i; /* Loop counter */
  73456. ExprList *pEList; /* The columns of the result set */
  73457. NameContext nc; /* Name context for resolving pE */
  73458. sqlite3 *db; /* Database connection */
  73459. int rc; /* Return code from subprocedures */
  73460. u8 savedSuppErr; /* Saved value of db->suppressErr */
  73461. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  73462. pEList = pSelect->pEList;
  73463. /* Resolve all names in the ORDER BY term expression
  73464. */
  73465. memset(&nc, 0, sizeof(nc));
  73466. nc.pParse = pParse;
  73467. nc.pSrcList = pSelect->pSrc;
  73468. nc.pEList = pEList;
  73469. nc.ncFlags = NC_AllowAgg;
  73470. nc.nErr = 0;
  73471. db = pParse->db;
  73472. savedSuppErr = db->suppressErr;
  73473. db->suppressErr = 1;
  73474. rc = sqlite3ResolveExprNames(&nc, pE);
  73475. db->suppressErr = savedSuppErr;
  73476. if( rc ) return 0;
  73477. /* Try to match the ORDER BY expression against an expression
  73478. ** in the result set. Return an 1-based index of the matching
  73479. ** result-set entry.
  73480. */
  73481. for(i=0; i<pEList->nExpr; i++){
  73482. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  73483. return i+1;
  73484. }
  73485. }
  73486. /* If no match, return 0. */
  73487. return 0;
  73488. }
  73489. /*
  73490. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  73491. */
  73492. static void resolveOutOfRangeError(
  73493. Parse *pParse, /* The error context into which to write the error */
  73494. const char *zType, /* "ORDER" or "GROUP" */
  73495. int i, /* The index (1-based) of the term out of range */
  73496. int mx /* Largest permissible value of i */
  73497. ){
  73498. sqlite3ErrorMsg(pParse,
  73499. "%r %s BY term out of range - should be "
  73500. "between 1 and %d", i, zType, mx);
  73501. }
  73502. /*
  73503. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  73504. ** each term of the ORDER BY clause is a constant integer between 1
  73505. ** and N where N is the number of columns in the compound SELECT.
  73506. **
  73507. ** ORDER BY terms that are already an integer between 1 and N are
  73508. ** unmodified. ORDER BY terms that are integers outside the range of
  73509. ** 1 through N generate an error. ORDER BY terms that are expressions
  73510. ** are matched against result set expressions of compound SELECT
  73511. ** beginning with the left-most SELECT and working toward the right.
  73512. ** At the first match, the ORDER BY expression is transformed into
  73513. ** the integer column number.
  73514. **
  73515. ** Return the number of errors seen.
  73516. */
  73517. static int resolveCompoundOrderBy(
  73518. Parse *pParse, /* Parsing context. Leave error messages here */
  73519. Select *pSelect /* The SELECT statement containing the ORDER BY */
  73520. ){
  73521. int i;
  73522. ExprList *pOrderBy;
  73523. ExprList *pEList;
  73524. sqlite3 *db;
  73525. int moreToDo = 1;
  73526. pOrderBy = pSelect->pOrderBy;
  73527. if( pOrderBy==0 ) return 0;
  73528. db = pParse->db;
  73529. #if SQLITE_MAX_COLUMN
  73530. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  73531. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  73532. return 1;
  73533. }
  73534. #endif
  73535. for(i=0; i<pOrderBy->nExpr; i++){
  73536. pOrderBy->a[i].done = 0;
  73537. }
  73538. pSelect->pNext = 0;
  73539. while( pSelect->pPrior ){
  73540. pSelect->pPrior->pNext = pSelect;
  73541. pSelect = pSelect->pPrior;
  73542. }
  73543. while( pSelect && moreToDo ){
  73544. struct ExprList_item *pItem;
  73545. moreToDo = 0;
  73546. pEList = pSelect->pEList;
  73547. assert( pEList!=0 );
  73548. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73549. int iCol = -1;
  73550. Expr *pE, *pDup;
  73551. if( pItem->done ) continue;
  73552. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  73553. if( sqlite3ExprIsInteger(pE, &iCol) ){
  73554. if( iCol<=0 || iCol>pEList->nExpr ){
  73555. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  73556. return 1;
  73557. }
  73558. }else{
  73559. iCol = resolveAsName(pParse, pEList, pE);
  73560. if( iCol==0 ){
  73561. pDup = sqlite3ExprDup(db, pE, 0);
  73562. if( !db->mallocFailed ){
  73563. assert(pDup);
  73564. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  73565. }
  73566. sqlite3ExprDelete(db, pDup);
  73567. }
  73568. }
  73569. if( iCol>0 ){
  73570. /* Convert the ORDER BY term into an integer column number iCol,
  73571. ** taking care to preserve the COLLATE clause if it exists */
  73572. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  73573. if( pNew==0 ) return 1;
  73574. pNew->flags |= EP_IntValue;
  73575. pNew->u.iValue = iCol;
  73576. if( pItem->pExpr==pE ){
  73577. pItem->pExpr = pNew;
  73578. }else{
  73579. assert( pItem->pExpr->op==TK_COLLATE );
  73580. assert( pItem->pExpr->pLeft==pE );
  73581. pItem->pExpr->pLeft = pNew;
  73582. }
  73583. sqlite3ExprDelete(db, pE);
  73584. pItem->iOrderByCol = (u16)iCol;
  73585. pItem->done = 1;
  73586. }else{
  73587. moreToDo = 1;
  73588. }
  73589. }
  73590. pSelect = pSelect->pNext;
  73591. }
  73592. for(i=0; i<pOrderBy->nExpr; i++){
  73593. if( pOrderBy->a[i].done==0 ){
  73594. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  73595. "column in the result set", i+1);
  73596. return 1;
  73597. }
  73598. }
  73599. return 0;
  73600. }
  73601. /*
  73602. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  73603. ** the SELECT statement pSelect. If any term is reference to a
  73604. ** result set expression (as determined by the ExprList.a.iOrderByCol field)
  73605. ** then convert that term into a copy of the corresponding result set
  73606. ** column.
  73607. **
  73608. ** If any errors are detected, add an error message to pParse and
  73609. ** return non-zero. Return zero if no errors are seen.
  73610. */
  73611. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  73612. Parse *pParse, /* Parsing context. Leave error messages here */
  73613. Select *pSelect, /* The SELECT statement containing the clause */
  73614. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  73615. const char *zType /* "ORDER" or "GROUP" */
  73616. ){
  73617. int i;
  73618. sqlite3 *db = pParse->db;
  73619. ExprList *pEList;
  73620. struct ExprList_item *pItem;
  73621. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  73622. #if SQLITE_MAX_COLUMN
  73623. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  73624. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  73625. return 1;
  73626. }
  73627. #endif
  73628. pEList = pSelect->pEList;
  73629. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  73630. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73631. if( pItem->iOrderByCol ){
  73632. if( pItem->iOrderByCol>pEList->nExpr ){
  73633. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  73634. return 1;
  73635. }
  73636. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  73637. }
  73638. }
  73639. return 0;
  73640. }
  73641. /*
  73642. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  73643. ** The Name context of the SELECT statement is pNC. zType is either
  73644. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  73645. **
  73646. ** This routine resolves each term of the clause into an expression.
  73647. ** If the order-by term is an integer I between 1 and N (where N is the
  73648. ** number of columns in the result set of the SELECT) then the expression
  73649. ** in the resolution is a copy of the I-th result-set expression. If
  73650. ** the order-by term is an identifier that corresponds to the AS-name of
  73651. ** a result-set expression, then the term resolves to a copy of the
  73652. ** result-set expression. Otherwise, the expression is resolved in
  73653. ** the usual way - using sqlite3ResolveExprNames().
  73654. **
  73655. ** This routine returns the number of errors. If errors occur, then
  73656. ** an appropriate error message might be left in pParse. (OOM errors
  73657. ** excepted.)
  73658. */
  73659. static int resolveOrderGroupBy(
  73660. NameContext *pNC, /* The name context of the SELECT statement */
  73661. Select *pSelect, /* The SELECT statement holding pOrderBy */
  73662. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  73663. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  73664. ){
  73665. int i, j; /* Loop counters */
  73666. int iCol; /* Column number */
  73667. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  73668. Parse *pParse; /* Parsing context */
  73669. int nResult; /* Number of terms in the result set */
  73670. if( pOrderBy==0 ) return 0;
  73671. nResult = pSelect->pEList->nExpr;
  73672. pParse = pNC->pParse;
  73673. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73674. Expr *pE = pItem->pExpr;
  73675. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  73676. if( zType[0]!='G' ){
  73677. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  73678. if( iCol>0 ){
  73679. /* If an AS-name match is found, mark this ORDER BY column as being
  73680. ** a copy of the iCol-th result-set column. The subsequent call to
  73681. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  73682. ** copy of the iCol-th result-set expression. */
  73683. pItem->iOrderByCol = (u16)iCol;
  73684. continue;
  73685. }
  73686. }
  73687. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  73688. /* The ORDER BY term is an integer constant. Again, set the column
  73689. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  73690. ** order-by term to a copy of the result-set expression */
  73691. if( iCol<1 || iCol>0xffff ){
  73692. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  73693. return 1;
  73694. }
  73695. pItem->iOrderByCol = (u16)iCol;
  73696. continue;
  73697. }
  73698. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  73699. pItem->iOrderByCol = 0;
  73700. if( sqlite3ResolveExprNames(pNC, pE) ){
  73701. return 1;
  73702. }
  73703. for(j=0; j<pSelect->pEList->nExpr; j++){
  73704. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  73705. pItem->iOrderByCol = j+1;
  73706. }
  73707. }
  73708. }
  73709. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  73710. }
  73711. /*
  73712. ** Resolve names in the SELECT statement p and all of its descendents.
  73713. */
  73714. static int resolveSelectStep(Walker *pWalker, Select *p){
  73715. NameContext *pOuterNC; /* Context that contains this SELECT */
  73716. NameContext sNC; /* Name context of this SELECT */
  73717. int isCompound; /* True if p is a compound select */
  73718. int nCompound; /* Number of compound terms processed so far */
  73719. Parse *pParse; /* Parsing context */
  73720. ExprList *pEList; /* Result set expression list */
  73721. int i; /* Loop counter */
  73722. ExprList *pGroupBy; /* The GROUP BY clause */
  73723. Select *pLeftmost; /* Left-most of SELECT of a compound */
  73724. sqlite3 *db; /* Database connection */
  73725. assert( p!=0 );
  73726. if( p->selFlags & SF_Resolved ){
  73727. return WRC_Prune;
  73728. }
  73729. pOuterNC = pWalker->u.pNC;
  73730. pParse = pWalker->pParse;
  73731. db = pParse->db;
  73732. /* Normally sqlite3SelectExpand() will be called first and will have
  73733. ** already expanded this SELECT. However, if this is a subquery within
  73734. ** an expression, sqlite3ResolveExprNames() will be called without a
  73735. ** prior call to sqlite3SelectExpand(). When that happens, let
  73736. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  73737. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  73738. ** this routine in the correct order.
  73739. */
  73740. if( (p->selFlags & SF_Expanded)==0 ){
  73741. sqlite3SelectPrep(pParse, p, pOuterNC);
  73742. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  73743. }
  73744. isCompound = p->pPrior!=0;
  73745. nCompound = 0;
  73746. pLeftmost = p;
  73747. while( p ){
  73748. assert( (p->selFlags & SF_Expanded)!=0 );
  73749. assert( (p->selFlags & SF_Resolved)==0 );
  73750. p->selFlags |= SF_Resolved;
  73751. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  73752. ** are not allowed to refer to any names, so pass an empty NameContext.
  73753. */
  73754. memset(&sNC, 0, sizeof(sNC));
  73755. sNC.pParse = pParse;
  73756. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  73757. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  73758. return WRC_Abort;
  73759. }
  73760. /* Recursively resolve names in all subqueries
  73761. */
  73762. for(i=0; i<p->pSrc->nSrc; i++){
  73763. struct SrcList_item *pItem = &p->pSrc->a[i];
  73764. if( pItem->pSelect ){
  73765. NameContext *pNC; /* Used to iterate name contexts */
  73766. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  73767. const char *zSavedContext = pParse->zAuthContext;
  73768. /* Count the total number of references to pOuterNC and all of its
  73769. ** parent contexts. After resolving references to expressions in
  73770. ** pItem->pSelect, check if this value has changed. If so, then
  73771. ** SELECT statement pItem->pSelect must be correlated. Set the
  73772. ** pItem->isCorrelated flag if this is the case. */
  73773. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  73774. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  73775. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  73776. pParse->zAuthContext = zSavedContext;
  73777. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  73778. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  73779. assert( pItem->isCorrelated==0 && nRef<=0 );
  73780. pItem->isCorrelated = (nRef!=0);
  73781. }
  73782. }
  73783. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  73784. ** resolve the result-set expression list.
  73785. */
  73786. sNC.ncFlags = NC_AllowAgg;
  73787. sNC.pSrcList = p->pSrc;
  73788. sNC.pNext = pOuterNC;
  73789. /* Resolve names in the result set. */
  73790. pEList = p->pEList;
  73791. assert( pEList!=0 );
  73792. for(i=0; i<pEList->nExpr; i++){
  73793. Expr *pX = pEList->a[i].pExpr;
  73794. if( sqlite3ResolveExprNames(&sNC, pX) ){
  73795. return WRC_Abort;
  73796. }
  73797. }
  73798. /* If there are no aggregate functions in the result-set, and no GROUP BY
  73799. ** expression, do not allow aggregates in any of the other expressions.
  73800. */
  73801. assert( (p->selFlags & SF_Aggregate)==0 );
  73802. pGroupBy = p->pGroupBy;
  73803. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  73804. p->selFlags |= SF_Aggregate;
  73805. }else{
  73806. sNC.ncFlags &= ~NC_AllowAgg;
  73807. }
  73808. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  73809. */
  73810. if( p->pHaving && !pGroupBy ){
  73811. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  73812. return WRC_Abort;
  73813. }
  73814. /* Add the output column list to the name-context before parsing the
  73815. ** other expressions in the SELECT statement. This is so that
  73816. ** expressions in the WHERE clause (etc.) can refer to expressions by
  73817. ** aliases in the result set.
  73818. **
  73819. ** Minor point: If this is the case, then the expression will be
  73820. ** re-evaluated for each reference to it.
  73821. */
  73822. sNC.pEList = p->pEList;
  73823. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  73824. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  73825. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  73826. ** outer queries
  73827. */
  73828. sNC.pNext = 0;
  73829. sNC.ncFlags |= NC_AllowAgg;
  73830. /* Process the ORDER BY clause for singleton SELECT statements.
  73831. ** The ORDER BY clause for compounds SELECT statements is handled
  73832. ** below, after all of the result-sets for all of the elements of
  73833. ** the compound have been resolved.
  73834. */
  73835. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  73836. return WRC_Abort;
  73837. }
  73838. if( db->mallocFailed ){
  73839. return WRC_Abort;
  73840. }
  73841. /* Resolve the GROUP BY clause. At the same time, make sure
  73842. ** the GROUP BY clause does not contain aggregate functions.
  73843. */
  73844. if( pGroupBy ){
  73845. struct ExprList_item *pItem;
  73846. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  73847. return WRC_Abort;
  73848. }
  73849. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  73850. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  73851. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  73852. "the GROUP BY clause");
  73853. return WRC_Abort;
  73854. }
  73855. }
  73856. }
  73857. /* Advance to the next term of the compound
  73858. */
  73859. p = p->pPrior;
  73860. nCompound++;
  73861. }
  73862. /* Resolve the ORDER BY on a compound SELECT after all terms of
  73863. ** the compound have been resolved.
  73864. */
  73865. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  73866. return WRC_Abort;
  73867. }
  73868. return WRC_Prune;
  73869. }
  73870. /*
  73871. ** This routine walks an expression tree and resolves references to
  73872. ** table columns and result-set columns. At the same time, do error
  73873. ** checking on function usage and set a flag if any aggregate functions
  73874. ** are seen.
  73875. **
  73876. ** To resolve table columns references we look for nodes (or subtrees) of the
  73877. ** form X.Y.Z or Y.Z or just Z where
  73878. **
  73879. ** X: The name of a database. Ex: "main" or "temp" or
  73880. ** the symbolic name assigned to an ATTACH-ed database.
  73881. **
  73882. ** Y: The name of a table in a FROM clause. Or in a trigger
  73883. ** one of the special names "old" or "new".
  73884. **
  73885. ** Z: The name of a column in table Y.
  73886. **
  73887. ** The node at the root of the subtree is modified as follows:
  73888. **
  73889. ** Expr.op Changed to TK_COLUMN
  73890. ** Expr.pTab Points to the Table object for X.Y
  73891. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  73892. ** Expr.iTable The VDBE cursor number for X.Y
  73893. **
  73894. **
  73895. ** To resolve result-set references, look for expression nodes of the
  73896. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  73897. ** size of an AS clause in the result-set of a SELECT. The Z expression
  73898. ** is replaced by a copy of the left-hand side of the result-set expression.
  73899. ** Table-name and function resolution occurs on the substituted expression
  73900. ** tree. For example, in:
  73901. **
  73902. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  73903. **
  73904. ** The "x" term of the order by is replaced by "a+b" to render:
  73905. **
  73906. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  73907. **
  73908. ** Function calls are checked to make sure that the function is
  73909. ** defined and that the correct number of arguments are specified.
  73910. ** If the function is an aggregate function, then the NC_HasAgg flag is
  73911. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  73912. ** If an expression contains aggregate functions then the EP_Agg
  73913. ** property on the expression is set.
  73914. **
  73915. ** An error message is left in pParse if anything is amiss. The number
  73916. ** if errors is returned.
  73917. */
  73918. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  73919. NameContext *pNC, /* Namespace to resolve expressions in. */
  73920. Expr *pExpr /* The expression to be analyzed. */
  73921. ){
  73922. u8 savedHasAgg;
  73923. Walker w;
  73924. if( pExpr==0 ) return 0;
  73925. #if SQLITE_MAX_EXPR_DEPTH>0
  73926. {
  73927. Parse *pParse = pNC->pParse;
  73928. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  73929. return 1;
  73930. }
  73931. pParse->nHeight += pExpr->nHeight;
  73932. }
  73933. #endif
  73934. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  73935. pNC->ncFlags &= ~NC_HasAgg;
  73936. memset(&w, 0, sizeof(w));
  73937. w.xExprCallback = resolveExprStep;
  73938. w.xSelectCallback = resolveSelectStep;
  73939. w.pParse = pNC->pParse;
  73940. w.u.pNC = pNC;
  73941. sqlite3WalkExpr(&w, pExpr);
  73942. #if SQLITE_MAX_EXPR_DEPTH>0
  73943. pNC->pParse->nHeight -= pExpr->nHeight;
  73944. #endif
  73945. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  73946. ExprSetProperty(pExpr, EP_Error);
  73947. }
  73948. if( pNC->ncFlags & NC_HasAgg ){
  73949. ExprSetProperty(pExpr, EP_Agg);
  73950. }else if( savedHasAgg ){
  73951. pNC->ncFlags |= NC_HasAgg;
  73952. }
  73953. return ExprHasProperty(pExpr, EP_Error);
  73954. }
  73955. /*
  73956. ** Resolve all names in all expressions of a SELECT and in all
  73957. ** decendents of the SELECT, including compounds off of p->pPrior,
  73958. ** subqueries in expressions, and subqueries used as FROM clause
  73959. ** terms.
  73960. **
  73961. ** See sqlite3ResolveExprNames() for a description of the kinds of
  73962. ** transformations that occur.
  73963. **
  73964. ** All SELECT statements should have been expanded using
  73965. ** sqlite3SelectExpand() prior to invoking this routine.
  73966. */
  73967. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  73968. Parse *pParse, /* The parser context */
  73969. Select *p, /* The SELECT statement being coded. */
  73970. NameContext *pOuterNC /* Name context for parent SELECT statement */
  73971. ){
  73972. Walker w;
  73973. assert( p!=0 );
  73974. memset(&w, 0, sizeof(w));
  73975. w.xExprCallback = resolveExprStep;
  73976. w.xSelectCallback = resolveSelectStep;
  73977. w.pParse = pParse;
  73978. w.u.pNC = pOuterNC;
  73979. sqlite3WalkSelect(&w, p);
  73980. }
  73981. /*
  73982. ** Resolve names in expressions that can only reference a single table:
  73983. **
  73984. ** * CHECK constraints
  73985. ** * WHERE clauses on partial indices
  73986. **
  73987. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  73988. ** is set to -1 and the Expr.iColumn value is set to the column number.
  73989. **
  73990. ** Any errors cause an error message to be set in pParse.
  73991. */
  73992. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  73993. Parse *pParse, /* Parsing context */
  73994. Table *pTab, /* The table being referenced */
  73995. int type, /* NC_IsCheck or NC_PartIdx */
  73996. Expr *pExpr, /* Expression to resolve. May be NULL. */
  73997. ExprList *pList /* Expression list to resolve. May be NUL. */
  73998. ){
  73999. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  74000. NameContext sNC; /* Name context for pParse->pNewTable */
  74001. int i; /* Loop counter */
  74002. assert( type==NC_IsCheck || type==NC_PartIdx );
  74003. memset(&sNC, 0, sizeof(sNC));
  74004. memset(&sSrc, 0, sizeof(sSrc));
  74005. sSrc.nSrc = 1;
  74006. sSrc.a[0].zName = pTab->zName;
  74007. sSrc.a[0].pTab = pTab;
  74008. sSrc.a[0].iCursor = -1;
  74009. sNC.pParse = pParse;
  74010. sNC.pSrcList = &sSrc;
  74011. sNC.ncFlags = type;
  74012. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  74013. if( pList ){
  74014. for(i=0; i<pList->nExpr; i++){
  74015. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  74016. return;
  74017. }
  74018. }
  74019. }
  74020. }
  74021. /************** End of resolve.c *********************************************/
  74022. /************** Begin file expr.c ********************************************/
  74023. /*
  74024. ** 2001 September 15
  74025. **
  74026. ** The author disclaims copyright to this source code. In place of
  74027. ** a legal notice, here is a blessing:
  74028. **
  74029. ** May you do good and not evil.
  74030. ** May you find forgiveness for yourself and forgive others.
  74031. ** May you share freely, never taking more than you give.
  74032. **
  74033. *************************************************************************
  74034. ** This file contains routines used for analyzing expressions and
  74035. ** for generating VDBE code that evaluates expressions in SQLite.
  74036. */
  74037. /*
  74038. ** Return the 'affinity' of the expression pExpr if any.
  74039. **
  74040. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  74041. ** or a sub-select with a column as the return value, then the
  74042. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  74043. ** indicating no affinity for the expression.
  74044. **
  74045. ** i.e. the WHERE clause expresssions in the following statements all
  74046. ** have an affinity:
  74047. **
  74048. ** CREATE TABLE t1(a);
  74049. ** SELECT * FROM t1 WHERE a;
  74050. ** SELECT a AS b FROM t1 WHERE b;
  74051. ** SELECT * FROM t1 WHERE (select a from t1);
  74052. */
  74053. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  74054. int op;
  74055. pExpr = sqlite3ExprSkipCollate(pExpr);
  74056. op = pExpr->op;
  74057. if( op==TK_SELECT ){
  74058. assert( pExpr->flags&EP_xIsSelect );
  74059. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  74060. }
  74061. #ifndef SQLITE_OMIT_CAST
  74062. if( op==TK_CAST ){
  74063. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  74064. return sqlite3AffinityType(pExpr->u.zToken, 0);
  74065. }
  74066. #endif
  74067. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  74068. && pExpr->pTab!=0
  74069. ){
  74070. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  74071. ** a TK_COLUMN but was previously evaluated and cached in a register */
  74072. int j = pExpr->iColumn;
  74073. if( j<0 ) return SQLITE_AFF_INTEGER;
  74074. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  74075. return pExpr->pTab->aCol[j].affinity;
  74076. }
  74077. return pExpr->affinity;
  74078. }
  74079. /*
  74080. ** Set the collating sequence for expression pExpr to be the collating
  74081. ** sequence named by pToken. Return a pointer to a new Expr node that
  74082. ** implements the COLLATE operator.
  74083. **
  74084. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  74085. ** and the pExpr parameter is returned unchanged.
  74086. */
  74087. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  74088. if( pCollName->n>0 ){
  74089. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  74090. if( pNew ){
  74091. pNew->pLeft = pExpr;
  74092. pNew->flags |= EP_Collate|EP_Skip;
  74093. pExpr = pNew;
  74094. }
  74095. }
  74096. return pExpr;
  74097. }
  74098. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  74099. Token s;
  74100. assert( zC!=0 );
  74101. s.z = zC;
  74102. s.n = sqlite3Strlen30(s.z);
  74103. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  74104. }
  74105. /*
  74106. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  74107. ** or likelihood() function at the root of an expression.
  74108. */
  74109. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  74110. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  74111. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  74112. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74113. assert( pExpr->x.pList->nExpr>0 );
  74114. assert( pExpr->op==TK_FUNCTION );
  74115. pExpr = pExpr->x.pList->a[0].pExpr;
  74116. }else{
  74117. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  74118. pExpr = pExpr->pLeft;
  74119. }
  74120. }
  74121. return pExpr;
  74122. }
  74123. /*
  74124. ** Return the collation sequence for the expression pExpr. If
  74125. ** there is no defined collating sequence, return NULL.
  74126. **
  74127. ** The collating sequence might be determined by a COLLATE operator
  74128. ** or by the presence of a column with a defined collating sequence.
  74129. ** COLLATE operators take first precedence. Left operands take
  74130. ** precedence over right operands.
  74131. */
  74132. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  74133. sqlite3 *db = pParse->db;
  74134. CollSeq *pColl = 0;
  74135. Expr *p = pExpr;
  74136. while( p ){
  74137. int op = p->op;
  74138. if( op==TK_CAST || op==TK_UPLUS ){
  74139. p = p->pLeft;
  74140. continue;
  74141. }
  74142. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  74143. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  74144. break;
  74145. }
  74146. if( p->pTab!=0
  74147. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  74148. || op==TK_REGISTER || op==TK_TRIGGER)
  74149. ){
  74150. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  74151. ** a TK_COLUMN but was previously evaluated and cached in a register */
  74152. int j = p->iColumn;
  74153. if( j>=0 ){
  74154. const char *zColl = p->pTab->aCol[j].zColl;
  74155. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  74156. }
  74157. break;
  74158. }
  74159. if( p->flags & EP_Collate ){
  74160. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  74161. p = p->pLeft;
  74162. }else{
  74163. p = p->pRight;
  74164. }
  74165. }else{
  74166. break;
  74167. }
  74168. }
  74169. if( sqlite3CheckCollSeq(pParse, pColl) ){
  74170. pColl = 0;
  74171. }
  74172. return pColl;
  74173. }
  74174. /*
  74175. ** pExpr is an operand of a comparison operator. aff2 is the
  74176. ** type affinity of the other operand. This routine returns the
  74177. ** type affinity that should be used for the comparison operator.
  74178. */
  74179. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  74180. char aff1 = sqlite3ExprAffinity(pExpr);
  74181. if( aff1 && aff2 ){
  74182. /* Both sides of the comparison are columns. If one has numeric
  74183. ** affinity, use that. Otherwise use no affinity.
  74184. */
  74185. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  74186. return SQLITE_AFF_NUMERIC;
  74187. }else{
  74188. return SQLITE_AFF_NONE;
  74189. }
  74190. }else if( !aff1 && !aff2 ){
  74191. /* Neither side of the comparison is a column. Compare the
  74192. ** results directly.
  74193. */
  74194. return SQLITE_AFF_NONE;
  74195. }else{
  74196. /* One side is a column, the other is not. Use the columns affinity. */
  74197. assert( aff1==0 || aff2==0 );
  74198. return (aff1 + aff2);
  74199. }
  74200. }
  74201. /*
  74202. ** pExpr is a comparison operator. Return the type affinity that should
  74203. ** be applied to both operands prior to doing the comparison.
  74204. */
  74205. static char comparisonAffinity(Expr *pExpr){
  74206. char aff;
  74207. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  74208. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  74209. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  74210. assert( pExpr->pLeft );
  74211. aff = sqlite3ExprAffinity(pExpr->pLeft);
  74212. if( pExpr->pRight ){
  74213. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  74214. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74215. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  74216. }else if( !aff ){
  74217. aff = SQLITE_AFF_NONE;
  74218. }
  74219. return aff;
  74220. }
  74221. /*
  74222. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  74223. ** idx_affinity is the affinity of an indexed column. Return true
  74224. ** if the index with affinity idx_affinity may be used to implement
  74225. ** the comparison in pExpr.
  74226. */
  74227. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  74228. char aff = comparisonAffinity(pExpr);
  74229. switch( aff ){
  74230. case SQLITE_AFF_NONE:
  74231. return 1;
  74232. case SQLITE_AFF_TEXT:
  74233. return idx_affinity==SQLITE_AFF_TEXT;
  74234. default:
  74235. return sqlite3IsNumericAffinity(idx_affinity);
  74236. }
  74237. }
  74238. /*
  74239. ** Return the P5 value that should be used for a binary comparison
  74240. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  74241. */
  74242. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  74243. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  74244. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  74245. return aff;
  74246. }
  74247. /*
  74248. ** Return a pointer to the collation sequence that should be used by
  74249. ** a binary comparison operator comparing pLeft and pRight.
  74250. **
  74251. ** If the left hand expression has a collating sequence type, then it is
  74252. ** used. Otherwise the collation sequence for the right hand expression
  74253. ** is used, or the default (BINARY) if neither expression has a collating
  74254. ** type.
  74255. **
  74256. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  74257. ** it is not considered.
  74258. */
  74259. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  74260. Parse *pParse,
  74261. Expr *pLeft,
  74262. Expr *pRight
  74263. ){
  74264. CollSeq *pColl;
  74265. assert( pLeft );
  74266. if( pLeft->flags & EP_Collate ){
  74267. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  74268. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  74269. pColl = sqlite3ExprCollSeq(pParse, pRight);
  74270. }else{
  74271. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  74272. if( !pColl ){
  74273. pColl = sqlite3ExprCollSeq(pParse, pRight);
  74274. }
  74275. }
  74276. return pColl;
  74277. }
  74278. /*
  74279. ** Generate code for a comparison operator.
  74280. */
  74281. static int codeCompare(
  74282. Parse *pParse, /* The parsing (and code generating) context */
  74283. Expr *pLeft, /* The left operand */
  74284. Expr *pRight, /* The right operand */
  74285. int opcode, /* The comparison opcode */
  74286. int in1, int in2, /* Register holding operands */
  74287. int dest, /* Jump here if true. */
  74288. int jumpIfNull /* If true, jump if either operand is NULL */
  74289. ){
  74290. int p5;
  74291. int addr;
  74292. CollSeq *p4;
  74293. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  74294. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  74295. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  74296. (void*)p4, P4_COLLSEQ);
  74297. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  74298. return addr;
  74299. }
  74300. #if SQLITE_MAX_EXPR_DEPTH>0
  74301. /*
  74302. ** Check that argument nHeight is less than or equal to the maximum
  74303. ** expression depth allowed. If it is not, leave an error message in
  74304. ** pParse.
  74305. */
  74306. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  74307. int rc = SQLITE_OK;
  74308. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  74309. if( nHeight>mxHeight ){
  74310. sqlite3ErrorMsg(pParse,
  74311. "Expression tree is too large (maximum depth %d)", mxHeight
  74312. );
  74313. rc = SQLITE_ERROR;
  74314. }
  74315. return rc;
  74316. }
  74317. /* The following three functions, heightOfExpr(), heightOfExprList()
  74318. ** and heightOfSelect(), are used to determine the maximum height
  74319. ** of any expression tree referenced by the structure passed as the
  74320. ** first argument.
  74321. **
  74322. ** If this maximum height is greater than the current value pointed
  74323. ** to by pnHeight, the second parameter, then set *pnHeight to that
  74324. ** value.
  74325. */
  74326. static void heightOfExpr(Expr *p, int *pnHeight){
  74327. if( p ){
  74328. if( p->nHeight>*pnHeight ){
  74329. *pnHeight = p->nHeight;
  74330. }
  74331. }
  74332. }
  74333. static void heightOfExprList(ExprList *p, int *pnHeight){
  74334. if( p ){
  74335. int i;
  74336. for(i=0; i<p->nExpr; i++){
  74337. heightOfExpr(p->a[i].pExpr, pnHeight);
  74338. }
  74339. }
  74340. }
  74341. static void heightOfSelect(Select *p, int *pnHeight){
  74342. if( p ){
  74343. heightOfExpr(p->pWhere, pnHeight);
  74344. heightOfExpr(p->pHaving, pnHeight);
  74345. heightOfExpr(p->pLimit, pnHeight);
  74346. heightOfExpr(p->pOffset, pnHeight);
  74347. heightOfExprList(p->pEList, pnHeight);
  74348. heightOfExprList(p->pGroupBy, pnHeight);
  74349. heightOfExprList(p->pOrderBy, pnHeight);
  74350. heightOfSelect(p->pPrior, pnHeight);
  74351. }
  74352. }
  74353. /*
  74354. ** Set the Expr.nHeight variable in the structure passed as an
  74355. ** argument. An expression with no children, Expr.pList or
  74356. ** Expr.pSelect member has a height of 1. Any other expression
  74357. ** has a height equal to the maximum height of any other
  74358. ** referenced Expr plus one.
  74359. */
  74360. static void exprSetHeight(Expr *p){
  74361. int nHeight = 0;
  74362. heightOfExpr(p->pLeft, &nHeight);
  74363. heightOfExpr(p->pRight, &nHeight);
  74364. if( ExprHasProperty(p, EP_xIsSelect) ){
  74365. heightOfSelect(p->x.pSelect, &nHeight);
  74366. }else{
  74367. heightOfExprList(p->x.pList, &nHeight);
  74368. }
  74369. p->nHeight = nHeight + 1;
  74370. }
  74371. /*
  74372. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  74373. ** the height is greater than the maximum allowed expression depth,
  74374. ** leave an error in pParse.
  74375. */
  74376. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  74377. exprSetHeight(p);
  74378. sqlite3ExprCheckHeight(pParse, p->nHeight);
  74379. }
  74380. /*
  74381. ** Return the maximum height of any expression tree referenced
  74382. ** by the select statement passed as an argument.
  74383. */
  74384. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  74385. int nHeight = 0;
  74386. heightOfSelect(p, &nHeight);
  74387. return nHeight;
  74388. }
  74389. #else
  74390. #define exprSetHeight(y)
  74391. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  74392. /*
  74393. ** This routine is the core allocator for Expr nodes.
  74394. **
  74395. ** Construct a new expression node and return a pointer to it. Memory
  74396. ** for this node and for the pToken argument is a single allocation
  74397. ** obtained from sqlite3DbMalloc(). The calling function
  74398. ** is responsible for making sure the node eventually gets freed.
  74399. **
  74400. ** If dequote is true, then the token (if it exists) is dequoted.
  74401. ** If dequote is false, no dequoting is performance. The deQuote
  74402. ** parameter is ignored if pToken is NULL or if the token does not
  74403. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  74404. ** then the EP_DblQuoted flag is set on the expression node.
  74405. **
  74406. ** Special case: If op==TK_INTEGER and pToken points to a string that
  74407. ** can be translated into a 32-bit integer, then the token is not
  74408. ** stored in u.zToken. Instead, the integer values is written
  74409. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  74410. ** is allocated to hold the integer text and the dequote flag is ignored.
  74411. */
  74412. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  74413. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  74414. int op, /* Expression opcode */
  74415. const Token *pToken, /* Token argument. Might be NULL */
  74416. int dequote /* True to dequote */
  74417. ){
  74418. Expr *pNew;
  74419. int nExtra = 0;
  74420. int iValue = 0;
  74421. if( pToken ){
  74422. if( op!=TK_INTEGER || pToken->z==0
  74423. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  74424. nExtra = pToken->n+1;
  74425. assert( iValue>=0 );
  74426. }
  74427. }
  74428. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  74429. if( pNew ){
  74430. pNew->op = (u8)op;
  74431. pNew->iAgg = -1;
  74432. if( pToken ){
  74433. if( nExtra==0 ){
  74434. pNew->flags |= EP_IntValue;
  74435. pNew->u.iValue = iValue;
  74436. }else{
  74437. int c;
  74438. pNew->u.zToken = (char*)&pNew[1];
  74439. assert( pToken->z!=0 || pToken->n==0 );
  74440. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  74441. pNew->u.zToken[pToken->n] = 0;
  74442. if( dequote && nExtra>=3
  74443. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  74444. sqlite3Dequote(pNew->u.zToken);
  74445. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  74446. }
  74447. }
  74448. }
  74449. #if SQLITE_MAX_EXPR_DEPTH>0
  74450. pNew->nHeight = 1;
  74451. #endif
  74452. }
  74453. return pNew;
  74454. }
  74455. /*
  74456. ** Allocate a new expression node from a zero-terminated token that has
  74457. ** already been dequoted.
  74458. */
  74459. SQLITE_PRIVATE Expr *sqlite3Expr(
  74460. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  74461. int op, /* Expression opcode */
  74462. const char *zToken /* Token argument. Might be NULL */
  74463. ){
  74464. Token x;
  74465. x.z = zToken;
  74466. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  74467. return sqlite3ExprAlloc(db, op, &x, 0);
  74468. }
  74469. /*
  74470. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  74471. **
  74472. ** If pRoot==NULL that means that a memory allocation error has occurred.
  74473. ** In that case, delete the subtrees pLeft and pRight.
  74474. */
  74475. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  74476. sqlite3 *db,
  74477. Expr *pRoot,
  74478. Expr *pLeft,
  74479. Expr *pRight
  74480. ){
  74481. if( pRoot==0 ){
  74482. assert( db->mallocFailed );
  74483. sqlite3ExprDelete(db, pLeft);
  74484. sqlite3ExprDelete(db, pRight);
  74485. }else{
  74486. if( pRight ){
  74487. pRoot->pRight = pRight;
  74488. pRoot->flags |= EP_Collate & pRight->flags;
  74489. }
  74490. if( pLeft ){
  74491. pRoot->pLeft = pLeft;
  74492. pRoot->flags |= EP_Collate & pLeft->flags;
  74493. }
  74494. exprSetHeight(pRoot);
  74495. }
  74496. }
  74497. /*
  74498. ** Allocate a Expr node which joins as many as two subtrees.
  74499. **
  74500. ** One or both of the subtrees can be NULL. Return a pointer to the new
  74501. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  74502. ** free the subtrees and return NULL.
  74503. */
  74504. SQLITE_PRIVATE Expr *sqlite3PExpr(
  74505. Parse *pParse, /* Parsing context */
  74506. int op, /* Expression opcode */
  74507. Expr *pLeft, /* Left operand */
  74508. Expr *pRight, /* Right operand */
  74509. const Token *pToken /* Argument token */
  74510. ){
  74511. Expr *p;
  74512. if( op==TK_AND && pLeft && pRight ){
  74513. /* Take advantage of short-circuit false optimization for AND */
  74514. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  74515. }else{
  74516. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  74517. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  74518. }
  74519. if( p ) {
  74520. sqlite3ExprCheckHeight(pParse, p->nHeight);
  74521. }
  74522. return p;
  74523. }
  74524. /*
  74525. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  74526. ** expression might be true. This is an optimization. If is OK to
  74527. ** return 0 here even if the expression really is always false (a
  74528. ** false negative). But it is a bug to return 1 if the expression
  74529. ** might be true in some rare circumstances (a false positive.)
  74530. **
  74531. ** Note that if the expression is part of conditional for a
  74532. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  74533. ** is it true or false, so always return 0.
  74534. */
  74535. static int exprAlwaysFalse(Expr *p){
  74536. int v = 0;
  74537. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  74538. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  74539. return v==0;
  74540. }
  74541. /*
  74542. ** Join two expressions using an AND operator. If either expression is
  74543. ** NULL, then just return the other expression.
  74544. **
  74545. ** If one side or the other of the AND is known to be false, then instead
  74546. ** of returning an AND expression, just return a constant expression with
  74547. ** a value of false.
  74548. */
  74549. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  74550. if( pLeft==0 ){
  74551. return pRight;
  74552. }else if( pRight==0 ){
  74553. return pLeft;
  74554. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  74555. sqlite3ExprDelete(db, pLeft);
  74556. sqlite3ExprDelete(db, pRight);
  74557. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  74558. }else{
  74559. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  74560. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  74561. return pNew;
  74562. }
  74563. }
  74564. /*
  74565. ** Construct a new expression node for a function with multiple
  74566. ** arguments.
  74567. */
  74568. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  74569. Expr *pNew;
  74570. sqlite3 *db = pParse->db;
  74571. assert( pToken );
  74572. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  74573. if( pNew==0 ){
  74574. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  74575. return 0;
  74576. }
  74577. pNew->x.pList = pList;
  74578. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  74579. sqlite3ExprSetHeight(pParse, pNew);
  74580. return pNew;
  74581. }
  74582. /*
  74583. ** Assign a variable number to an expression that encodes a wildcard
  74584. ** in the original SQL statement.
  74585. **
  74586. ** Wildcards consisting of a single "?" are assigned the next sequential
  74587. ** variable number.
  74588. **
  74589. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  74590. ** sure "nnn" is not too be to avoid a denial of service attack when
  74591. ** the SQL statement comes from an external source.
  74592. **
  74593. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  74594. ** as the previous instance of the same wildcard. Or if this is the first
  74595. ** instance of the wildcard, the next sequenial variable number is
  74596. ** assigned.
  74597. */
  74598. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  74599. sqlite3 *db = pParse->db;
  74600. const char *z;
  74601. if( pExpr==0 ) return;
  74602. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  74603. z = pExpr->u.zToken;
  74604. assert( z!=0 );
  74605. assert( z[0]!=0 );
  74606. if( z[1]==0 ){
  74607. /* Wildcard of the form "?". Assign the next variable number */
  74608. assert( z[0]=='?' );
  74609. pExpr->iColumn = (ynVar)(++pParse->nVar);
  74610. }else{
  74611. ynVar x = 0;
  74612. u32 n = sqlite3Strlen30(z);
  74613. if( z[0]=='?' ){
  74614. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  74615. ** use it as the variable number */
  74616. i64 i;
  74617. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  74618. pExpr->iColumn = x = (ynVar)i;
  74619. testcase( i==0 );
  74620. testcase( i==1 );
  74621. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  74622. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  74623. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  74624. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  74625. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  74626. x = 0;
  74627. }
  74628. if( i>pParse->nVar ){
  74629. pParse->nVar = (int)i;
  74630. }
  74631. }else{
  74632. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  74633. ** number as the prior appearance of the same name, or if the name
  74634. ** has never appeared before, reuse the same variable number
  74635. */
  74636. ynVar i;
  74637. for(i=0; i<pParse->nzVar; i++){
  74638. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  74639. pExpr->iColumn = x = (ynVar)i+1;
  74640. break;
  74641. }
  74642. }
  74643. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  74644. }
  74645. if( x>0 ){
  74646. if( x>pParse->nzVar ){
  74647. char **a;
  74648. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  74649. if( a==0 ) return; /* Error reported through db->mallocFailed */
  74650. pParse->azVar = a;
  74651. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  74652. pParse->nzVar = x;
  74653. }
  74654. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  74655. sqlite3DbFree(db, pParse->azVar[x-1]);
  74656. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  74657. }
  74658. }
  74659. }
  74660. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  74661. sqlite3ErrorMsg(pParse, "too many SQL variables");
  74662. }
  74663. }
  74664. /*
  74665. ** Recursively delete an expression tree.
  74666. */
  74667. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  74668. if( p==0 ) return;
  74669. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  74670. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  74671. if( !ExprHasProperty(p, EP_TokenOnly) ){
  74672. /* The Expr.x union is never used at the same time as Expr.pRight */
  74673. assert( p->x.pList==0 || p->pRight==0 );
  74674. sqlite3ExprDelete(db, p->pLeft);
  74675. sqlite3ExprDelete(db, p->pRight);
  74676. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  74677. if( ExprHasProperty(p, EP_xIsSelect) ){
  74678. sqlite3SelectDelete(db, p->x.pSelect);
  74679. }else{
  74680. sqlite3ExprListDelete(db, p->x.pList);
  74681. }
  74682. }
  74683. if( !ExprHasProperty(p, EP_Static) ){
  74684. sqlite3DbFree(db, p);
  74685. }
  74686. }
  74687. /*
  74688. ** Return the number of bytes allocated for the expression structure
  74689. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  74690. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  74691. */
  74692. static int exprStructSize(Expr *p){
  74693. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  74694. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  74695. return EXPR_FULLSIZE;
  74696. }
  74697. /*
  74698. ** The dupedExpr*Size() routines each return the number of bytes required
  74699. ** to store a copy of an expression or expression tree. They differ in
  74700. ** how much of the tree is measured.
  74701. **
  74702. ** dupedExprStructSize() Size of only the Expr structure
  74703. ** dupedExprNodeSize() Size of Expr + space for token
  74704. ** dupedExprSize() Expr + token + subtree components
  74705. **
  74706. ***************************************************************************
  74707. **
  74708. ** The dupedExprStructSize() function returns two values OR-ed together:
  74709. ** (1) the space required for a copy of the Expr structure only and
  74710. ** (2) the EP_xxx flags that indicate what the structure size should be.
  74711. ** The return values is always one of:
  74712. **
  74713. ** EXPR_FULLSIZE
  74714. ** EXPR_REDUCEDSIZE | EP_Reduced
  74715. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  74716. **
  74717. ** The size of the structure can be found by masking the return value
  74718. ** of this routine with 0xfff. The flags can be found by masking the
  74719. ** return value with EP_Reduced|EP_TokenOnly.
  74720. **
  74721. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  74722. ** (unreduced) Expr objects as they or originally constructed by the parser.
  74723. ** During expression analysis, extra information is computed and moved into
  74724. ** later parts of teh Expr object and that extra information might get chopped
  74725. ** off if the expression is reduced. Note also that it does not work to
  74726. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  74727. ** to reduce a pristine expression tree from the parser. The implementation
  74728. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  74729. ** to enforce this constraint.
  74730. */
  74731. static int dupedExprStructSize(Expr *p, int flags){
  74732. int nSize;
  74733. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  74734. assert( EXPR_FULLSIZE<=0xfff );
  74735. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  74736. if( 0==(flags&EXPRDUP_REDUCE) ){
  74737. nSize = EXPR_FULLSIZE;
  74738. }else{
  74739. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  74740. assert( !ExprHasProperty(p, EP_FromJoin) );
  74741. assert( !ExprHasProperty(p, EP_MemToken) );
  74742. assert( !ExprHasProperty(p, EP_NoReduce) );
  74743. if( p->pLeft || p->x.pList ){
  74744. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  74745. }else{
  74746. assert( p->pRight==0 );
  74747. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  74748. }
  74749. }
  74750. return nSize;
  74751. }
  74752. /*
  74753. ** This function returns the space in bytes required to store the copy
  74754. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  74755. ** string is defined.)
  74756. */
  74757. static int dupedExprNodeSize(Expr *p, int flags){
  74758. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  74759. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  74760. nByte += sqlite3Strlen30(p->u.zToken)+1;
  74761. }
  74762. return ROUND8(nByte);
  74763. }
  74764. /*
  74765. ** Return the number of bytes required to create a duplicate of the
  74766. ** expression passed as the first argument. The second argument is a
  74767. ** mask containing EXPRDUP_XXX flags.
  74768. **
  74769. ** The value returned includes space to create a copy of the Expr struct
  74770. ** itself and the buffer referred to by Expr.u.zToken, if any.
  74771. **
  74772. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  74773. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  74774. ** and Expr.pRight variables (but not for any structures pointed to or
  74775. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  74776. */
  74777. static int dupedExprSize(Expr *p, int flags){
  74778. int nByte = 0;
  74779. if( p ){
  74780. nByte = dupedExprNodeSize(p, flags);
  74781. if( flags&EXPRDUP_REDUCE ){
  74782. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  74783. }
  74784. }
  74785. return nByte;
  74786. }
  74787. /*
  74788. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  74789. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  74790. ** to store the copy of expression p, the copies of p->u.zToken
  74791. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  74792. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  74793. ** portion of the buffer copied into by this function.
  74794. */
  74795. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  74796. Expr *pNew = 0; /* Value to return */
  74797. if( p ){
  74798. const int isReduced = (flags&EXPRDUP_REDUCE);
  74799. u8 *zAlloc;
  74800. u32 staticFlag = 0;
  74801. assert( pzBuffer==0 || isReduced );
  74802. /* Figure out where to write the new Expr structure. */
  74803. if( pzBuffer ){
  74804. zAlloc = *pzBuffer;
  74805. staticFlag = EP_Static;
  74806. }else{
  74807. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  74808. }
  74809. pNew = (Expr *)zAlloc;
  74810. if( pNew ){
  74811. /* Set nNewSize to the size allocated for the structure pointed to
  74812. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  74813. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  74814. ** by the copy of the p->u.zToken string (if any).
  74815. */
  74816. const unsigned nStructSize = dupedExprStructSize(p, flags);
  74817. const int nNewSize = nStructSize & 0xfff;
  74818. int nToken;
  74819. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  74820. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  74821. }else{
  74822. nToken = 0;
  74823. }
  74824. if( isReduced ){
  74825. assert( ExprHasProperty(p, EP_Reduced)==0 );
  74826. memcpy(zAlloc, p, nNewSize);
  74827. }else{
  74828. int nSize = exprStructSize(p);
  74829. memcpy(zAlloc, p, nSize);
  74830. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  74831. }
  74832. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  74833. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  74834. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  74835. pNew->flags |= staticFlag;
  74836. /* Copy the p->u.zToken string, if any. */
  74837. if( nToken ){
  74838. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  74839. memcpy(zToken, p->u.zToken, nToken);
  74840. }
  74841. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  74842. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  74843. if( ExprHasProperty(p, EP_xIsSelect) ){
  74844. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  74845. }else{
  74846. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  74847. }
  74848. }
  74849. /* Fill in pNew->pLeft and pNew->pRight. */
  74850. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  74851. zAlloc += dupedExprNodeSize(p, flags);
  74852. if( ExprHasProperty(pNew, EP_Reduced) ){
  74853. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  74854. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  74855. }
  74856. if( pzBuffer ){
  74857. *pzBuffer = zAlloc;
  74858. }
  74859. }else{
  74860. if( !ExprHasProperty(p, EP_TokenOnly) ){
  74861. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  74862. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  74863. }
  74864. }
  74865. }
  74866. }
  74867. return pNew;
  74868. }
  74869. /*
  74870. ** The following group of routines make deep copies of expressions,
  74871. ** expression lists, ID lists, and select statements. The copies can
  74872. ** be deleted (by being passed to their respective ...Delete() routines)
  74873. ** without effecting the originals.
  74874. **
  74875. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  74876. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  74877. ** by subsequent calls to sqlite*ListAppend() routines.
  74878. **
  74879. ** Any tables that the SrcList might point to are not duplicated.
  74880. **
  74881. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  74882. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  74883. ** truncated version of the usual Expr structure that will be stored as
  74884. ** part of the in-memory representation of the database schema.
  74885. */
  74886. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  74887. return exprDup(db, p, flags, 0);
  74888. }
  74889. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  74890. ExprList *pNew;
  74891. struct ExprList_item *pItem, *pOldItem;
  74892. int i;
  74893. if( p==0 ) return 0;
  74894. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  74895. if( pNew==0 ) return 0;
  74896. pNew->iECursor = 0;
  74897. pNew->nExpr = i = p->nExpr;
  74898. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  74899. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  74900. if( pItem==0 ){
  74901. sqlite3DbFree(db, pNew);
  74902. return 0;
  74903. }
  74904. pOldItem = p->a;
  74905. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  74906. Expr *pOldExpr = pOldItem->pExpr;
  74907. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  74908. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74909. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  74910. pItem->sortOrder = pOldItem->sortOrder;
  74911. pItem->done = 0;
  74912. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  74913. pItem->iOrderByCol = pOldItem->iOrderByCol;
  74914. pItem->iAlias = pOldItem->iAlias;
  74915. }
  74916. return pNew;
  74917. }
  74918. /*
  74919. ** If cursors, triggers, views and subqueries are all omitted from
  74920. ** the build, then none of the following routines, except for
  74921. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  74922. ** called with a NULL argument.
  74923. */
  74924. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  74925. || !defined(SQLITE_OMIT_SUBQUERY)
  74926. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  74927. SrcList *pNew;
  74928. int i;
  74929. int nByte;
  74930. if( p==0 ) return 0;
  74931. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  74932. pNew = sqlite3DbMallocRaw(db, nByte );
  74933. if( pNew==0 ) return 0;
  74934. pNew->nSrc = pNew->nAlloc = p->nSrc;
  74935. for(i=0; i<p->nSrc; i++){
  74936. struct SrcList_item *pNewItem = &pNew->a[i];
  74937. struct SrcList_item *pOldItem = &p->a[i];
  74938. Table *pTab;
  74939. pNewItem->pSchema = pOldItem->pSchema;
  74940. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  74941. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74942. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  74943. pNewItem->jointype = pOldItem->jointype;
  74944. pNewItem->iCursor = pOldItem->iCursor;
  74945. pNewItem->addrFillSub = pOldItem->addrFillSub;
  74946. pNewItem->regReturn = pOldItem->regReturn;
  74947. pNewItem->isCorrelated = pOldItem->isCorrelated;
  74948. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  74949. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  74950. pNewItem->notIndexed = pOldItem->notIndexed;
  74951. pNewItem->pIndex = pOldItem->pIndex;
  74952. pTab = pNewItem->pTab = pOldItem->pTab;
  74953. if( pTab ){
  74954. pTab->nRef++;
  74955. }
  74956. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  74957. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  74958. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  74959. pNewItem->colUsed = pOldItem->colUsed;
  74960. }
  74961. return pNew;
  74962. }
  74963. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  74964. IdList *pNew;
  74965. int i;
  74966. if( p==0 ) return 0;
  74967. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  74968. if( pNew==0 ) return 0;
  74969. pNew->nId = p->nId;
  74970. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  74971. if( pNew->a==0 ){
  74972. sqlite3DbFree(db, pNew);
  74973. return 0;
  74974. }
  74975. /* Note that because the size of the allocation for p->a[] is not
  74976. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  74977. ** on the duplicate created by this function. */
  74978. for(i=0; i<p->nId; i++){
  74979. struct IdList_item *pNewItem = &pNew->a[i];
  74980. struct IdList_item *pOldItem = &p->a[i];
  74981. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74982. pNewItem->idx = pOldItem->idx;
  74983. }
  74984. return pNew;
  74985. }
  74986. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  74987. Select *pNew, *pPrior;
  74988. if( p==0 ) return 0;
  74989. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  74990. if( pNew==0 ) return 0;
  74991. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  74992. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  74993. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  74994. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  74995. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  74996. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  74997. pNew->op = p->op;
  74998. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  74999. if( pPrior ) pPrior->pNext = pNew;
  75000. pNew->pNext = 0;
  75001. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  75002. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  75003. pNew->iLimit = 0;
  75004. pNew->iOffset = 0;
  75005. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  75006. pNew->pRightmost = 0;
  75007. pNew->addrOpenEphm[0] = -1;
  75008. pNew->addrOpenEphm[1] = -1;
  75009. pNew->addrOpenEphm[2] = -1;
  75010. return pNew;
  75011. }
  75012. #else
  75013. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  75014. assert( p==0 );
  75015. return 0;
  75016. }
  75017. #endif
  75018. /*
  75019. ** Add a new element to the end of an expression list. If pList is
  75020. ** initially NULL, then create a new expression list.
  75021. **
  75022. ** If a memory allocation error occurs, the entire list is freed and
  75023. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  75024. ** that the new entry was successfully appended.
  75025. */
  75026. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  75027. Parse *pParse, /* Parsing context */
  75028. ExprList *pList, /* List to which to append. Might be NULL */
  75029. Expr *pExpr /* Expression to be appended. Might be NULL */
  75030. ){
  75031. sqlite3 *db = pParse->db;
  75032. if( pList==0 ){
  75033. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  75034. if( pList==0 ){
  75035. goto no_mem;
  75036. }
  75037. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  75038. if( pList->a==0 ) goto no_mem;
  75039. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  75040. struct ExprList_item *a;
  75041. assert( pList->nExpr>0 );
  75042. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  75043. if( a==0 ){
  75044. goto no_mem;
  75045. }
  75046. pList->a = a;
  75047. }
  75048. assert( pList->a!=0 );
  75049. if( 1 ){
  75050. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  75051. memset(pItem, 0, sizeof(*pItem));
  75052. pItem->pExpr = pExpr;
  75053. }
  75054. return pList;
  75055. no_mem:
  75056. /* Avoid leaking memory if malloc has failed. */
  75057. sqlite3ExprDelete(db, pExpr);
  75058. sqlite3ExprListDelete(db, pList);
  75059. return 0;
  75060. }
  75061. /*
  75062. ** Set the ExprList.a[].zName element of the most recently added item
  75063. ** on the expression list.
  75064. **
  75065. ** pList might be NULL following an OOM error. But pName should never be
  75066. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  75067. ** is set.
  75068. */
  75069. SQLITE_PRIVATE void sqlite3ExprListSetName(
  75070. Parse *pParse, /* Parsing context */
  75071. ExprList *pList, /* List to which to add the span. */
  75072. Token *pName, /* Name to be added */
  75073. int dequote /* True to cause the name to be dequoted */
  75074. ){
  75075. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  75076. if( pList ){
  75077. struct ExprList_item *pItem;
  75078. assert( pList->nExpr>0 );
  75079. pItem = &pList->a[pList->nExpr-1];
  75080. assert( pItem->zName==0 );
  75081. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  75082. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  75083. }
  75084. }
  75085. /*
  75086. ** Set the ExprList.a[].zSpan element of the most recently added item
  75087. ** on the expression list.
  75088. **
  75089. ** pList might be NULL following an OOM error. But pSpan should never be
  75090. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  75091. ** is set.
  75092. */
  75093. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  75094. Parse *pParse, /* Parsing context */
  75095. ExprList *pList, /* List to which to add the span. */
  75096. ExprSpan *pSpan /* The span to be added */
  75097. ){
  75098. sqlite3 *db = pParse->db;
  75099. assert( pList!=0 || db->mallocFailed!=0 );
  75100. if( pList ){
  75101. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  75102. assert( pList->nExpr>0 );
  75103. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  75104. sqlite3DbFree(db, pItem->zSpan);
  75105. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  75106. (int)(pSpan->zEnd - pSpan->zStart));
  75107. }
  75108. }
  75109. /*
  75110. ** If the expression list pEList contains more than iLimit elements,
  75111. ** leave an error message in pParse.
  75112. */
  75113. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  75114. Parse *pParse,
  75115. ExprList *pEList,
  75116. const char *zObject
  75117. ){
  75118. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  75119. testcase( pEList && pEList->nExpr==mx );
  75120. testcase( pEList && pEList->nExpr==mx+1 );
  75121. if( pEList && pEList->nExpr>mx ){
  75122. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  75123. }
  75124. }
  75125. /*
  75126. ** Delete an entire expression list.
  75127. */
  75128. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  75129. int i;
  75130. struct ExprList_item *pItem;
  75131. if( pList==0 ) return;
  75132. assert( pList->a!=0 || pList->nExpr==0 );
  75133. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  75134. sqlite3ExprDelete(db, pItem->pExpr);
  75135. sqlite3DbFree(db, pItem->zName);
  75136. sqlite3DbFree(db, pItem->zSpan);
  75137. }
  75138. sqlite3DbFree(db, pList->a);
  75139. sqlite3DbFree(db, pList);
  75140. }
  75141. /*
  75142. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  75143. ** to an integer. These routines are checking an expression to see
  75144. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  75145. ** not constant.
  75146. **
  75147. ** These callback routines are used to implement the following:
  75148. **
  75149. ** sqlite3ExprIsConstant()
  75150. ** sqlite3ExprIsConstantNotJoin()
  75151. ** sqlite3ExprIsConstantOrFunction()
  75152. **
  75153. */
  75154. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  75155. /* If pWalker->u.i is 3 then any term of the expression that comes from
  75156. ** the ON or USING clauses of a join disqualifies the expression
  75157. ** from being considered constant. */
  75158. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  75159. pWalker->u.i = 0;
  75160. return WRC_Abort;
  75161. }
  75162. switch( pExpr->op ){
  75163. /* Consider functions to be constant if all their arguments are constant
  75164. ** and pWalker->u.i==2 */
  75165. case TK_FUNCTION:
  75166. if( pWalker->u.i==2 ) return 0;
  75167. /* Fall through */
  75168. case TK_ID:
  75169. case TK_COLUMN:
  75170. case TK_AGG_FUNCTION:
  75171. case TK_AGG_COLUMN:
  75172. testcase( pExpr->op==TK_ID );
  75173. testcase( pExpr->op==TK_COLUMN );
  75174. testcase( pExpr->op==TK_AGG_FUNCTION );
  75175. testcase( pExpr->op==TK_AGG_COLUMN );
  75176. pWalker->u.i = 0;
  75177. return WRC_Abort;
  75178. default:
  75179. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  75180. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  75181. return WRC_Continue;
  75182. }
  75183. }
  75184. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  75185. UNUSED_PARAMETER(NotUsed);
  75186. pWalker->u.i = 0;
  75187. return WRC_Abort;
  75188. }
  75189. static int exprIsConst(Expr *p, int initFlag){
  75190. Walker w;
  75191. memset(&w, 0, sizeof(w));
  75192. w.u.i = initFlag;
  75193. w.xExprCallback = exprNodeIsConstant;
  75194. w.xSelectCallback = selectNodeIsConstant;
  75195. sqlite3WalkExpr(&w, p);
  75196. return w.u.i;
  75197. }
  75198. /*
  75199. ** Walk an expression tree. Return 1 if the expression is constant
  75200. ** and 0 if it involves variables or function calls.
  75201. **
  75202. ** For the purposes of this function, a double-quoted string (ex: "abc")
  75203. ** is considered a variable but a single-quoted string (ex: 'abc') is
  75204. ** a constant.
  75205. */
  75206. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  75207. return exprIsConst(p, 1);
  75208. }
  75209. /*
  75210. ** Walk an expression tree. Return 1 if the expression is constant
  75211. ** that does no originate from the ON or USING clauses of a join.
  75212. ** Return 0 if it involves variables or function calls or terms from
  75213. ** an ON or USING clause.
  75214. */
  75215. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  75216. return exprIsConst(p, 3);
  75217. }
  75218. /*
  75219. ** Walk an expression tree. Return 1 if the expression is constant
  75220. ** or a function call with constant arguments. Return and 0 if there
  75221. ** are any variables.
  75222. **
  75223. ** For the purposes of this function, a double-quoted string (ex: "abc")
  75224. ** is considered a variable but a single-quoted string (ex: 'abc') is
  75225. ** a constant.
  75226. */
  75227. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  75228. return exprIsConst(p, 2);
  75229. }
  75230. /*
  75231. ** If the expression p codes a constant integer that is small enough
  75232. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  75233. ** in *pValue. If the expression is not an integer or if it is too big
  75234. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  75235. */
  75236. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  75237. int rc = 0;
  75238. /* If an expression is an integer literal that fits in a signed 32-bit
  75239. ** integer, then the EP_IntValue flag will have already been set */
  75240. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  75241. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  75242. if( p->flags & EP_IntValue ){
  75243. *pValue = p->u.iValue;
  75244. return 1;
  75245. }
  75246. switch( p->op ){
  75247. case TK_UPLUS: {
  75248. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  75249. break;
  75250. }
  75251. case TK_UMINUS: {
  75252. int v;
  75253. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  75254. assert( v!=(-2147483647-1) );
  75255. *pValue = -v;
  75256. rc = 1;
  75257. }
  75258. break;
  75259. }
  75260. default: break;
  75261. }
  75262. return rc;
  75263. }
  75264. /*
  75265. ** Return FALSE if there is no chance that the expression can be NULL.
  75266. **
  75267. ** If the expression might be NULL or if the expression is too complex
  75268. ** to tell return TRUE.
  75269. **
  75270. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  75271. ** when we know that a value cannot be NULL. Hence, a false positive
  75272. ** (returning TRUE when in fact the expression can never be NULL) might
  75273. ** be a small performance hit but is otherwise harmless. On the other
  75274. ** hand, a false negative (returning FALSE when the result could be NULL)
  75275. ** will likely result in an incorrect answer. So when in doubt, return
  75276. ** TRUE.
  75277. */
  75278. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  75279. u8 op;
  75280. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  75281. op = p->op;
  75282. if( op==TK_REGISTER ) op = p->op2;
  75283. switch( op ){
  75284. case TK_INTEGER:
  75285. case TK_STRING:
  75286. case TK_FLOAT:
  75287. case TK_BLOB:
  75288. return 0;
  75289. default:
  75290. return 1;
  75291. }
  75292. }
  75293. /*
  75294. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  75295. ** to location iDest if the value in iReg is NULL. The value in iReg
  75296. ** was computed by pExpr. If we can look at pExpr at compile-time and
  75297. ** determine that it can never generate a NULL, then the OP_IsNull operation
  75298. ** can be omitted.
  75299. */
  75300. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  75301. Vdbe *v, /* The VDBE under construction */
  75302. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  75303. int iReg, /* Test the value in this register for NULL */
  75304. int iDest /* Jump here if the value is null */
  75305. ){
  75306. if( sqlite3ExprCanBeNull(pExpr) ){
  75307. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  75308. }
  75309. }
  75310. /*
  75311. ** Return TRUE if the given expression is a constant which would be
  75312. ** unchanged by OP_Affinity with the affinity given in the second
  75313. ** argument.
  75314. **
  75315. ** This routine is used to determine if the OP_Affinity operation
  75316. ** can be omitted. When in doubt return FALSE. A false negative
  75317. ** is harmless. A false positive, however, can result in the wrong
  75318. ** answer.
  75319. */
  75320. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  75321. u8 op;
  75322. if( aff==SQLITE_AFF_NONE ) return 1;
  75323. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  75324. op = p->op;
  75325. if( op==TK_REGISTER ) op = p->op2;
  75326. switch( op ){
  75327. case TK_INTEGER: {
  75328. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  75329. }
  75330. case TK_FLOAT: {
  75331. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  75332. }
  75333. case TK_STRING: {
  75334. return aff==SQLITE_AFF_TEXT;
  75335. }
  75336. case TK_BLOB: {
  75337. return 1;
  75338. }
  75339. case TK_COLUMN: {
  75340. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  75341. return p->iColumn<0
  75342. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  75343. }
  75344. default: {
  75345. return 0;
  75346. }
  75347. }
  75348. }
  75349. /*
  75350. ** Return TRUE if the given string is a row-id column name.
  75351. */
  75352. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  75353. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  75354. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  75355. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  75356. return 0;
  75357. }
  75358. /*
  75359. ** Return true if we are able to the IN operator optimization on a
  75360. ** query of the form
  75361. **
  75362. ** x IN (SELECT ...)
  75363. **
  75364. ** Where the SELECT... clause is as specified by the parameter to this
  75365. ** routine.
  75366. **
  75367. ** The Select object passed in has already been preprocessed and no
  75368. ** errors have been found.
  75369. */
  75370. #ifndef SQLITE_OMIT_SUBQUERY
  75371. static int isCandidateForInOpt(Select *p){
  75372. SrcList *pSrc;
  75373. ExprList *pEList;
  75374. Table *pTab;
  75375. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  75376. if( p->pPrior ) return 0; /* Not a compound SELECT */
  75377. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  75378. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  75379. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  75380. return 0; /* No DISTINCT keyword and no aggregate functions */
  75381. }
  75382. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  75383. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  75384. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  75385. if( p->pWhere ) return 0; /* Has no WHERE clause */
  75386. pSrc = p->pSrc;
  75387. assert( pSrc!=0 );
  75388. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  75389. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  75390. pTab = pSrc->a[0].pTab;
  75391. if( NEVER(pTab==0) ) return 0;
  75392. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  75393. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  75394. pEList = p->pEList;
  75395. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  75396. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  75397. return 1;
  75398. }
  75399. #endif /* SQLITE_OMIT_SUBQUERY */
  75400. /*
  75401. ** Code an OP_Once instruction and allocate space for its flag. Return the
  75402. ** address of the new instruction.
  75403. */
  75404. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  75405. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  75406. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  75407. }
  75408. /*
  75409. ** This function is used by the implementation of the IN (...) operator.
  75410. ** The pX parameter is the expression on the RHS of the IN operator, which
  75411. ** might be either a list of expressions or a subquery.
  75412. **
  75413. ** The job of this routine is to find or create a b-tree object that can
  75414. ** be used either to test for membership in the RHS set or to iterate through
  75415. ** all members of the RHS set, skipping duplicates.
  75416. **
  75417. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  75418. ** and pX->iTable is set to the index of that cursor.
  75419. **
  75420. ** The returned value of this function indicates the b-tree type, as follows:
  75421. **
  75422. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  75423. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  75424. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  75425. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  75426. ** populated epheremal table.
  75427. **
  75428. ** An existing b-tree might be used if the RHS expression pX is a simple
  75429. ** subquery such as:
  75430. **
  75431. ** SELECT <column> FROM <table>
  75432. **
  75433. ** If the RHS of the IN operator is a list or a more complex subquery, then
  75434. ** an ephemeral table might need to be generated from the RHS and then
  75435. ** pX->iTable made to point to the ephermeral table instead of an
  75436. ** existing table.
  75437. **
  75438. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  75439. ** through the set members, skipping any duplicates. In this case an
  75440. ** epheremal table must be used unless the selected <column> is guaranteed
  75441. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  75442. ** has a UNIQUE constraint or UNIQUE index.
  75443. **
  75444. ** If the prNotFound parameter is not 0, then the b-tree will be used
  75445. ** for fast set membership tests. In this case an epheremal table must
  75446. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  75447. ** be found with <column> as its left-most column.
  75448. **
  75449. ** When the b-tree is being used for membership tests, the calling function
  75450. ** needs to know whether or not the structure contains an SQL NULL
  75451. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  75452. ** If there is any chance that the (...) might contain a NULL value at
  75453. ** runtime, then a register is allocated and the register number written
  75454. ** to *prNotFound. If there is no chance that the (...) contains a
  75455. ** NULL value, then *prNotFound is left unchanged.
  75456. **
  75457. ** If a register is allocated and its location stored in *prNotFound, then
  75458. ** its initial value is NULL. If the (...) does not remain constant
  75459. ** for the duration of the query (i.e. the SELECT within the (...)
  75460. ** is a correlated subquery) then the value of the allocated register is
  75461. ** reset to NULL each time the subquery is rerun. This allows the
  75462. ** caller to use vdbe code equivalent to the following:
  75463. **
  75464. ** if( register==NULL ){
  75465. ** has_null = <test if data structure contains null>
  75466. ** register = 1
  75467. ** }
  75468. **
  75469. ** in order to avoid running the <test if data structure contains null>
  75470. ** test more often than is necessary.
  75471. */
  75472. #ifndef SQLITE_OMIT_SUBQUERY
  75473. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  75474. Select *p; /* SELECT to the right of IN operator */
  75475. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  75476. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  75477. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  75478. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  75479. assert( pX->op==TK_IN );
  75480. /* Check to see if an existing table or index can be used to
  75481. ** satisfy the query. This is preferable to generating a new
  75482. ** ephemeral table.
  75483. */
  75484. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  75485. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  75486. sqlite3 *db = pParse->db; /* Database connection */
  75487. Table *pTab; /* Table <table>. */
  75488. Expr *pExpr; /* Expression <column> */
  75489. int iCol; /* Index of column <column> */
  75490. int iDb; /* Database idx for pTab */
  75491. assert( p ); /* Because of isCandidateForInOpt(p) */
  75492. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  75493. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  75494. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  75495. pTab = p->pSrc->a[0].pTab;
  75496. pExpr = p->pEList->a[0].pExpr;
  75497. iCol = pExpr->iColumn;
  75498. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  75499. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75500. sqlite3CodeVerifySchema(pParse, iDb);
  75501. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  75502. /* This function is only called from two places. In both cases the vdbe
  75503. ** has already been allocated. So assume sqlite3GetVdbe() is always
  75504. ** successful here.
  75505. */
  75506. assert(v);
  75507. if( iCol<0 ){
  75508. int iAddr;
  75509. iAddr = sqlite3CodeOnce(pParse);
  75510. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  75511. eType = IN_INDEX_ROWID;
  75512. sqlite3VdbeJumpHere(v, iAddr);
  75513. }else{
  75514. Index *pIdx; /* Iterator variable */
  75515. /* The collation sequence used by the comparison. If an index is to
  75516. ** be used in place of a temp-table, it must be ordered according
  75517. ** to this collation sequence. */
  75518. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  75519. /* Check that the affinity that will be used to perform the
  75520. ** comparison is the same as the affinity of the column. If
  75521. ** it is not, it is not possible to use any index.
  75522. */
  75523. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  75524. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  75525. if( (pIdx->aiColumn[0]==iCol)
  75526. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  75527. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  75528. ){
  75529. int iAddr;
  75530. char *pKey;
  75531. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  75532. iAddr = sqlite3CodeOnce(pParse);
  75533. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  75534. pKey,P4_KEYINFO_HANDOFF);
  75535. VdbeComment((v, "%s", pIdx->zName));
  75536. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  75537. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  75538. sqlite3VdbeJumpHere(v, iAddr);
  75539. if( prNotFound && !pTab->aCol[iCol].notNull ){
  75540. *prNotFound = ++pParse->nMem;
  75541. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  75542. }
  75543. }
  75544. }
  75545. }
  75546. }
  75547. if( eType==0 ){
  75548. /* Could not found an existing table or index to use as the RHS b-tree.
  75549. ** We will have to generate an ephemeral table to do the job.
  75550. */
  75551. u32 savedNQueryLoop = pParse->nQueryLoop;
  75552. int rMayHaveNull = 0;
  75553. eType = IN_INDEX_EPH;
  75554. if( prNotFound ){
  75555. *prNotFound = rMayHaveNull = ++pParse->nMem;
  75556. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  75557. }else{
  75558. testcase( pParse->nQueryLoop>0 );
  75559. pParse->nQueryLoop = 0;
  75560. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  75561. eType = IN_INDEX_ROWID;
  75562. }
  75563. }
  75564. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  75565. pParse->nQueryLoop = savedNQueryLoop;
  75566. }else{
  75567. pX->iTable = iTab;
  75568. }
  75569. return eType;
  75570. }
  75571. #endif
  75572. /*
  75573. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  75574. ** or IN operators. Examples:
  75575. **
  75576. ** (SELECT a FROM b) -- subquery
  75577. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  75578. ** x IN (4,5,11) -- IN operator with list on right-hand side
  75579. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  75580. **
  75581. ** The pExpr parameter describes the expression that contains the IN
  75582. ** operator or subquery.
  75583. **
  75584. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  75585. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  75586. ** to some integer key column of a table B-Tree. In this case, use an
  75587. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  75588. ** (slower) variable length keys B-Tree.
  75589. **
  75590. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  75591. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  75592. ** Furthermore, the IN is in a WHERE clause and that we really want
  75593. ** to iterate over the RHS of the IN operator in order to quickly locate
  75594. ** all corresponding LHS elements. All this routine does is initialize
  75595. ** the register given by rMayHaveNull to NULL. Calling routines will take
  75596. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  75597. **
  75598. ** If rMayHaveNull is zero, that means that the subquery is being used
  75599. ** for membership testing only. There is no need to initialize any
  75600. ** registers to indicate the presence or absence of NULLs on the RHS.
  75601. **
  75602. ** For a SELECT or EXISTS operator, return the register that holds the
  75603. ** result. For IN operators or if an error occurs, the return value is 0.
  75604. */
  75605. #ifndef SQLITE_OMIT_SUBQUERY
  75606. SQLITE_PRIVATE int sqlite3CodeSubselect(
  75607. Parse *pParse, /* Parsing context */
  75608. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  75609. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  75610. int isRowid /* If true, LHS of IN operator is a rowid */
  75611. ){
  75612. int testAddr = -1; /* One-time test address */
  75613. int rReg = 0; /* Register storing resulting */
  75614. Vdbe *v = sqlite3GetVdbe(pParse);
  75615. if( NEVER(v==0) ) return 0;
  75616. sqlite3ExprCachePush(pParse);
  75617. /* This code must be run in its entirety every time it is encountered
  75618. ** if any of the following is true:
  75619. **
  75620. ** * The right-hand side is a correlated subquery
  75621. ** * The right-hand side is an expression list containing variables
  75622. ** * We are inside a trigger
  75623. **
  75624. ** If all of the above are false, then we can run this code just once
  75625. ** save the results, and reuse the same result on subsequent invocations.
  75626. */
  75627. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  75628. testAddr = sqlite3CodeOnce(pParse);
  75629. }
  75630. #ifndef SQLITE_OMIT_EXPLAIN
  75631. if( pParse->explain==2 ){
  75632. char *zMsg = sqlite3MPrintf(
  75633. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  75634. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  75635. );
  75636. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  75637. }
  75638. #endif
  75639. switch( pExpr->op ){
  75640. case TK_IN: {
  75641. char affinity; /* Affinity of the LHS of the IN */
  75642. int addr; /* Address of OP_OpenEphemeral instruction */
  75643. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  75644. KeyInfo *pKeyInfo = 0; /* Key information */
  75645. if( rMayHaveNull ){
  75646. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  75647. }
  75648. affinity = sqlite3ExprAffinity(pLeft);
  75649. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  75650. ** expression it is handled the same way. An ephemeral table is
  75651. ** filled with single-field index keys representing the results
  75652. ** from the SELECT or the <exprlist>.
  75653. **
  75654. ** If the 'x' expression is a column value, or the SELECT...
  75655. ** statement returns a column value, then the affinity of that
  75656. ** column is used to build the index keys. If both 'x' and the
  75657. ** SELECT... statement are columns, then numeric affinity is used
  75658. ** if either column has NUMERIC or INTEGER affinity. If neither
  75659. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  75660. ** is used.
  75661. */
  75662. pExpr->iTable = pParse->nTab++;
  75663. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  75664. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  75665. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  75666. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75667. /* Case 1: expr IN (SELECT ...)
  75668. **
  75669. ** Generate code to write the results of the select into the temporary
  75670. ** table allocated and opened above.
  75671. */
  75672. SelectDest dest;
  75673. ExprList *pEList;
  75674. assert( !isRowid );
  75675. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  75676. dest.affSdst = (u8)affinity;
  75677. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  75678. pExpr->x.pSelect->iLimit = 0;
  75679. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  75680. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  75681. sqlite3DbFree(pParse->db, pKeyInfo);
  75682. return 0;
  75683. }
  75684. pEList = pExpr->x.pSelect->pEList;
  75685. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  75686. assert( pEList!=0 );
  75687. assert( pEList->nExpr>0 );
  75688. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  75689. pEList->a[0].pExpr);
  75690. }else if( ALWAYS(pExpr->x.pList!=0) ){
  75691. /* Case 2: expr IN (exprlist)
  75692. **
  75693. ** For each expression, build an index key from the evaluation and
  75694. ** store it in the temporary table. If <expr> is a column, then use
  75695. ** that columns affinity when building index keys. If <expr> is not
  75696. ** a column, use numeric affinity.
  75697. */
  75698. int i;
  75699. ExprList *pList = pExpr->x.pList;
  75700. struct ExprList_item *pItem;
  75701. int r1, r2, r3;
  75702. if( !affinity ){
  75703. affinity = SQLITE_AFF_NONE;
  75704. }
  75705. if( pKeyInfo ){
  75706. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  75707. }
  75708. /* Loop through each expression in <exprlist>. */
  75709. r1 = sqlite3GetTempReg(pParse);
  75710. r2 = sqlite3GetTempReg(pParse);
  75711. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  75712. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  75713. Expr *pE2 = pItem->pExpr;
  75714. int iValToIns;
  75715. /* If the expression is not constant then we will need to
  75716. ** disable the test that was generated above that makes sure
  75717. ** this code only executes once. Because for a non-constant
  75718. ** expression we need to rerun this code each time.
  75719. */
  75720. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  75721. sqlite3VdbeChangeToNoop(v, testAddr);
  75722. testAddr = -1;
  75723. }
  75724. /* Evaluate the expression and insert it into the temp table */
  75725. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  75726. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  75727. }else{
  75728. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  75729. if( isRowid ){
  75730. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  75731. sqlite3VdbeCurrentAddr(v)+2);
  75732. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  75733. }else{
  75734. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  75735. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  75736. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  75737. }
  75738. }
  75739. }
  75740. sqlite3ReleaseTempReg(pParse, r1);
  75741. sqlite3ReleaseTempReg(pParse, r2);
  75742. }
  75743. if( pKeyInfo ){
  75744. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  75745. }
  75746. break;
  75747. }
  75748. case TK_EXISTS:
  75749. case TK_SELECT:
  75750. default: {
  75751. /* If this has to be a scalar SELECT. Generate code to put the
  75752. ** value of this select in a memory cell and record the number
  75753. ** of the memory cell in iColumn. If this is an EXISTS, write
  75754. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  75755. ** and record that memory cell in iColumn.
  75756. */
  75757. Select *pSel; /* SELECT statement to encode */
  75758. SelectDest dest; /* How to deal with SELECt result */
  75759. testcase( pExpr->op==TK_EXISTS );
  75760. testcase( pExpr->op==TK_SELECT );
  75761. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  75762. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  75763. pSel = pExpr->x.pSelect;
  75764. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  75765. if( pExpr->op==TK_SELECT ){
  75766. dest.eDest = SRT_Mem;
  75767. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  75768. VdbeComment((v, "Init subquery result"));
  75769. }else{
  75770. dest.eDest = SRT_Exists;
  75771. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  75772. VdbeComment((v, "Init EXISTS result"));
  75773. }
  75774. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  75775. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  75776. &sqlite3IntTokens[1]);
  75777. pSel->iLimit = 0;
  75778. if( sqlite3Select(pParse, pSel, &dest) ){
  75779. return 0;
  75780. }
  75781. rReg = dest.iSDParm;
  75782. ExprSetVVAProperty(pExpr, EP_NoReduce);
  75783. break;
  75784. }
  75785. }
  75786. if( testAddr>=0 ){
  75787. sqlite3VdbeJumpHere(v, testAddr);
  75788. }
  75789. sqlite3ExprCachePop(pParse, 1);
  75790. return rReg;
  75791. }
  75792. #endif /* SQLITE_OMIT_SUBQUERY */
  75793. #ifndef SQLITE_OMIT_SUBQUERY
  75794. /*
  75795. ** Generate code for an IN expression.
  75796. **
  75797. ** x IN (SELECT ...)
  75798. ** x IN (value, value, ...)
  75799. **
  75800. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  75801. ** is an array of zero or more values. The expression is true if the LHS is
  75802. ** contained within the RHS. The value of the expression is unknown (NULL)
  75803. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  75804. ** RHS contains one or more NULL values.
  75805. **
  75806. ** This routine generates code will jump to destIfFalse if the LHS is not
  75807. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  75808. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  75809. ** within the RHS then fall through.
  75810. */
  75811. static void sqlite3ExprCodeIN(
  75812. Parse *pParse, /* Parsing and code generating context */
  75813. Expr *pExpr, /* The IN expression */
  75814. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  75815. int destIfNull /* Jump here if the results are unknown due to NULLs */
  75816. ){
  75817. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  75818. char affinity; /* Comparison affinity to use */
  75819. int eType; /* Type of the RHS */
  75820. int r1; /* Temporary use register */
  75821. Vdbe *v; /* Statement under construction */
  75822. /* Compute the RHS. After this step, the table with cursor
  75823. ** pExpr->iTable will contains the values that make up the RHS.
  75824. */
  75825. v = pParse->pVdbe;
  75826. assert( v!=0 ); /* OOM detected prior to this routine */
  75827. VdbeNoopComment((v, "begin IN expr"));
  75828. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  75829. /* Figure out the affinity to use to create a key from the results
  75830. ** of the expression. affinityStr stores a static string suitable for
  75831. ** P4 of OP_MakeRecord.
  75832. */
  75833. affinity = comparisonAffinity(pExpr);
  75834. /* Code the LHS, the <expr> from "<expr> IN (...)".
  75835. */
  75836. sqlite3ExprCachePush(pParse);
  75837. r1 = sqlite3GetTempReg(pParse);
  75838. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  75839. /* If the LHS is NULL, then the result is either false or NULL depending
  75840. ** on whether the RHS is empty or not, respectively.
  75841. */
  75842. if( destIfNull==destIfFalse ){
  75843. /* Shortcut for the common case where the false and NULL outcomes are
  75844. ** the same. */
  75845. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  75846. }else{
  75847. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  75848. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  75849. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  75850. sqlite3VdbeJumpHere(v, addr1);
  75851. }
  75852. if( eType==IN_INDEX_ROWID ){
  75853. /* In this case, the RHS is the ROWID of table b-tree
  75854. */
  75855. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  75856. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  75857. }else{
  75858. /* In this case, the RHS is an index b-tree.
  75859. */
  75860. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  75861. /* If the set membership test fails, then the result of the
  75862. ** "x IN (...)" expression must be either 0 or NULL. If the set
  75863. ** contains no NULL values, then the result is 0. If the set
  75864. ** contains one or more NULL values, then the result of the
  75865. ** expression is also NULL.
  75866. */
  75867. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  75868. /* This branch runs if it is known at compile time that the RHS
  75869. ** cannot contain NULL values. This happens as the result
  75870. ** of a "NOT NULL" constraint in the database schema.
  75871. **
  75872. ** Also run this branch if NULL is equivalent to FALSE
  75873. ** for this particular IN operator.
  75874. */
  75875. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  75876. }else{
  75877. /* In this branch, the RHS of the IN might contain a NULL and
  75878. ** the presence of a NULL on the RHS makes a difference in the
  75879. ** outcome.
  75880. */
  75881. int j1, j2, j3;
  75882. /* First check to see if the LHS is contained in the RHS. If so,
  75883. ** then the presence of NULLs in the RHS does not matter, so jump
  75884. ** over all of the code that follows.
  75885. */
  75886. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  75887. /* Here we begin generating code that runs if the LHS is not
  75888. ** contained within the RHS. Generate additional code that
  75889. ** tests the RHS for NULLs. If the RHS contains a NULL then
  75890. ** jump to destIfNull. If there are no NULLs in the RHS then
  75891. ** jump to destIfFalse.
  75892. */
  75893. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  75894. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  75895. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  75896. sqlite3VdbeJumpHere(v, j3);
  75897. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  75898. sqlite3VdbeJumpHere(v, j2);
  75899. /* Jump to the appropriate target depending on whether or not
  75900. ** the RHS contains a NULL
  75901. */
  75902. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  75903. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  75904. /* The OP_Found at the top of this branch jumps here when true,
  75905. ** causing the overall IN expression evaluation to fall through.
  75906. */
  75907. sqlite3VdbeJumpHere(v, j1);
  75908. }
  75909. }
  75910. sqlite3ReleaseTempReg(pParse, r1);
  75911. sqlite3ExprCachePop(pParse, 1);
  75912. VdbeComment((v, "end IN expr"));
  75913. }
  75914. #endif /* SQLITE_OMIT_SUBQUERY */
  75915. /*
  75916. ** Duplicate an 8-byte value
  75917. */
  75918. static char *dup8bytes(Vdbe *v, const char *in){
  75919. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  75920. if( out ){
  75921. memcpy(out, in, 8);
  75922. }
  75923. return out;
  75924. }
  75925. #ifndef SQLITE_OMIT_FLOATING_POINT
  75926. /*
  75927. ** Generate an instruction that will put the floating point
  75928. ** value described by z[0..n-1] into register iMem.
  75929. **
  75930. ** The z[] string will probably not be zero-terminated. But the
  75931. ** z[n] character is guaranteed to be something that does not look
  75932. ** like the continuation of the number.
  75933. */
  75934. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  75935. if( ALWAYS(z!=0) ){
  75936. double value;
  75937. char *zV;
  75938. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  75939. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  75940. if( negateFlag ) value = -value;
  75941. zV = dup8bytes(v, (char*)&value);
  75942. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  75943. }
  75944. }
  75945. #endif
  75946. /*
  75947. ** Generate an instruction that will put the integer describe by
  75948. ** text z[0..n-1] into register iMem.
  75949. **
  75950. ** Expr.u.zToken is always UTF8 and zero-terminated.
  75951. */
  75952. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  75953. Vdbe *v = pParse->pVdbe;
  75954. if( pExpr->flags & EP_IntValue ){
  75955. int i = pExpr->u.iValue;
  75956. assert( i>=0 );
  75957. if( negFlag ) i = -i;
  75958. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  75959. }else{
  75960. int c;
  75961. i64 value;
  75962. const char *z = pExpr->u.zToken;
  75963. assert( z!=0 );
  75964. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  75965. if( c==0 || (c==2 && negFlag) ){
  75966. char *zV;
  75967. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  75968. zV = dup8bytes(v, (char*)&value);
  75969. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  75970. }else{
  75971. #ifdef SQLITE_OMIT_FLOATING_POINT
  75972. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  75973. #else
  75974. codeReal(v, z, negFlag, iMem);
  75975. #endif
  75976. }
  75977. }
  75978. }
  75979. /*
  75980. ** Clear a cache entry.
  75981. */
  75982. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  75983. if( p->tempReg ){
  75984. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  75985. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  75986. }
  75987. p->tempReg = 0;
  75988. }
  75989. }
  75990. /*
  75991. ** Record in the column cache that a particular column from a
  75992. ** particular table is stored in a particular register.
  75993. */
  75994. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  75995. int i;
  75996. int minLru;
  75997. int idxLru;
  75998. struct yColCache *p;
  75999. assert( iReg>0 ); /* Register numbers are always positive */
  76000. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  76001. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  76002. ** for testing only - to verify that SQLite always gets the same answer
  76003. ** with and without the column cache.
  76004. */
  76005. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  76006. /* First replace any existing entry.
  76007. **
  76008. ** Actually, the way the column cache is currently used, we are guaranteed
  76009. ** that the object will never already be in cache. Verify this guarantee.
  76010. */
  76011. #ifndef NDEBUG
  76012. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76013. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  76014. }
  76015. #endif
  76016. /* Find an empty slot and replace it */
  76017. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76018. if( p->iReg==0 ){
  76019. p->iLevel = pParse->iCacheLevel;
  76020. p->iTable = iTab;
  76021. p->iColumn = iCol;
  76022. p->iReg = iReg;
  76023. p->tempReg = 0;
  76024. p->lru = pParse->iCacheCnt++;
  76025. return;
  76026. }
  76027. }
  76028. /* Replace the last recently used */
  76029. minLru = 0x7fffffff;
  76030. idxLru = -1;
  76031. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76032. if( p->lru<minLru ){
  76033. idxLru = i;
  76034. minLru = p->lru;
  76035. }
  76036. }
  76037. if( ALWAYS(idxLru>=0) ){
  76038. p = &pParse->aColCache[idxLru];
  76039. p->iLevel = pParse->iCacheLevel;
  76040. p->iTable = iTab;
  76041. p->iColumn = iCol;
  76042. p->iReg = iReg;
  76043. p->tempReg = 0;
  76044. p->lru = pParse->iCacheCnt++;
  76045. return;
  76046. }
  76047. }
  76048. /*
  76049. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  76050. ** Purge the range of registers from the column cache.
  76051. */
  76052. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  76053. int i;
  76054. int iLast = iReg + nReg - 1;
  76055. struct yColCache *p;
  76056. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76057. int r = p->iReg;
  76058. if( r>=iReg && r<=iLast ){
  76059. cacheEntryClear(pParse, p);
  76060. p->iReg = 0;
  76061. }
  76062. }
  76063. }
  76064. /*
  76065. ** Remember the current column cache context. Any new entries added
  76066. ** added to the column cache after this call are removed when the
  76067. ** corresponding pop occurs.
  76068. */
  76069. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  76070. pParse->iCacheLevel++;
  76071. }
  76072. /*
  76073. ** Remove from the column cache any entries that were added since the
  76074. ** the previous N Push operations. In other words, restore the cache
  76075. ** to the state it was in N Pushes ago.
  76076. */
  76077. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  76078. int i;
  76079. struct yColCache *p;
  76080. assert( N>0 );
  76081. assert( pParse->iCacheLevel>=N );
  76082. pParse->iCacheLevel -= N;
  76083. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76084. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  76085. cacheEntryClear(pParse, p);
  76086. p->iReg = 0;
  76087. }
  76088. }
  76089. }
  76090. /*
  76091. ** When a cached column is reused, make sure that its register is
  76092. ** no longer available as a temp register. ticket #3879: that same
  76093. ** register might be in the cache in multiple places, so be sure to
  76094. ** get them all.
  76095. */
  76096. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  76097. int i;
  76098. struct yColCache *p;
  76099. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76100. if( p->iReg==iReg ){
  76101. p->tempReg = 0;
  76102. }
  76103. }
  76104. }
  76105. /*
  76106. ** Generate code to extract the value of the iCol-th column of a table.
  76107. */
  76108. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  76109. Vdbe *v, /* The VDBE under construction */
  76110. Table *pTab, /* The table containing the value */
  76111. int iTabCur, /* The cursor for this table */
  76112. int iCol, /* Index of the column to extract */
  76113. int regOut /* Extract the valud into this register */
  76114. ){
  76115. if( iCol<0 || iCol==pTab->iPKey ){
  76116. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  76117. }else{
  76118. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  76119. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  76120. }
  76121. if( iCol>=0 ){
  76122. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  76123. }
  76124. }
  76125. /*
  76126. ** Generate code that will extract the iColumn-th column from
  76127. ** table pTab and store the column value in a register. An effort
  76128. ** is made to store the column value in register iReg, but this is
  76129. ** not guaranteed. The location of the column value is returned.
  76130. **
  76131. ** There must be an open cursor to pTab in iTable when this routine
  76132. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  76133. */
  76134. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  76135. Parse *pParse, /* Parsing and code generating context */
  76136. Table *pTab, /* Description of the table we are reading from */
  76137. int iColumn, /* Index of the table column */
  76138. int iTable, /* The cursor pointing to the table */
  76139. int iReg, /* Store results here */
  76140. u8 p5 /* P5 value for OP_Column */
  76141. ){
  76142. Vdbe *v = pParse->pVdbe;
  76143. int i;
  76144. struct yColCache *p;
  76145. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76146. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  76147. p->lru = pParse->iCacheCnt++;
  76148. sqlite3ExprCachePinRegister(pParse, p->iReg);
  76149. return p->iReg;
  76150. }
  76151. }
  76152. assert( v!=0 );
  76153. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  76154. if( p5 ){
  76155. sqlite3VdbeChangeP5(v, p5);
  76156. }else{
  76157. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  76158. }
  76159. return iReg;
  76160. }
  76161. /*
  76162. ** Clear all column cache entries.
  76163. */
  76164. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  76165. int i;
  76166. struct yColCache *p;
  76167. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76168. if( p->iReg ){
  76169. cacheEntryClear(pParse, p);
  76170. p->iReg = 0;
  76171. }
  76172. }
  76173. }
  76174. /*
  76175. ** Record the fact that an affinity change has occurred on iCount
  76176. ** registers starting with iStart.
  76177. */
  76178. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  76179. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  76180. }
  76181. /*
  76182. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  76183. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  76184. */
  76185. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  76186. int i;
  76187. struct yColCache *p;
  76188. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  76189. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  76190. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76191. int x = p->iReg;
  76192. if( x>=iFrom && x<iFrom+nReg ){
  76193. p->iReg += iTo-iFrom;
  76194. }
  76195. }
  76196. }
  76197. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  76198. /*
  76199. ** Return true if any register in the range iFrom..iTo (inclusive)
  76200. ** is used as part of the column cache.
  76201. **
  76202. ** This routine is used within assert() and testcase() macros only
  76203. ** and does not appear in a normal build.
  76204. */
  76205. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  76206. int i;
  76207. struct yColCache *p;
  76208. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76209. int r = p->iReg;
  76210. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  76211. }
  76212. return 0;
  76213. }
  76214. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  76215. /*
  76216. ** Convert an expression node to a TK_REGISTER
  76217. */
  76218. static void exprToRegister(Expr *p, int iReg){
  76219. p->op2 = p->op;
  76220. p->op = TK_REGISTER;
  76221. p->iTable = iReg;
  76222. ExprClearProperty(p, EP_Skip);
  76223. }
  76224. /*
  76225. ** Generate code into the current Vdbe to evaluate the given
  76226. ** expression. Attempt to store the results in register "target".
  76227. ** Return the register where results are stored.
  76228. **
  76229. ** With this routine, there is no guarantee that results will
  76230. ** be stored in target. The result might be stored in some other
  76231. ** register if it is convenient to do so. The calling function
  76232. ** must check the return code and move the results to the desired
  76233. ** register.
  76234. */
  76235. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  76236. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  76237. int op; /* The opcode being coded */
  76238. int inReg = target; /* Results stored in register inReg */
  76239. int regFree1 = 0; /* If non-zero free this temporary register */
  76240. int regFree2 = 0; /* If non-zero free this temporary register */
  76241. int r1, r2, r3, r4; /* Various register numbers */
  76242. sqlite3 *db = pParse->db; /* The database connection */
  76243. assert( target>0 && target<=pParse->nMem );
  76244. if( v==0 ){
  76245. assert( pParse->db->mallocFailed );
  76246. return 0;
  76247. }
  76248. if( pExpr==0 ){
  76249. op = TK_NULL;
  76250. }else{
  76251. op = pExpr->op;
  76252. }
  76253. switch( op ){
  76254. case TK_AGG_COLUMN: {
  76255. AggInfo *pAggInfo = pExpr->pAggInfo;
  76256. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  76257. if( !pAggInfo->directMode ){
  76258. assert( pCol->iMem>0 );
  76259. inReg = pCol->iMem;
  76260. break;
  76261. }else if( pAggInfo->useSortingIdx ){
  76262. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  76263. pCol->iSorterColumn, target);
  76264. break;
  76265. }
  76266. /* Otherwise, fall thru into the TK_COLUMN case */
  76267. }
  76268. case TK_COLUMN: {
  76269. int iTab = pExpr->iTable;
  76270. if( iTab<0 ){
  76271. if( pParse->ckBase>0 ){
  76272. /* Generating CHECK constraints or inserting into partial index */
  76273. inReg = pExpr->iColumn + pParse->ckBase;
  76274. break;
  76275. }else{
  76276. /* Deleting from a partial index */
  76277. iTab = pParse->iPartIdxTab;
  76278. }
  76279. }
  76280. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  76281. pExpr->iColumn, iTab, target,
  76282. pExpr->op2);
  76283. break;
  76284. }
  76285. case TK_INTEGER: {
  76286. codeInteger(pParse, pExpr, 0, target);
  76287. break;
  76288. }
  76289. #ifndef SQLITE_OMIT_FLOATING_POINT
  76290. case TK_FLOAT: {
  76291. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76292. codeReal(v, pExpr->u.zToken, 0, target);
  76293. break;
  76294. }
  76295. #endif
  76296. case TK_STRING: {
  76297. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76298. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  76299. break;
  76300. }
  76301. case TK_NULL: {
  76302. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76303. break;
  76304. }
  76305. #ifndef SQLITE_OMIT_BLOB_LITERAL
  76306. case TK_BLOB: {
  76307. int n;
  76308. const char *z;
  76309. char *zBlob;
  76310. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76311. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  76312. assert( pExpr->u.zToken[1]=='\'' );
  76313. z = &pExpr->u.zToken[2];
  76314. n = sqlite3Strlen30(z) - 1;
  76315. assert( z[n]=='\'' );
  76316. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  76317. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  76318. break;
  76319. }
  76320. #endif
  76321. case TK_VARIABLE: {
  76322. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76323. assert( pExpr->u.zToken!=0 );
  76324. assert( pExpr->u.zToken[0]!=0 );
  76325. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  76326. if( pExpr->u.zToken[1]!=0 ){
  76327. assert( pExpr->u.zToken[0]=='?'
  76328. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  76329. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  76330. }
  76331. break;
  76332. }
  76333. case TK_REGISTER: {
  76334. inReg = pExpr->iTable;
  76335. break;
  76336. }
  76337. case TK_AS: {
  76338. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76339. break;
  76340. }
  76341. #ifndef SQLITE_OMIT_CAST
  76342. case TK_CAST: {
  76343. /* Expressions of the form: CAST(pLeft AS token) */
  76344. int aff, to_op;
  76345. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76346. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76347. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  76348. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  76349. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  76350. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  76351. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  76352. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  76353. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  76354. testcase( to_op==OP_ToText );
  76355. testcase( to_op==OP_ToBlob );
  76356. testcase( to_op==OP_ToNumeric );
  76357. testcase( to_op==OP_ToInt );
  76358. testcase( to_op==OP_ToReal );
  76359. if( inReg!=target ){
  76360. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  76361. inReg = target;
  76362. }
  76363. sqlite3VdbeAddOp1(v, to_op, inReg);
  76364. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  76365. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  76366. break;
  76367. }
  76368. #endif /* SQLITE_OMIT_CAST */
  76369. case TK_LT:
  76370. case TK_LE:
  76371. case TK_GT:
  76372. case TK_GE:
  76373. case TK_NE:
  76374. case TK_EQ: {
  76375. assert( TK_LT==OP_Lt );
  76376. assert( TK_LE==OP_Le );
  76377. assert( TK_GT==OP_Gt );
  76378. assert( TK_GE==OP_Ge );
  76379. assert( TK_EQ==OP_Eq );
  76380. assert( TK_NE==OP_Ne );
  76381. testcase( op==TK_LT );
  76382. testcase( op==TK_LE );
  76383. testcase( op==TK_GT );
  76384. testcase( op==TK_GE );
  76385. testcase( op==TK_EQ );
  76386. testcase( op==TK_NE );
  76387. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76388. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76389. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  76390. r1, r2, inReg, SQLITE_STOREP2);
  76391. testcase( regFree1==0 );
  76392. testcase( regFree2==0 );
  76393. break;
  76394. }
  76395. case TK_IS:
  76396. case TK_ISNOT: {
  76397. testcase( op==TK_IS );
  76398. testcase( op==TK_ISNOT );
  76399. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76400. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76401. op = (op==TK_IS) ? TK_EQ : TK_NE;
  76402. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  76403. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  76404. testcase( regFree1==0 );
  76405. testcase( regFree2==0 );
  76406. break;
  76407. }
  76408. case TK_AND:
  76409. case TK_OR:
  76410. case TK_PLUS:
  76411. case TK_STAR:
  76412. case TK_MINUS:
  76413. case TK_REM:
  76414. case TK_BITAND:
  76415. case TK_BITOR:
  76416. case TK_SLASH:
  76417. case TK_LSHIFT:
  76418. case TK_RSHIFT:
  76419. case TK_CONCAT: {
  76420. assert( TK_AND==OP_And );
  76421. assert( TK_OR==OP_Or );
  76422. assert( TK_PLUS==OP_Add );
  76423. assert( TK_MINUS==OP_Subtract );
  76424. assert( TK_REM==OP_Remainder );
  76425. assert( TK_BITAND==OP_BitAnd );
  76426. assert( TK_BITOR==OP_BitOr );
  76427. assert( TK_SLASH==OP_Divide );
  76428. assert( TK_LSHIFT==OP_ShiftLeft );
  76429. assert( TK_RSHIFT==OP_ShiftRight );
  76430. assert( TK_CONCAT==OP_Concat );
  76431. testcase( op==TK_AND );
  76432. testcase( op==TK_OR );
  76433. testcase( op==TK_PLUS );
  76434. testcase( op==TK_MINUS );
  76435. testcase( op==TK_REM );
  76436. testcase( op==TK_BITAND );
  76437. testcase( op==TK_BITOR );
  76438. testcase( op==TK_SLASH );
  76439. testcase( op==TK_LSHIFT );
  76440. testcase( op==TK_RSHIFT );
  76441. testcase( op==TK_CONCAT );
  76442. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76443. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76444. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  76445. testcase( regFree1==0 );
  76446. testcase( regFree2==0 );
  76447. break;
  76448. }
  76449. case TK_UMINUS: {
  76450. Expr *pLeft = pExpr->pLeft;
  76451. assert( pLeft );
  76452. if( pLeft->op==TK_INTEGER ){
  76453. codeInteger(pParse, pLeft, 1, target);
  76454. #ifndef SQLITE_OMIT_FLOATING_POINT
  76455. }else if( pLeft->op==TK_FLOAT ){
  76456. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76457. codeReal(v, pLeft->u.zToken, 1, target);
  76458. #endif
  76459. }else{
  76460. regFree1 = r1 = sqlite3GetTempReg(pParse);
  76461. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  76462. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  76463. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  76464. testcase( regFree2==0 );
  76465. }
  76466. inReg = target;
  76467. break;
  76468. }
  76469. case TK_BITNOT:
  76470. case TK_NOT: {
  76471. assert( TK_BITNOT==OP_BitNot );
  76472. assert( TK_NOT==OP_Not );
  76473. testcase( op==TK_BITNOT );
  76474. testcase( op==TK_NOT );
  76475. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76476. testcase( regFree1==0 );
  76477. inReg = target;
  76478. sqlite3VdbeAddOp2(v, op, r1, inReg);
  76479. break;
  76480. }
  76481. case TK_ISNULL:
  76482. case TK_NOTNULL: {
  76483. int addr;
  76484. assert( TK_ISNULL==OP_IsNull );
  76485. assert( TK_NOTNULL==OP_NotNull );
  76486. testcase( op==TK_ISNULL );
  76487. testcase( op==TK_NOTNULL );
  76488. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  76489. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76490. testcase( regFree1==0 );
  76491. addr = sqlite3VdbeAddOp1(v, op, r1);
  76492. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  76493. sqlite3VdbeJumpHere(v, addr);
  76494. break;
  76495. }
  76496. case TK_AGG_FUNCTION: {
  76497. AggInfo *pInfo = pExpr->pAggInfo;
  76498. if( pInfo==0 ){
  76499. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76500. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  76501. }else{
  76502. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  76503. }
  76504. break;
  76505. }
  76506. case TK_CONST_FUNC:
  76507. case TK_FUNCTION: {
  76508. ExprList *pFarg; /* List of function arguments */
  76509. int nFarg; /* Number of function arguments */
  76510. FuncDef *pDef; /* The function definition object */
  76511. int nId; /* Length of the function name in bytes */
  76512. const char *zId; /* The function name */
  76513. int constMask = 0; /* Mask of function arguments that are constant */
  76514. int i; /* Loop counter */
  76515. u8 enc = ENC(db); /* The text encoding used by this database */
  76516. CollSeq *pColl = 0; /* A collating sequence */
  76517. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  76518. testcase( op==TK_CONST_FUNC );
  76519. testcase( op==TK_FUNCTION );
  76520. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  76521. pFarg = 0;
  76522. }else{
  76523. pFarg = pExpr->x.pList;
  76524. }
  76525. nFarg = pFarg ? pFarg->nExpr : 0;
  76526. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76527. zId = pExpr->u.zToken;
  76528. nId = sqlite3Strlen30(zId);
  76529. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  76530. if( pDef==0 ){
  76531. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  76532. break;
  76533. }
  76534. /* Attempt a direct implementation of the built-in COALESCE() and
  76535. ** IFNULL() functions. This avoids unnecessary evalation of
  76536. ** arguments past the first non-NULL argument.
  76537. */
  76538. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  76539. int endCoalesce = sqlite3VdbeMakeLabel(v);
  76540. assert( nFarg>=2 );
  76541. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  76542. for(i=1; i<nFarg; i++){
  76543. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  76544. sqlite3ExprCacheRemove(pParse, target, 1);
  76545. sqlite3ExprCachePush(pParse);
  76546. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  76547. sqlite3ExprCachePop(pParse, 1);
  76548. }
  76549. sqlite3VdbeResolveLabel(v, endCoalesce);
  76550. break;
  76551. }
  76552. /* The UNLIKELY() function is a no-op. The result is the value
  76553. ** of the first argument.
  76554. */
  76555. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  76556. assert( nFarg>=1 );
  76557. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  76558. break;
  76559. }
  76560. if( pFarg ){
  76561. r1 = sqlite3GetTempRange(pParse, nFarg);
  76562. /* For length() and typeof() functions with a column argument,
  76563. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  76564. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  76565. ** loading.
  76566. */
  76567. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  76568. u8 exprOp;
  76569. assert( nFarg==1 );
  76570. assert( pFarg->a[0].pExpr!=0 );
  76571. exprOp = pFarg->a[0].pExpr->op;
  76572. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  76573. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  76574. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  76575. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  76576. ==SQLITE_FUNC_LENGTH );
  76577. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  76578. }
  76579. }
  76580. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  76581. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  76582. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  76583. }else{
  76584. r1 = 0;
  76585. }
  76586. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76587. /* Possibly overload the function if the first argument is
  76588. ** a virtual table column.
  76589. **
  76590. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  76591. ** second argument, not the first, as the argument to test to
  76592. ** see if it is a column in a virtual table. This is done because
  76593. ** the left operand of infix functions (the operand we want to
  76594. ** control overloading) ends up as the second argument to the
  76595. ** function. The expression "A glob B" is equivalent to
  76596. ** "glob(B,A). We want to use the A in "A glob B" to test
  76597. ** for function overloading. But we use the B term in "glob(B,A)".
  76598. */
  76599. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  76600. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  76601. }else if( nFarg>0 ){
  76602. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  76603. }
  76604. #endif
  76605. for(i=0; i<nFarg; i++){
  76606. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  76607. constMask |= (1<<i);
  76608. }
  76609. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  76610. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  76611. }
  76612. }
  76613. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  76614. if( !pColl ) pColl = db->pDfltColl;
  76615. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  76616. }
  76617. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  76618. (char*)pDef, P4_FUNCDEF);
  76619. sqlite3VdbeChangeP5(v, (u8)nFarg);
  76620. if( nFarg ){
  76621. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  76622. }
  76623. break;
  76624. }
  76625. #ifndef SQLITE_OMIT_SUBQUERY
  76626. case TK_EXISTS:
  76627. case TK_SELECT: {
  76628. testcase( op==TK_EXISTS );
  76629. testcase( op==TK_SELECT );
  76630. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  76631. break;
  76632. }
  76633. case TK_IN: {
  76634. int destIfFalse = sqlite3VdbeMakeLabel(v);
  76635. int destIfNull = sqlite3VdbeMakeLabel(v);
  76636. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76637. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  76638. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  76639. sqlite3VdbeResolveLabel(v, destIfFalse);
  76640. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  76641. sqlite3VdbeResolveLabel(v, destIfNull);
  76642. break;
  76643. }
  76644. #endif /* SQLITE_OMIT_SUBQUERY */
  76645. /*
  76646. ** x BETWEEN y AND z
  76647. **
  76648. ** This is equivalent to
  76649. **
  76650. ** x>=y AND x<=z
  76651. **
  76652. ** X is stored in pExpr->pLeft.
  76653. ** Y is stored in pExpr->pList->a[0].pExpr.
  76654. ** Z is stored in pExpr->pList->a[1].pExpr.
  76655. */
  76656. case TK_BETWEEN: {
  76657. Expr *pLeft = pExpr->pLeft;
  76658. struct ExprList_item *pLItem = pExpr->x.pList->a;
  76659. Expr *pRight = pLItem->pExpr;
  76660. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  76661. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  76662. testcase( regFree1==0 );
  76663. testcase( regFree2==0 );
  76664. r3 = sqlite3GetTempReg(pParse);
  76665. r4 = sqlite3GetTempReg(pParse);
  76666. codeCompare(pParse, pLeft, pRight, OP_Ge,
  76667. r1, r2, r3, SQLITE_STOREP2);
  76668. pLItem++;
  76669. pRight = pLItem->pExpr;
  76670. sqlite3ReleaseTempReg(pParse, regFree2);
  76671. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  76672. testcase( regFree2==0 );
  76673. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  76674. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  76675. sqlite3ReleaseTempReg(pParse, r3);
  76676. sqlite3ReleaseTempReg(pParse, r4);
  76677. break;
  76678. }
  76679. case TK_COLLATE:
  76680. case TK_UPLUS: {
  76681. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76682. break;
  76683. }
  76684. case TK_TRIGGER: {
  76685. /* If the opcode is TK_TRIGGER, then the expression is a reference
  76686. ** to a column in the new.* or old.* pseudo-tables available to
  76687. ** trigger programs. In this case Expr.iTable is set to 1 for the
  76688. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  76689. ** is set to the column of the pseudo-table to read, or to -1 to
  76690. ** read the rowid field.
  76691. **
  76692. ** The expression is implemented using an OP_Param opcode. The p1
  76693. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  76694. ** to reference another column of the old.* pseudo-table, where
  76695. ** i is the index of the column. For a new.rowid reference, p1 is
  76696. ** set to (n+1), where n is the number of columns in each pseudo-table.
  76697. ** For a reference to any other column in the new.* pseudo-table, p1
  76698. ** is set to (n+2+i), where n and i are as defined previously. For
  76699. ** example, if the table on which triggers are being fired is
  76700. ** declared as:
  76701. **
  76702. ** CREATE TABLE t1(a, b);
  76703. **
  76704. ** Then p1 is interpreted as follows:
  76705. **
  76706. ** p1==0 -> old.rowid p1==3 -> new.rowid
  76707. ** p1==1 -> old.a p1==4 -> new.a
  76708. ** p1==2 -> old.b p1==5 -> new.b
  76709. */
  76710. Table *pTab = pExpr->pTab;
  76711. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  76712. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  76713. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  76714. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  76715. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  76716. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  76717. VdbeComment((v, "%s.%s -> $%d",
  76718. (pExpr->iTable ? "new" : "old"),
  76719. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  76720. target
  76721. ));
  76722. #ifndef SQLITE_OMIT_FLOATING_POINT
  76723. /* If the column has REAL affinity, it may currently be stored as an
  76724. ** integer. Use OP_RealAffinity to make sure it is really real. */
  76725. if( pExpr->iColumn>=0
  76726. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  76727. ){
  76728. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  76729. }
  76730. #endif
  76731. break;
  76732. }
  76733. /*
  76734. ** Form A:
  76735. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  76736. **
  76737. ** Form B:
  76738. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  76739. **
  76740. ** Form A is can be transformed into the equivalent form B as follows:
  76741. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  76742. ** WHEN x=eN THEN rN ELSE y END
  76743. **
  76744. ** X (if it exists) is in pExpr->pLeft.
  76745. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  76746. ** odd. The Y is also optional. If the number of elements in x.pList
  76747. ** is even, then Y is omitted and the "otherwise" result is NULL.
  76748. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  76749. **
  76750. ** The result of the expression is the Ri for the first matching Ei,
  76751. ** or if there is no matching Ei, the ELSE term Y, or if there is
  76752. ** no ELSE term, NULL.
  76753. */
  76754. default: assert( op==TK_CASE ); {
  76755. int endLabel; /* GOTO label for end of CASE stmt */
  76756. int nextCase; /* GOTO label for next WHEN clause */
  76757. int nExpr; /* 2x number of WHEN terms */
  76758. int i; /* Loop counter */
  76759. ExprList *pEList; /* List of WHEN terms */
  76760. struct ExprList_item *aListelem; /* Array of WHEN terms */
  76761. Expr opCompare; /* The X==Ei expression */
  76762. Expr cacheX; /* Cached expression X */
  76763. Expr *pX; /* The X expression */
  76764. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  76765. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  76766. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  76767. assert(pExpr->x.pList->nExpr > 0);
  76768. pEList = pExpr->x.pList;
  76769. aListelem = pEList->a;
  76770. nExpr = pEList->nExpr;
  76771. endLabel = sqlite3VdbeMakeLabel(v);
  76772. if( (pX = pExpr->pLeft)!=0 ){
  76773. cacheX = *pX;
  76774. testcase( pX->op==TK_COLUMN );
  76775. testcase( pX->op==TK_REGISTER );
  76776. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  76777. testcase( regFree1==0 );
  76778. opCompare.op = TK_EQ;
  76779. opCompare.pLeft = &cacheX;
  76780. pTest = &opCompare;
  76781. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  76782. ** The value in regFree1 might get SCopy-ed into the file result.
  76783. ** So make sure that the regFree1 register is not reused for other
  76784. ** purposes and possibly overwritten. */
  76785. regFree1 = 0;
  76786. }
  76787. for(i=0; i<nExpr-1; i=i+2){
  76788. sqlite3ExprCachePush(pParse);
  76789. if( pX ){
  76790. assert( pTest!=0 );
  76791. opCompare.pRight = aListelem[i].pExpr;
  76792. }else{
  76793. pTest = aListelem[i].pExpr;
  76794. }
  76795. nextCase = sqlite3VdbeMakeLabel(v);
  76796. testcase( pTest->op==TK_COLUMN );
  76797. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  76798. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  76799. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  76800. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  76801. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  76802. sqlite3ExprCachePop(pParse, 1);
  76803. sqlite3VdbeResolveLabel(v, nextCase);
  76804. }
  76805. if( (nExpr&1)!=0 ){
  76806. sqlite3ExprCachePush(pParse);
  76807. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  76808. sqlite3ExprCachePop(pParse, 1);
  76809. }else{
  76810. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76811. }
  76812. assert( db->mallocFailed || pParse->nErr>0
  76813. || pParse->iCacheLevel==iCacheLevel );
  76814. sqlite3VdbeResolveLabel(v, endLabel);
  76815. break;
  76816. }
  76817. #ifndef SQLITE_OMIT_TRIGGER
  76818. case TK_RAISE: {
  76819. assert( pExpr->affinity==OE_Rollback
  76820. || pExpr->affinity==OE_Abort
  76821. || pExpr->affinity==OE_Fail
  76822. || pExpr->affinity==OE_Ignore
  76823. );
  76824. if( !pParse->pTriggerTab ){
  76825. sqlite3ErrorMsg(pParse,
  76826. "RAISE() may only be used within a trigger-program");
  76827. return 0;
  76828. }
  76829. if( pExpr->affinity==OE_Abort ){
  76830. sqlite3MayAbort(pParse);
  76831. }
  76832. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76833. if( pExpr->affinity==OE_Ignore ){
  76834. sqlite3VdbeAddOp4(
  76835. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  76836. }else{
  76837. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  76838. pExpr->affinity, pExpr->u.zToken, 0);
  76839. }
  76840. break;
  76841. }
  76842. #endif
  76843. }
  76844. sqlite3ReleaseTempReg(pParse, regFree1);
  76845. sqlite3ReleaseTempReg(pParse, regFree2);
  76846. return inReg;
  76847. }
  76848. /*
  76849. ** Generate code to evaluate an expression and store the results
  76850. ** into a register. Return the register number where the results
  76851. ** are stored.
  76852. **
  76853. ** If the register is a temporary register that can be deallocated,
  76854. ** then write its number into *pReg. If the result register is not
  76855. ** a temporary, then set *pReg to zero.
  76856. */
  76857. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  76858. int r1 = sqlite3GetTempReg(pParse);
  76859. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  76860. if( r2==r1 ){
  76861. *pReg = r1;
  76862. }else{
  76863. sqlite3ReleaseTempReg(pParse, r1);
  76864. *pReg = 0;
  76865. }
  76866. return r2;
  76867. }
  76868. /*
  76869. ** Generate code that will evaluate expression pExpr and store the
  76870. ** results in register target. The results are guaranteed to appear
  76871. ** in register target.
  76872. */
  76873. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  76874. int inReg;
  76875. assert( target>0 && target<=pParse->nMem );
  76876. if( pExpr && pExpr->op==TK_REGISTER ){
  76877. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  76878. }else{
  76879. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  76880. assert( pParse->pVdbe || pParse->db->mallocFailed );
  76881. if( inReg!=target && pParse->pVdbe ){
  76882. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  76883. }
  76884. }
  76885. return target;
  76886. }
  76887. /*
  76888. ** Generate code that evalutes the given expression and puts the result
  76889. ** in register target.
  76890. **
  76891. ** Also make a copy of the expression results into another "cache" register
  76892. ** and modify the expression so that the next time it is evaluated,
  76893. ** the result is a copy of the cache register.
  76894. **
  76895. ** This routine is used for expressions that are used multiple
  76896. ** times. They are evaluated once and the results of the expression
  76897. ** are reused.
  76898. */
  76899. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  76900. Vdbe *v = pParse->pVdbe;
  76901. int inReg;
  76902. inReg = sqlite3ExprCode(pParse, pExpr, target);
  76903. assert( target>0 );
  76904. /* This routine is called for terms to INSERT or UPDATE. And the only
  76905. ** other place where expressions can be converted into TK_REGISTER is
  76906. ** in WHERE clause processing. So as currently implemented, there is
  76907. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  76908. ** keep the ALWAYS() in case the conditions above change with future
  76909. ** modifications or enhancements. */
  76910. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  76911. int iMem;
  76912. iMem = ++pParse->nMem;
  76913. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  76914. exprToRegister(pExpr, iMem);
  76915. }
  76916. return inReg;
  76917. }
  76918. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  76919. /*
  76920. ** Generate a human-readable explanation of an expression tree.
  76921. */
  76922. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  76923. int op; /* The opcode being coded */
  76924. const char *zBinOp = 0; /* Binary operator */
  76925. const char *zUniOp = 0; /* Unary operator */
  76926. if( pExpr==0 ){
  76927. op = TK_NULL;
  76928. }else{
  76929. op = pExpr->op;
  76930. }
  76931. switch( op ){
  76932. case TK_AGG_COLUMN: {
  76933. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  76934. pExpr->iTable, pExpr->iColumn);
  76935. break;
  76936. }
  76937. case TK_COLUMN: {
  76938. if( pExpr->iTable<0 ){
  76939. /* This only happens when coding check constraints */
  76940. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  76941. }else{
  76942. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  76943. pExpr->iTable, pExpr->iColumn);
  76944. }
  76945. break;
  76946. }
  76947. case TK_INTEGER: {
  76948. if( pExpr->flags & EP_IntValue ){
  76949. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  76950. }else{
  76951. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  76952. }
  76953. break;
  76954. }
  76955. #ifndef SQLITE_OMIT_FLOATING_POINT
  76956. case TK_FLOAT: {
  76957. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  76958. break;
  76959. }
  76960. #endif
  76961. case TK_STRING: {
  76962. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  76963. break;
  76964. }
  76965. case TK_NULL: {
  76966. sqlite3ExplainPrintf(pOut,"NULL");
  76967. break;
  76968. }
  76969. #ifndef SQLITE_OMIT_BLOB_LITERAL
  76970. case TK_BLOB: {
  76971. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  76972. break;
  76973. }
  76974. #endif
  76975. case TK_VARIABLE: {
  76976. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  76977. pExpr->u.zToken, pExpr->iColumn);
  76978. break;
  76979. }
  76980. case TK_REGISTER: {
  76981. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  76982. break;
  76983. }
  76984. case TK_AS: {
  76985. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  76986. break;
  76987. }
  76988. #ifndef SQLITE_OMIT_CAST
  76989. case TK_CAST: {
  76990. /* Expressions of the form: CAST(pLeft AS token) */
  76991. const char *zAff = "unk";
  76992. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  76993. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  76994. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  76995. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  76996. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  76997. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  76998. }
  76999. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  77000. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77001. sqlite3ExplainPrintf(pOut, ")");
  77002. break;
  77003. }
  77004. #endif /* SQLITE_OMIT_CAST */
  77005. case TK_LT: zBinOp = "LT"; break;
  77006. case TK_LE: zBinOp = "LE"; break;
  77007. case TK_GT: zBinOp = "GT"; break;
  77008. case TK_GE: zBinOp = "GE"; break;
  77009. case TK_NE: zBinOp = "NE"; break;
  77010. case TK_EQ: zBinOp = "EQ"; break;
  77011. case TK_IS: zBinOp = "IS"; break;
  77012. case TK_ISNOT: zBinOp = "ISNOT"; break;
  77013. case TK_AND: zBinOp = "AND"; break;
  77014. case TK_OR: zBinOp = "OR"; break;
  77015. case TK_PLUS: zBinOp = "ADD"; break;
  77016. case TK_STAR: zBinOp = "MUL"; break;
  77017. case TK_MINUS: zBinOp = "SUB"; break;
  77018. case TK_REM: zBinOp = "REM"; break;
  77019. case TK_BITAND: zBinOp = "BITAND"; break;
  77020. case TK_BITOR: zBinOp = "BITOR"; break;
  77021. case TK_SLASH: zBinOp = "DIV"; break;
  77022. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  77023. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  77024. case TK_CONCAT: zBinOp = "CONCAT"; break;
  77025. case TK_UMINUS: zUniOp = "UMINUS"; break;
  77026. case TK_UPLUS: zUniOp = "UPLUS"; break;
  77027. case TK_BITNOT: zUniOp = "BITNOT"; break;
  77028. case TK_NOT: zUniOp = "NOT"; break;
  77029. case TK_ISNULL: zUniOp = "ISNULL"; break;
  77030. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  77031. case TK_COLLATE: {
  77032. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77033. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  77034. break;
  77035. }
  77036. case TK_AGG_FUNCTION:
  77037. case TK_CONST_FUNC:
  77038. case TK_FUNCTION: {
  77039. ExprList *pFarg; /* List of function arguments */
  77040. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  77041. pFarg = 0;
  77042. }else{
  77043. pFarg = pExpr->x.pList;
  77044. }
  77045. if( op==TK_AGG_FUNCTION ){
  77046. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  77047. pExpr->op2, pExpr->u.zToken);
  77048. }else{
  77049. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  77050. }
  77051. if( pFarg ){
  77052. sqlite3ExplainExprList(pOut, pFarg);
  77053. }
  77054. sqlite3ExplainPrintf(pOut, ")");
  77055. break;
  77056. }
  77057. #ifndef SQLITE_OMIT_SUBQUERY
  77058. case TK_EXISTS: {
  77059. sqlite3ExplainPrintf(pOut, "EXISTS(");
  77060. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77061. sqlite3ExplainPrintf(pOut,")");
  77062. break;
  77063. }
  77064. case TK_SELECT: {
  77065. sqlite3ExplainPrintf(pOut, "(");
  77066. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77067. sqlite3ExplainPrintf(pOut, ")");
  77068. break;
  77069. }
  77070. case TK_IN: {
  77071. sqlite3ExplainPrintf(pOut, "IN(");
  77072. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77073. sqlite3ExplainPrintf(pOut, ",");
  77074. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77075. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77076. }else{
  77077. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  77078. }
  77079. sqlite3ExplainPrintf(pOut, ")");
  77080. break;
  77081. }
  77082. #endif /* SQLITE_OMIT_SUBQUERY */
  77083. /*
  77084. ** x BETWEEN y AND z
  77085. **
  77086. ** This is equivalent to
  77087. **
  77088. ** x>=y AND x<=z
  77089. **
  77090. ** X is stored in pExpr->pLeft.
  77091. ** Y is stored in pExpr->pList->a[0].pExpr.
  77092. ** Z is stored in pExpr->pList->a[1].pExpr.
  77093. */
  77094. case TK_BETWEEN: {
  77095. Expr *pX = pExpr->pLeft;
  77096. Expr *pY = pExpr->x.pList->a[0].pExpr;
  77097. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  77098. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  77099. sqlite3ExplainExpr(pOut, pX);
  77100. sqlite3ExplainPrintf(pOut, ",");
  77101. sqlite3ExplainExpr(pOut, pY);
  77102. sqlite3ExplainPrintf(pOut, ",");
  77103. sqlite3ExplainExpr(pOut, pZ);
  77104. sqlite3ExplainPrintf(pOut, ")");
  77105. break;
  77106. }
  77107. case TK_TRIGGER: {
  77108. /* If the opcode is TK_TRIGGER, then the expression is a reference
  77109. ** to a column in the new.* or old.* pseudo-tables available to
  77110. ** trigger programs. In this case Expr.iTable is set to 1 for the
  77111. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  77112. ** is set to the column of the pseudo-table to read, or to -1 to
  77113. ** read the rowid field.
  77114. */
  77115. sqlite3ExplainPrintf(pOut, "%s(%d)",
  77116. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  77117. break;
  77118. }
  77119. case TK_CASE: {
  77120. sqlite3ExplainPrintf(pOut, "CASE(");
  77121. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77122. sqlite3ExplainPrintf(pOut, ",");
  77123. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  77124. break;
  77125. }
  77126. #ifndef SQLITE_OMIT_TRIGGER
  77127. case TK_RAISE: {
  77128. const char *zType = "unk";
  77129. switch( pExpr->affinity ){
  77130. case OE_Rollback: zType = "rollback"; break;
  77131. case OE_Abort: zType = "abort"; break;
  77132. case OE_Fail: zType = "fail"; break;
  77133. case OE_Ignore: zType = "ignore"; break;
  77134. }
  77135. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  77136. break;
  77137. }
  77138. #endif
  77139. }
  77140. if( zBinOp ){
  77141. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  77142. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77143. sqlite3ExplainPrintf(pOut,",");
  77144. sqlite3ExplainExpr(pOut, pExpr->pRight);
  77145. sqlite3ExplainPrintf(pOut,")");
  77146. }else if( zUniOp ){
  77147. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  77148. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77149. sqlite3ExplainPrintf(pOut,")");
  77150. }
  77151. }
  77152. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  77153. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  77154. /*
  77155. ** Generate a human-readable explanation of an expression list.
  77156. */
  77157. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  77158. int i;
  77159. if( pList==0 || pList->nExpr==0 ){
  77160. sqlite3ExplainPrintf(pOut, "(empty-list)");
  77161. return;
  77162. }else if( pList->nExpr==1 ){
  77163. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  77164. }else{
  77165. sqlite3ExplainPush(pOut);
  77166. for(i=0; i<pList->nExpr; i++){
  77167. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  77168. sqlite3ExplainPush(pOut);
  77169. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  77170. sqlite3ExplainPop(pOut);
  77171. if( pList->a[i].zName ){
  77172. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  77173. }
  77174. if( pList->a[i].bSpanIsTab ){
  77175. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  77176. }
  77177. if( i<pList->nExpr-1 ){
  77178. sqlite3ExplainNL(pOut);
  77179. }
  77180. }
  77181. sqlite3ExplainPop(pOut);
  77182. }
  77183. }
  77184. #endif /* SQLITE_DEBUG */
  77185. /*
  77186. ** Return TRUE if pExpr is an constant expression that is appropriate
  77187. ** for factoring out of a loop. Appropriate expressions are:
  77188. **
  77189. ** * Any expression that evaluates to two or more opcodes.
  77190. **
  77191. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  77192. ** or OP_Variable that does not need to be placed in a
  77193. ** specific register.
  77194. **
  77195. ** There is no point in factoring out single-instruction constant
  77196. ** expressions that need to be placed in a particular register.
  77197. ** We could factor them out, but then we would end up adding an
  77198. ** OP_SCopy instruction to move the value into the correct register
  77199. ** later. We might as well just use the original instruction and
  77200. ** avoid the OP_SCopy.
  77201. */
  77202. static int isAppropriateForFactoring(Expr *p){
  77203. if( !sqlite3ExprIsConstantNotJoin(p) ){
  77204. return 0; /* Only constant expressions are appropriate for factoring */
  77205. }
  77206. if( (p->flags & EP_FixedDest)==0 ){
  77207. return 1; /* Any constant without a fixed destination is appropriate */
  77208. }
  77209. while( p->op==TK_UPLUS ) p = p->pLeft;
  77210. switch( p->op ){
  77211. #ifndef SQLITE_OMIT_BLOB_LITERAL
  77212. case TK_BLOB:
  77213. #endif
  77214. case TK_VARIABLE:
  77215. case TK_INTEGER:
  77216. case TK_FLOAT:
  77217. case TK_NULL:
  77218. case TK_STRING: {
  77219. testcase( p->op==TK_BLOB );
  77220. testcase( p->op==TK_VARIABLE );
  77221. testcase( p->op==TK_INTEGER );
  77222. testcase( p->op==TK_FLOAT );
  77223. testcase( p->op==TK_NULL );
  77224. testcase( p->op==TK_STRING );
  77225. /* Single-instruction constants with a fixed destination are
  77226. ** better done in-line. If we factor them, they will just end
  77227. ** up generating an OP_SCopy to move the value to the destination
  77228. ** register. */
  77229. return 0;
  77230. }
  77231. case TK_UMINUS: {
  77232. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  77233. return 0;
  77234. }
  77235. break;
  77236. }
  77237. default: {
  77238. break;
  77239. }
  77240. }
  77241. return 1;
  77242. }
  77243. /*
  77244. ** If pExpr is a constant expression that is appropriate for
  77245. ** factoring out of a loop, then evaluate the expression
  77246. ** into a register and convert the expression into a TK_REGISTER
  77247. ** expression.
  77248. */
  77249. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  77250. Parse *pParse = pWalker->pParse;
  77251. switch( pExpr->op ){
  77252. case TK_IN:
  77253. case TK_REGISTER: {
  77254. return WRC_Prune;
  77255. }
  77256. case TK_COLLATE: {
  77257. return WRC_Continue;
  77258. }
  77259. case TK_FUNCTION:
  77260. case TK_AGG_FUNCTION:
  77261. case TK_CONST_FUNC: {
  77262. /* The arguments to a function have a fixed destination.
  77263. ** Mark them this way to avoid generated unneeded OP_SCopy
  77264. ** instructions.
  77265. */
  77266. ExprList *pList = pExpr->x.pList;
  77267. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77268. if( pList ){
  77269. int i = pList->nExpr;
  77270. struct ExprList_item *pItem = pList->a;
  77271. for(; i>0; i--, pItem++){
  77272. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  77273. }
  77274. }
  77275. break;
  77276. }
  77277. }
  77278. if( isAppropriateForFactoring(pExpr) ){
  77279. int r1 = ++pParse->nMem;
  77280. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  77281. /* If r2!=r1, it means that register r1 is never used. That is harmless
  77282. ** but suboptimal, so we want to know about the situation to fix it.
  77283. ** Hence the following assert: */
  77284. assert( r2==r1 );
  77285. exprToRegister(pExpr, r2);
  77286. return WRC_Prune;
  77287. }
  77288. return WRC_Continue;
  77289. }
  77290. /*
  77291. ** Preevaluate constant subexpressions within pExpr and store the
  77292. ** results in registers. Modify pExpr so that the constant subexpresions
  77293. ** are TK_REGISTER opcodes that refer to the precomputed values.
  77294. **
  77295. ** This routine is a no-op if the jump to the cookie-check code has
  77296. ** already occur. Since the cookie-check jump is generated prior to
  77297. ** any other serious processing, this check ensures that there is no
  77298. ** way to accidently bypass the constant initializations.
  77299. **
  77300. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  77301. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  77302. ** interface. This allows test logic to verify that the same answer is
  77303. ** obtained for queries regardless of whether or not constants are
  77304. ** precomputed into registers or if they are inserted in-line.
  77305. */
  77306. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  77307. Walker w;
  77308. if( pParse->cookieGoto ) return;
  77309. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  77310. memset(&w, 0, sizeof(w));
  77311. w.xExprCallback = evalConstExpr;
  77312. w.pParse = pParse;
  77313. sqlite3WalkExpr(&w, pExpr);
  77314. }
  77315. /*
  77316. ** Generate code that pushes the value of every element of the given
  77317. ** expression list into a sequence of registers beginning at target.
  77318. **
  77319. ** Return the number of elements evaluated.
  77320. */
  77321. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  77322. Parse *pParse, /* Parsing context */
  77323. ExprList *pList, /* The expression list to be coded */
  77324. int target, /* Where to write results */
  77325. int doHardCopy /* Make a hard copy of every element */
  77326. ){
  77327. struct ExprList_item *pItem;
  77328. int i, n;
  77329. assert( pList!=0 );
  77330. assert( target>0 );
  77331. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  77332. n = pList->nExpr;
  77333. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  77334. Expr *pExpr = pItem->pExpr;
  77335. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  77336. if( inReg!=target+i ){
  77337. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  77338. inReg, target+i);
  77339. }
  77340. }
  77341. return n;
  77342. }
  77343. /*
  77344. ** Generate code for a BETWEEN operator.
  77345. **
  77346. ** x BETWEEN y AND z
  77347. **
  77348. ** The above is equivalent to
  77349. **
  77350. ** x>=y AND x<=z
  77351. **
  77352. ** Code it as such, taking care to do the common subexpression
  77353. ** elementation of x.
  77354. */
  77355. static void exprCodeBetween(
  77356. Parse *pParse, /* Parsing and code generating context */
  77357. Expr *pExpr, /* The BETWEEN expression */
  77358. int dest, /* Jump here if the jump is taken */
  77359. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  77360. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  77361. ){
  77362. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  77363. Expr compLeft; /* The x>=y term */
  77364. Expr compRight; /* The x<=z term */
  77365. Expr exprX; /* The x subexpression */
  77366. int regFree1 = 0; /* Temporary use register */
  77367. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77368. exprX = *pExpr->pLeft;
  77369. exprAnd.op = TK_AND;
  77370. exprAnd.pLeft = &compLeft;
  77371. exprAnd.pRight = &compRight;
  77372. compLeft.op = TK_GE;
  77373. compLeft.pLeft = &exprX;
  77374. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  77375. compRight.op = TK_LE;
  77376. compRight.pLeft = &exprX;
  77377. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  77378. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  77379. if( jumpIfTrue ){
  77380. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  77381. }else{
  77382. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  77383. }
  77384. sqlite3ReleaseTempReg(pParse, regFree1);
  77385. /* Ensure adequate test coverage */
  77386. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  77387. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  77388. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  77389. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  77390. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  77391. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  77392. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  77393. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  77394. }
  77395. /*
  77396. ** Generate code for a boolean expression such that a jump is made
  77397. ** to the label "dest" if the expression is true but execution
  77398. ** continues straight thru if the expression is false.
  77399. **
  77400. ** If the expression evaluates to NULL (neither true nor false), then
  77401. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  77402. **
  77403. ** This code depends on the fact that certain token values (ex: TK_EQ)
  77404. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  77405. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  77406. ** the make process cause these values to align. Assert()s in the code
  77407. ** below verify that the numbers are aligned correctly.
  77408. */
  77409. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  77410. Vdbe *v = pParse->pVdbe;
  77411. int op = 0;
  77412. int regFree1 = 0;
  77413. int regFree2 = 0;
  77414. int r1, r2;
  77415. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  77416. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  77417. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  77418. op = pExpr->op;
  77419. switch( op ){
  77420. case TK_AND: {
  77421. int d2 = sqlite3VdbeMakeLabel(v);
  77422. testcase( jumpIfNull==0 );
  77423. sqlite3ExprCachePush(pParse);
  77424. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  77425. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  77426. sqlite3VdbeResolveLabel(v, d2);
  77427. sqlite3ExprCachePop(pParse, 1);
  77428. break;
  77429. }
  77430. case TK_OR: {
  77431. testcase( jumpIfNull==0 );
  77432. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  77433. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  77434. break;
  77435. }
  77436. case TK_NOT: {
  77437. testcase( jumpIfNull==0 );
  77438. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  77439. break;
  77440. }
  77441. case TK_LT:
  77442. case TK_LE:
  77443. case TK_GT:
  77444. case TK_GE:
  77445. case TK_NE:
  77446. case TK_EQ: {
  77447. assert( TK_LT==OP_Lt );
  77448. assert( TK_LE==OP_Le );
  77449. assert( TK_GT==OP_Gt );
  77450. assert( TK_GE==OP_Ge );
  77451. assert( TK_EQ==OP_Eq );
  77452. assert( TK_NE==OP_Ne );
  77453. testcase( op==TK_LT );
  77454. testcase( op==TK_LE );
  77455. testcase( op==TK_GT );
  77456. testcase( op==TK_GE );
  77457. testcase( op==TK_EQ );
  77458. testcase( op==TK_NE );
  77459. testcase( jumpIfNull==0 );
  77460. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77461. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77462. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77463. r1, r2, dest, jumpIfNull);
  77464. testcase( regFree1==0 );
  77465. testcase( regFree2==0 );
  77466. break;
  77467. }
  77468. case TK_IS:
  77469. case TK_ISNOT: {
  77470. testcase( op==TK_IS );
  77471. testcase( op==TK_ISNOT );
  77472. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77473. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77474. op = (op==TK_IS) ? TK_EQ : TK_NE;
  77475. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77476. r1, r2, dest, SQLITE_NULLEQ);
  77477. testcase( regFree1==0 );
  77478. testcase( regFree2==0 );
  77479. break;
  77480. }
  77481. case TK_ISNULL:
  77482. case TK_NOTNULL: {
  77483. assert( TK_ISNULL==OP_IsNull );
  77484. assert( TK_NOTNULL==OP_NotNull );
  77485. testcase( op==TK_ISNULL );
  77486. testcase( op==TK_NOTNULL );
  77487. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77488. sqlite3VdbeAddOp2(v, op, r1, dest);
  77489. testcase( regFree1==0 );
  77490. break;
  77491. }
  77492. case TK_BETWEEN: {
  77493. testcase( jumpIfNull==0 );
  77494. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  77495. break;
  77496. }
  77497. #ifndef SQLITE_OMIT_SUBQUERY
  77498. case TK_IN: {
  77499. int destIfFalse = sqlite3VdbeMakeLabel(v);
  77500. int destIfNull = jumpIfNull ? dest : destIfFalse;
  77501. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  77502. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  77503. sqlite3VdbeResolveLabel(v, destIfFalse);
  77504. break;
  77505. }
  77506. #endif
  77507. default: {
  77508. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  77509. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  77510. testcase( regFree1==0 );
  77511. testcase( jumpIfNull==0 );
  77512. break;
  77513. }
  77514. }
  77515. sqlite3ReleaseTempReg(pParse, regFree1);
  77516. sqlite3ReleaseTempReg(pParse, regFree2);
  77517. }
  77518. /*
  77519. ** Generate code for a boolean expression such that a jump is made
  77520. ** to the label "dest" if the expression is false but execution
  77521. ** continues straight thru if the expression is true.
  77522. **
  77523. ** If the expression evaluates to NULL (neither true nor false) then
  77524. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  77525. ** is 0.
  77526. */
  77527. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  77528. Vdbe *v = pParse->pVdbe;
  77529. int op = 0;
  77530. int regFree1 = 0;
  77531. int regFree2 = 0;
  77532. int r1, r2;
  77533. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  77534. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  77535. if( pExpr==0 ) return;
  77536. /* The value of pExpr->op and op are related as follows:
  77537. **
  77538. ** pExpr->op op
  77539. ** --------- ----------
  77540. ** TK_ISNULL OP_NotNull
  77541. ** TK_NOTNULL OP_IsNull
  77542. ** TK_NE OP_Eq
  77543. ** TK_EQ OP_Ne
  77544. ** TK_GT OP_Le
  77545. ** TK_LE OP_Gt
  77546. ** TK_GE OP_Lt
  77547. ** TK_LT OP_Ge
  77548. **
  77549. ** For other values of pExpr->op, op is undefined and unused.
  77550. ** The value of TK_ and OP_ constants are arranged such that we
  77551. ** can compute the mapping above using the following expression.
  77552. ** Assert()s verify that the computation is correct.
  77553. */
  77554. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  77555. /* Verify correct alignment of TK_ and OP_ constants
  77556. */
  77557. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  77558. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  77559. assert( pExpr->op!=TK_NE || op==OP_Eq );
  77560. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  77561. assert( pExpr->op!=TK_LT || op==OP_Ge );
  77562. assert( pExpr->op!=TK_LE || op==OP_Gt );
  77563. assert( pExpr->op!=TK_GT || op==OP_Le );
  77564. assert( pExpr->op!=TK_GE || op==OP_Lt );
  77565. switch( pExpr->op ){
  77566. case TK_AND: {
  77567. testcase( jumpIfNull==0 );
  77568. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  77569. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  77570. break;
  77571. }
  77572. case TK_OR: {
  77573. int d2 = sqlite3VdbeMakeLabel(v);
  77574. testcase( jumpIfNull==0 );
  77575. sqlite3ExprCachePush(pParse);
  77576. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  77577. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  77578. sqlite3VdbeResolveLabel(v, d2);
  77579. sqlite3ExprCachePop(pParse, 1);
  77580. break;
  77581. }
  77582. case TK_NOT: {
  77583. testcase( jumpIfNull==0 );
  77584. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  77585. break;
  77586. }
  77587. case TK_LT:
  77588. case TK_LE:
  77589. case TK_GT:
  77590. case TK_GE:
  77591. case TK_NE:
  77592. case TK_EQ: {
  77593. testcase( op==TK_LT );
  77594. testcase( op==TK_LE );
  77595. testcase( op==TK_GT );
  77596. testcase( op==TK_GE );
  77597. testcase( op==TK_EQ );
  77598. testcase( op==TK_NE );
  77599. testcase( jumpIfNull==0 );
  77600. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77601. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77602. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77603. r1, r2, dest, jumpIfNull);
  77604. testcase( regFree1==0 );
  77605. testcase( regFree2==0 );
  77606. break;
  77607. }
  77608. case TK_IS:
  77609. case TK_ISNOT: {
  77610. testcase( pExpr->op==TK_IS );
  77611. testcase( pExpr->op==TK_ISNOT );
  77612. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77613. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77614. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  77615. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77616. r1, r2, dest, SQLITE_NULLEQ);
  77617. testcase( regFree1==0 );
  77618. testcase( regFree2==0 );
  77619. break;
  77620. }
  77621. case TK_ISNULL:
  77622. case TK_NOTNULL: {
  77623. testcase( op==TK_ISNULL );
  77624. testcase( op==TK_NOTNULL );
  77625. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77626. sqlite3VdbeAddOp2(v, op, r1, dest);
  77627. testcase( regFree1==0 );
  77628. break;
  77629. }
  77630. case TK_BETWEEN: {
  77631. testcase( jumpIfNull==0 );
  77632. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  77633. break;
  77634. }
  77635. #ifndef SQLITE_OMIT_SUBQUERY
  77636. case TK_IN: {
  77637. if( jumpIfNull ){
  77638. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  77639. }else{
  77640. int destIfNull = sqlite3VdbeMakeLabel(v);
  77641. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  77642. sqlite3VdbeResolveLabel(v, destIfNull);
  77643. }
  77644. break;
  77645. }
  77646. #endif
  77647. default: {
  77648. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  77649. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  77650. testcase( regFree1==0 );
  77651. testcase( jumpIfNull==0 );
  77652. break;
  77653. }
  77654. }
  77655. sqlite3ReleaseTempReg(pParse, regFree1);
  77656. sqlite3ReleaseTempReg(pParse, regFree2);
  77657. }
  77658. /*
  77659. ** Do a deep comparison of two expression trees. Return 0 if the two
  77660. ** expressions are completely identical. Return 1 if they differ only
  77661. ** by a COLLATE operator at the top level. Return 2 if there are differences
  77662. ** other than the top-level COLLATE operator.
  77663. **
  77664. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  77665. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  77666. **
  77667. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  77668. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  77669. **
  77670. ** Sometimes this routine will return 2 even if the two expressions
  77671. ** really are equivalent. If we cannot prove that the expressions are
  77672. ** identical, we return 2 just to be safe. So if this routine
  77673. ** returns 2, then you do not really know for certain if the two
  77674. ** expressions are the same. But if you get a 0 or 1 return, then you
  77675. ** can be sure the expressions are the same. In the places where
  77676. ** this routine is used, it does not hurt to get an extra 2 - that
  77677. ** just might result in some slightly slower code. But returning
  77678. ** an incorrect 0 or 1 could lead to a malfunction.
  77679. */
  77680. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  77681. if( pA==0||pB==0 ){
  77682. return pB==pA ? 0 : 2;
  77683. }
  77684. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  77685. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  77686. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  77687. return 2;
  77688. }
  77689. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  77690. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  77691. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  77692. return 1;
  77693. }
  77694. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  77695. return 1;
  77696. }
  77697. return 2;
  77698. }
  77699. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  77700. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  77701. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  77702. if( pA->iColumn!=pB->iColumn ) return 2;
  77703. if( pA->iTable!=pB->iTable
  77704. && pA->op!=TK_REGISTER
  77705. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  77706. if( ExprHasProperty(pA, EP_IntValue) ){
  77707. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  77708. return 2;
  77709. }
  77710. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  77711. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  77712. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  77713. return pA->op==TK_COLLATE ? 1 : 2;
  77714. }
  77715. }
  77716. return 0;
  77717. }
  77718. /*
  77719. ** Compare two ExprList objects. Return 0 if they are identical and
  77720. ** non-zero if they differ in any way.
  77721. **
  77722. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  77723. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  77724. **
  77725. ** This routine might return non-zero for equivalent ExprLists. The
  77726. ** only consequence will be disabled optimizations. But this routine
  77727. ** must never return 0 if the two ExprList objects are different, or
  77728. ** a malfunction will result.
  77729. **
  77730. ** Two NULL pointers are considered to be the same. But a NULL pointer
  77731. ** always differs from a non-NULL pointer.
  77732. */
  77733. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  77734. int i;
  77735. if( pA==0 && pB==0 ) return 0;
  77736. if( pA==0 || pB==0 ) return 1;
  77737. if( pA->nExpr!=pB->nExpr ) return 1;
  77738. for(i=0; i<pA->nExpr; i++){
  77739. Expr *pExprA = pA->a[i].pExpr;
  77740. Expr *pExprB = pB->a[i].pExpr;
  77741. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  77742. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  77743. }
  77744. return 0;
  77745. }
  77746. /*
  77747. ** Return true if we can prove the pE2 will always be true if pE1 is
  77748. ** true. Return false if we cannot complete the proof or if pE2 might
  77749. ** be false. Examples:
  77750. **
  77751. ** pE1: x==5 pE2: x==5 Result: true
  77752. ** pE1: x>0 pE2: x==5 Result: false
  77753. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  77754. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  77755. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  77756. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  77757. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  77758. **
  77759. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  77760. ** Expr.iTable<0 then assume a table number given by iTab.
  77761. **
  77762. ** When in doubt, return false. Returning true might give a performance
  77763. ** improvement. Returning false might cause a performance reduction, but
  77764. ** it will always give the correct answer and is hence always safe.
  77765. */
  77766. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  77767. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  77768. return 1;
  77769. }
  77770. if( pE2->op==TK_OR
  77771. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  77772. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  77773. ){
  77774. return 1;
  77775. }
  77776. if( pE2->op==TK_NOTNULL
  77777. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  77778. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  77779. ){
  77780. return 1;
  77781. }
  77782. return 0;
  77783. }
  77784. /*
  77785. ** An instance of the following structure is used by the tree walker
  77786. ** to count references to table columns in the arguments of an
  77787. ** aggregate function, in order to implement the
  77788. ** sqlite3FunctionThisSrc() routine.
  77789. */
  77790. struct SrcCount {
  77791. SrcList *pSrc; /* One particular FROM clause in a nested query */
  77792. int nThis; /* Number of references to columns in pSrcList */
  77793. int nOther; /* Number of references to columns in other FROM clauses */
  77794. };
  77795. /*
  77796. ** Count the number of references to columns.
  77797. */
  77798. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  77799. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  77800. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  77801. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  77802. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  77803. ** NEVER() will need to be removed. */
  77804. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  77805. int i;
  77806. struct SrcCount *p = pWalker->u.pSrcCount;
  77807. SrcList *pSrc = p->pSrc;
  77808. for(i=0; i<pSrc->nSrc; i++){
  77809. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  77810. }
  77811. if( i<pSrc->nSrc ){
  77812. p->nThis++;
  77813. }else{
  77814. p->nOther++;
  77815. }
  77816. }
  77817. return WRC_Continue;
  77818. }
  77819. /*
  77820. ** Determine if any of the arguments to the pExpr Function reference
  77821. ** pSrcList. Return true if they do. Also return true if the function
  77822. ** has no arguments or has only constant arguments. Return false if pExpr
  77823. ** references columns but not columns of tables found in pSrcList.
  77824. */
  77825. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  77826. Walker w;
  77827. struct SrcCount cnt;
  77828. assert( pExpr->op==TK_AGG_FUNCTION );
  77829. memset(&w, 0, sizeof(w));
  77830. w.xExprCallback = exprSrcCount;
  77831. w.u.pSrcCount = &cnt;
  77832. cnt.pSrc = pSrcList;
  77833. cnt.nThis = 0;
  77834. cnt.nOther = 0;
  77835. sqlite3WalkExprList(&w, pExpr->x.pList);
  77836. return cnt.nThis>0 || cnt.nOther==0;
  77837. }
  77838. /*
  77839. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  77840. ** the new element. Return a negative number if malloc fails.
  77841. */
  77842. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  77843. int i;
  77844. pInfo->aCol = sqlite3ArrayAllocate(
  77845. db,
  77846. pInfo->aCol,
  77847. sizeof(pInfo->aCol[0]),
  77848. &pInfo->nColumn,
  77849. &i
  77850. );
  77851. return i;
  77852. }
  77853. /*
  77854. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  77855. ** the new element. Return a negative number if malloc fails.
  77856. */
  77857. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  77858. int i;
  77859. pInfo->aFunc = sqlite3ArrayAllocate(
  77860. db,
  77861. pInfo->aFunc,
  77862. sizeof(pInfo->aFunc[0]),
  77863. &pInfo->nFunc,
  77864. &i
  77865. );
  77866. return i;
  77867. }
  77868. /*
  77869. ** This is the xExprCallback for a tree walker. It is used to
  77870. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  77871. ** for additional information.
  77872. */
  77873. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  77874. int i;
  77875. NameContext *pNC = pWalker->u.pNC;
  77876. Parse *pParse = pNC->pParse;
  77877. SrcList *pSrcList = pNC->pSrcList;
  77878. AggInfo *pAggInfo = pNC->pAggInfo;
  77879. switch( pExpr->op ){
  77880. case TK_AGG_COLUMN:
  77881. case TK_COLUMN: {
  77882. testcase( pExpr->op==TK_AGG_COLUMN );
  77883. testcase( pExpr->op==TK_COLUMN );
  77884. /* Check to see if the column is in one of the tables in the FROM
  77885. ** clause of the aggregate query */
  77886. if( ALWAYS(pSrcList!=0) ){
  77887. struct SrcList_item *pItem = pSrcList->a;
  77888. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  77889. struct AggInfo_col *pCol;
  77890. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  77891. if( pExpr->iTable==pItem->iCursor ){
  77892. /* If we reach this point, it means that pExpr refers to a table
  77893. ** that is in the FROM clause of the aggregate query.
  77894. **
  77895. ** Make an entry for the column in pAggInfo->aCol[] if there
  77896. ** is not an entry there already.
  77897. */
  77898. int k;
  77899. pCol = pAggInfo->aCol;
  77900. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  77901. if( pCol->iTable==pExpr->iTable &&
  77902. pCol->iColumn==pExpr->iColumn ){
  77903. break;
  77904. }
  77905. }
  77906. if( (k>=pAggInfo->nColumn)
  77907. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  77908. ){
  77909. pCol = &pAggInfo->aCol[k];
  77910. pCol->pTab = pExpr->pTab;
  77911. pCol->iTable = pExpr->iTable;
  77912. pCol->iColumn = pExpr->iColumn;
  77913. pCol->iMem = ++pParse->nMem;
  77914. pCol->iSorterColumn = -1;
  77915. pCol->pExpr = pExpr;
  77916. if( pAggInfo->pGroupBy ){
  77917. int j, n;
  77918. ExprList *pGB = pAggInfo->pGroupBy;
  77919. struct ExprList_item *pTerm = pGB->a;
  77920. n = pGB->nExpr;
  77921. for(j=0; j<n; j++, pTerm++){
  77922. Expr *pE = pTerm->pExpr;
  77923. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  77924. pE->iColumn==pExpr->iColumn ){
  77925. pCol->iSorterColumn = j;
  77926. break;
  77927. }
  77928. }
  77929. }
  77930. if( pCol->iSorterColumn<0 ){
  77931. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  77932. }
  77933. }
  77934. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  77935. ** because it was there before or because we just created it).
  77936. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  77937. ** pAggInfo->aCol[] entry.
  77938. */
  77939. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77940. pExpr->pAggInfo = pAggInfo;
  77941. pExpr->op = TK_AGG_COLUMN;
  77942. pExpr->iAgg = (i16)k;
  77943. break;
  77944. } /* endif pExpr->iTable==pItem->iCursor */
  77945. } /* end loop over pSrcList */
  77946. }
  77947. return WRC_Prune;
  77948. }
  77949. case TK_AGG_FUNCTION: {
  77950. if( (pNC->ncFlags & NC_InAggFunc)==0
  77951. && pWalker->walkerDepth==pExpr->op2
  77952. ){
  77953. /* Check to see if pExpr is a duplicate of another aggregate
  77954. ** function that is already in the pAggInfo structure
  77955. */
  77956. struct AggInfo_func *pItem = pAggInfo->aFunc;
  77957. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  77958. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  77959. break;
  77960. }
  77961. }
  77962. if( i>=pAggInfo->nFunc ){
  77963. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  77964. */
  77965. u8 enc = ENC(pParse->db);
  77966. i = addAggInfoFunc(pParse->db, pAggInfo);
  77967. if( i>=0 ){
  77968. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77969. pItem = &pAggInfo->aFunc[i];
  77970. pItem->pExpr = pExpr;
  77971. pItem->iMem = ++pParse->nMem;
  77972. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77973. pItem->pFunc = sqlite3FindFunction(pParse->db,
  77974. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  77975. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  77976. if( pExpr->flags & EP_Distinct ){
  77977. pItem->iDistinct = pParse->nTab++;
  77978. }else{
  77979. pItem->iDistinct = -1;
  77980. }
  77981. }
  77982. }
  77983. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  77984. */
  77985. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  77986. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77987. pExpr->iAgg = (i16)i;
  77988. pExpr->pAggInfo = pAggInfo;
  77989. return WRC_Prune;
  77990. }else{
  77991. return WRC_Continue;
  77992. }
  77993. }
  77994. }
  77995. return WRC_Continue;
  77996. }
  77997. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  77998. UNUSED_PARAMETER(pWalker);
  77999. UNUSED_PARAMETER(pSelect);
  78000. return WRC_Continue;
  78001. }
  78002. /*
  78003. ** Analyze the pExpr expression looking for aggregate functions and
  78004. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  78005. ** points to. Additional entries are made on the AggInfo object as
  78006. ** necessary.
  78007. **
  78008. ** This routine should only be called after the expression has been
  78009. ** analyzed by sqlite3ResolveExprNames().
  78010. */
  78011. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  78012. Walker w;
  78013. memset(&w, 0, sizeof(w));
  78014. w.xExprCallback = analyzeAggregate;
  78015. w.xSelectCallback = analyzeAggregatesInSelect;
  78016. w.u.pNC = pNC;
  78017. assert( pNC->pSrcList!=0 );
  78018. sqlite3WalkExpr(&w, pExpr);
  78019. }
  78020. /*
  78021. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  78022. ** expression list. Return the number of errors.
  78023. **
  78024. ** If an error is found, the analysis is cut short.
  78025. */
  78026. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  78027. struct ExprList_item *pItem;
  78028. int i;
  78029. if( pList ){
  78030. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  78031. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  78032. }
  78033. }
  78034. }
  78035. /*
  78036. ** Allocate a single new register for use to hold some intermediate result.
  78037. */
  78038. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  78039. if( pParse->nTempReg==0 ){
  78040. return ++pParse->nMem;
  78041. }
  78042. return pParse->aTempReg[--pParse->nTempReg];
  78043. }
  78044. /*
  78045. ** Deallocate a register, making available for reuse for some other
  78046. ** purpose.
  78047. **
  78048. ** If a register is currently being used by the column cache, then
  78049. ** the dallocation is deferred until the column cache line that uses
  78050. ** the register becomes stale.
  78051. */
  78052. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  78053. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  78054. int i;
  78055. struct yColCache *p;
  78056. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  78057. if( p->iReg==iReg ){
  78058. p->tempReg = 1;
  78059. return;
  78060. }
  78061. }
  78062. pParse->aTempReg[pParse->nTempReg++] = iReg;
  78063. }
  78064. }
  78065. /*
  78066. ** Allocate or deallocate a block of nReg consecutive registers
  78067. */
  78068. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  78069. int i, n;
  78070. i = pParse->iRangeReg;
  78071. n = pParse->nRangeReg;
  78072. if( nReg<=n ){
  78073. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  78074. pParse->iRangeReg += nReg;
  78075. pParse->nRangeReg -= nReg;
  78076. }else{
  78077. i = pParse->nMem+1;
  78078. pParse->nMem += nReg;
  78079. }
  78080. return i;
  78081. }
  78082. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  78083. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  78084. if( nReg>pParse->nRangeReg ){
  78085. pParse->nRangeReg = nReg;
  78086. pParse->iRangeReg = iReg;
  78087. }
  78088. }
  78089. /*
  78090. ** Mark all temporary registers as being unavailable for reuse.
  78091. */
  78092. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  78093. pParse->nTempReg = 0;
  78094. pParse->nRangeReg = 0;
  78095. }
  78096. /************** End of expr.c ************************************************/
  78097. /************** Begin file alter.c *******************************************/
  78098. /*
  78099. ** 2005 February 15
  78100. **
  78101. ** The author disclaims copyright to this source code. In place of
  78102. ** a legal notice, here is a blessing:
  78103. **
  78104. ** May you do good and not evil.
  78105. ** May you find forgiveness for yourself and forgive others.
  78106. ** May you share freely, never taking more than you give.
  78107. **
  78108. *************************************************************************
  78109. ** This file contains C code routines that used to generate VDBE code
  78110. ** that implements the ALTER TABLE command.
  78111. */
  78112. /*
  78113. ** The code in this file only exists if we are not omitting the
  78114. ** ALTER TABLE logic from the build.
  78115. */
  78116. #ifndef SQLITE_OMIT_ALTERTABLE
  78117. /*
  78118. ** This function is used by SQL generated to implement the
  78119. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  78120. ** CREATE INDEX command. The second is a table name. The table name in
  78121. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  78122. ** argument and the result returned. Examples:
  78123. **
  78124. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  78125. ** -> 'CREATE TABLE def(a, b, c)'
  78126. **
  78127. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  78128. ** -> 'CREATE INDEX i ON def(a, b, c)'
  78129. */
  78130. static void renameTableFunc(
  78131. sqlite3_context *context,
  78132. int NotUsed,
  78133. sqlite3_value **argv
  78134. ){
  78135. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  78136. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  78137. int token;
  78138. Token tname;
  78139. unsigned char const *zCsr = zSql;
  78140. int len = 0;
  78141. char *zRet;
  78142. sqlite3 *db = sqlite3_context_db_handle(context);
  78143. UNUSED_PARAMETER(NotUsed);
  78144. /* The principle used to locate the table name in the CREATE TABLE
  78145. ** statement is that the table name is the first non-space token that
  78146. ** is immediately followed by a TK_LP or TK_USING token.
  78147. */
  78148. if( zSql ){
  78149. do {
  78150. if( !*zCsr ){
  78151. /* Ran out of input before finding an opening bracket. Return NULL. */
  78152. return;
  78153. }
  78154. /* Store the token that zCsr points to in tname. */
  78155. tname.z = (char*)zCsr;
  78156. tname.n = len;
  78157. /* Advance zCsr to the next token. Store that token type in 'token',
  78158. ** and its length in 'len' (to be used next iteration of this loop).
  78159. */
  78160. do {
  78161. zCsr += len;
  78162. len = sqlite3GetToken(zCsr, &token);
  78163. } while( token==TK_SPACE );
  78164. assert( len>0 );
  78165. } while( token!=TK_LP && token!=TK_USING );
  78166. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  78167. zTableName, tname.z+tname.n);
  78168. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  78169. }
  78170. }
  78171. /*
  78172. ** This C function implements an SQL user function that is used by SQL code
  78173. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  78174. ** of any foreign key constraints that use the table being renamed as the
  78175. ** parent table. It is passed three arguments:
  78176. **
  78177. ** 1) The complete text of the CREATE TABLE statement being modified,
  78178. ** 2) The old name of the table being renamed, and
  78179. ** 3) The new name of the table being renamed.
  78180. **
  78181. ** It returns the new CREATE TABLE statement. For example:
  78182. **
  78183. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  78184. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  78185. */
  78186. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78187. static void renameParentFunc(
  78188. sqlite3_context *context,
  78189. int NotUsed,
  78190. sqlite3_value **argv
  78191. ){
  78192. sqlite3 *db = sqlite3_context_db_handle(context);
  78193. char *zOutput = 0;
  78194. char *zResult;
  78195. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  78196. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  78197. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  78198. unsigned const char *z; /* Pointer to token */
  78199. int n; /* Length of token z */
  78200. int token; /* Type of token */
  78201. UNUSED_PARAMETER(NotUsed);
  78202. for(z=zInput; *z; z=z+n){
  78203. n = sqlite3GetToken(z, &token);
  78204. if( token==TK_REFERENCES ){
  78205. char *zParent;
  78206. do {
  78207. z += n;
  78208. n = sqlite3GetToken(z, &token);
  78209. }while( token==TK_SPACE );
  78210. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  78211. if( zParent==0 ) break;
  78212. sqlite3Dequote(zParent);
  78213. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  78214. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  78215. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  78216. );
  78217. sqlite3DbFree(db, zOutput);
  78218. zOutput = zOut;
  78219. zInput = &z[n];
  78220. }
  78221. sqlite3DbFree(db, zParent);
  78222. }
  78223. }
  78224. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  78225. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  78226. sqlite3DbFree(db, zOutput);
  78227. }
  78228. #endif
  78229. #ifndef SQLITE_OMIT_TRIGGER
  78230. /* This function is used by SQL generated to implement the
  78231. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  78232. ** statement. The second is a table name. The table name in the CREATE
  78233. ** TRIGGER statement is replaced with the third argument and the result
  78234. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  78235. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  78236. */
  78237. static void renameTriggerFunc(
  78238. sqlite3_context *context,
  78239. int NotUsed,
  78240. sqlite3_value **argv
  78241. ){
  78242. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  78243. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  78244. int token;
  78245. Token tname;
  78246. int dist = 3;
  78247. unsigned char const *zCsr = zSql;
  78248. int len = 0;
  78249. char *zRet;
  78250. sqlite3 *db = sqlite3_context_db_handle(context);
  78251. UNUSED_PARAMETER(NotUsed);
  78252. /* The principle used to locate the table name in the CREATE TRIGGER
  78253. ** statement is that the table name is the first token that is immediatedly
  78254. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  78255. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  78256. */
  78257. if( zSql ){
  78258. do {
  78259. if( !*zCsr ){
  78260. /* Ran out of input before finding the table name. Return NULL. */
  78261. return;
  78262. }
  78263. /* Store the token that zCsr points to in tname. */
  78264. tname.z = (char*)zCsr;
  78265. tname.n = len;
  78266. /* Advance zCsr to the next token. Store that token type in 'token',
  78267. ** and its length in 'len' (to be used next iteration of this loop).
  78268. */
  78269. do {
  78270. zCsr += len;
  78271. len = sqlite3GetToken(zCsr, &token);
  78272. }while( token==TK_SPACE );
  78273. assert( len>0 );
  78274. /* Variable 'dist' stores the number of tokens read since the most
  78275. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  78276. ** token is read and 'dist' equals 2, the condition stated above
  78277. ** to be met.
  78278. **
  78279. ** Note that ON cannot be a database, table or column name, so
  78280. ** there is no need to worry about syntax like
  78281. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  78282. */
  78283. dist++;
  78284. if( token==TK_DOT || token==TK_ON ){
  78285. dist = 0;
  78286. }
  78287. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  78288. /* Variable tname now contains the token that is the old table-name
  78289. ** in the CREATE TRIGGER statement.
  78290. */
  78291. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  78292. zTableName, tname.z+tname.n);
  78293. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  78294. }
  78295. }
  78296. #endif /* !SQLITE_OMIT_TRIGGER */
  78297. /*
  78298. ** Register built-in functions used to help implement ALTER TABLE
  78299. */
  78300. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  78301. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  78302. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  78303. #ifndef SQLITE_OMIT_TRIGGER
  78304. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  78305. #endif
  78306. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78307. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  78308. #endif
  78309. };
  78310. int i;
  78311. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  78312. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  78313. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  78314. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  78315. }
  78316. }
  78317. /*
  78318. ** This function is used to create the text of expressions of the form:
  78319. **
  78320. ** name=<constant1> OR name=<constant2> OR ...
  78321. **
  78322. ** If argument zWhere is NULL, then a pointer string containing the text
  78323. ** "name=<constant>" is returned, where <constant> is the quoted version
  78324. ** of the string passed as argument zConstant. The returned buffer is
  78325. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  78326. ** caller to ensure that it is eventually freed.
  78327. **
  78328. ** If argument zWhere is not NULL, then the string returned is
  78329. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  78330. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  78331. **
  78332. */
  78333. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  78334. char *zNew;
  78335. if( !zWhere ){
  78336. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  78337. }else{
  78338. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  78339. sqlite3DbFree(db, zWhere);
  78340. }
  78341. return zNew;
  78342. }
  78343. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78344. /*
  78345. ** Generate the text of a WHERE expression which can be used to select all
  78346. ** tables that have foreign key constraints that refer to table pTab (i.e.
  78347. ** constraints for which pTab is the parent table) from the sqlite_master
  78348. ** table.
  78349. */
  78350. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  78351. FKey *p;
  78352. char *zWhere = 0;
  78353. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78354. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  78355. }
  78356. return zWhere;
  78357. }
  78358. #endif
  78359. /*
  78360. ** Generate the text of a WHERE expression which can be used to select all
  78361. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  78362. ** table pTab has no temporary triggers, or is itself stored in the
  78363. ** temporary database, NULL is returned.
  78364. */
  78365. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  78366. Trigger *pTrig;
  78367. char *zWhere = 0;
  78368. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  78369. /* If the table is not located in the temp-db (in which case NULL is
  78370. ** returned, loop through the tables list of triggers. For each trigger
  78371. ** that is not part of the temp-db schema, add a clause to the WHERE
  78372. ** expression being built up in zWhere.
  78373. */
  78374. if( pTab->pSchema!=pTempSchema ){
  78375. sqlite3 *db = pParse->db;
  78376. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  78377. if( pTrig->pSchema==pTempSchema ){
  78378. zWhere = whereOrName(db, zWhere, pTrig->zName);
  78379. }
  78380. }
  78381. }
  78382. if( zWhere ){
  78383. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  78384. sqlite3DbFree(pParse->db, zWhere);
  78385. zWhere = zNew;
  78386. }
  78387. return zWhere;
  78388. }
  78389. /*
  78390. ** Generate code to drop and reload the internal representation of table
  78391. ** pTab from the database, including triggers and temporary triggers.
  78392. ** Argument zName is the name of the table in the database schema at
  78393. ** the time the generated code is executed. This can be different from
  78394. ** pTab->zName if this function is being called to code part of an
  78395. ** "ALTER TABLE RENAME TO" statement.
  78396. */
  78397. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  78398. Vdbe *v;
  78399. char *zWhere;
  78400. int iDb; /* Index of database containing pTab */
  78401. #ifndef SQLITE_OMIT_TRIGGER
  78402. Trigger *pTrig;
  78403. #endif
  78404. v = sqlite3GetVdbe(pParse);
  78405. if( NEVER(v==0) ) return;
  78406. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  78407. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78408. assert( iDb>=0 );
  78409. #ifndef SQLITE_OMIT_TRIGGER
  78410. /* Drop any table triggers from the internal schema. */
  78411. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  78412. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  78413. assert( iTrigDb==iDb || iTrigDb==1 );
  78414. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  78415. }
  78416. #endif
  78417. /* Drop the table and index from the internal schema. */
  78418. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  78419. /* Reload the table, index and permanent trigger schemas. */
  78420. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  78421. if( !zWhere ) return;
  78422. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  78423. #ifndef SQLITE_OMIT_TRIGGER
  78424. /* Now, if the table is not stored in the temp database, reload any temp
  78425. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  78426. */
  78427. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  78428. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  78429. }
  78430. #endif
  78431. }
  78432. /*
  78433. ** Parameter zName is the name of a table that is about to be altered
  78434. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  78435. ** If the table is a system table, this function leaves an error message
  78436. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  78437. **
  78438. ** Or, if zName is not a system table, zero is returned.
  78439. */
  78440. static int isSystemTable(Parse *pParse, const char *zName){
  78441. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  78442. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  78443. return 1;
  78444. }
  78445. return 0;
  78446. }
  78447. /*
  78448. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  78449. ** command.
  78450. */
  78451. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  78452. Parse *pParse, /* Parser context. */
  78453. SrcList *pSrc, /* The table to rename. */
  78454. Token *pName /* The new table name. */
  78455. ){
  78456. int iDb; /* Database that contains the table */
  78457. char *zDb; /* Name of database iDb */
  78458. Table *pTab; /* Table being renamed */
  78459. char *zName = 0; /* NULL-terminated version of pName */
  78460. sqlite3 *db = pParse->db; /* Database connection */
  78461. int nTabName; /* Number of UTF-8 characters in zTabName */
  78462. const char *zTabName; /* Original name of the table */
  78463. Vdbe *v;
  78464. #ifndef SQLITE_OMIT_TRIGGER
  78465. char *zWhere = 0; /* Where clause to locate temp triggers */
  78466. #endif
  78467. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  78468. int savedDbFlags; /* Saved value of db->flags */
  78469. savedDbFlags = db->flags;
  78470. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  78471. assert( pSrc->nSrc==1 );
  78472. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  78473. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  78474. if( !pTab ) goto exit_rename_table;
  78475. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78476. zDb = db->aDb[iDb].zName;
  78477. db->flags |= SQLITE_PreferBuiltin;
  78478. /* Get a NULL terminated version of the new table name. */
  78479. zName = sqlite3NameFromToken(db, pName);
  78480. if( !zName ) goto exit_rename_table;
  78481. /* Check that a table or index named 'zName' does not already exist
  78482. ** in database iDb. If so, this is an error.
  78483. */
  78484. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  78485. sqlite3ErrorMsg(pParse,
  78486. "there is already another table or index with this name: %s", zName);
  78487. goto exit_rename_table;
  78488. }
  78489. /* Make sure it is not a system table being altered, or a reserved name
  78490. ** that the table is being renamed to.
  78491. */
  78492. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  78493. goto exit_rename_table;
  78494. }
  78495. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  78496. exit_rename_table;
  78497. }
  78498. #ifndef SQLITE_OMIT_VIEW
  78499. if( pTab->pSelect ){
  78500. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  78501. goto exit_rename_table;
  78502. }
  78503. #endif
  78504. #ifndef SQLITE_OMIT_AUTHORIZATION
  78505. /* Invoke the authorization callback. */
  78506. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  78507. goto exit_rename_table;
  78508. }
  78509. #endif
  78510. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78511. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  78512. goto exit_rename_table;
  78513. }
  78514. if( IsVirtual(pTab) ){
  78515. pVTab = sqlite3GetVTable(db, pTab);
  78516. if( pVTab->pVtab->pModule->xRename==0 ){
  78517. pVTab = 0;
  78518. }
  78519. }
  78520. #endif
  78521. /* Begin a transaction and code the VerifyCookie for database iDb.
  78522. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  78523. ** schema). Open a statement transaction if the table is a virtual
  78524. ** table.
  78525. */
  78526. v = sqlite3GetVdbe(pParse);
  78527. if( v==0 ){
  78528. goto exit_rename_table;
  78529. }
  78530. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  78531. sqlite3ChangeCookie(pParse, iDb);
  78532. /* If this is a virtual table, invoke the xRename() function if
  78533. ** one is defined. The xRename() callback will modify the names
  78534. ** of any resources used by the v-table implementation (including other
  78535. ** SQLite tables) that are identified by the name of the virtual table.
  78536. */
  78537. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78538. if( pVTab ){
  78539. int i = ++pParse->nMem;
  78540. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  78541. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  78542. sqlite3MayAbort(pParse);
  78543. }
  78544. #endif
  78545. /* figure out how many UTF-8 characters are in zName */
  78546. zTabName = pTab->zName;
  78547. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  78548. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78549. if( db->flags&SQLITE_ForeignKeys ){
  78550. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  78551. ** statements corresponding to all child tables of foreign key constraints
  78552. ** for which the renamed table is the parent table. */
  78553. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  78554. sqlite3NestedParse(pParse,
  78555. "UPDATE \"%w\".%s SET "
  78556. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  78557. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  78558. sqlite3DbFree(db, zWhere);
  78559. }
  78560. }
  78561. #endif
  78562. /* Modify the sqlite_master table to use the new table name. */
  78563. sqlite3NestedParse(pParse,
  78564. "UPDATE %Q.%s SET "
  78565. #ifdef SQLITE_OMIT_TRIGGER
  78566. "sql = sqlite_rename_table(sql, %Q), "
  78567. #else
  78568. "sql = CASE "
  78569. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  78570. "ELSE sqlite_rename_table(sql, %Q) END, "
  78571. #endif
  78572. "tbl_name = %Q, "
  78573. "name = CASE "
  78574. "WHEN type='table' THEN %Q "
  78575. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  78576. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  78577. "ELSE name END "
  78578. "WHERE tbl_name=%Q COLLATE nocase AND "
  78579. "(type='table' OR type='index' OR type='trigger');",
  78580. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  78581. #ifndef SQLITE_OMIT_TRIGGER
  78582. zName,
  78583. #endif
  78584. zName, nTabName, zTabName
  78585. );
  78586. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78587. /* If the sqlite_sequence table exists in this database, then update
  78588. ** it with the new table name.
  78589. */
  78590. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  78591. sqlite3NestedParse(pParse,
  78592. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  78593. zDb, zName, pTab->zName);
  78594. }
  78595. #endif
  78596. #ifndef SQLITE_OMIT_TRIGGER
  78597. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  78598. ** table. Don't do this if the table being ALTERed is itself located in
  78599. ** the temp database.
  78600. */
  78601. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  78602. sqlite3NestedParse(pParse,
  78603. "UPDATE sqlite_temp_master SET "
  78604. "sql = sqlite_rename_trigger(sql, %Q), "
  78605. "tbl_name = %Q "
  78606. "WHERE %s;", zName, zName, zWhere);
  78607. sqlite3DbFree(db, zWhere);
  78608. }
  78609. #endif
  78610. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78611. if( db->flags&SQLITE_ForeignKeys ){
  78612. FKey *p;
  78613. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78614. Table *pFrom = p->pFrom;
  78615. if( pFrom!=pTab ){
  78616. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  78617. }
  78618. }
  78619. }
  78620. #endif
  78621. /* Drop and reload the internal table schema. */
  78622. reloadTableSchema(pParse, pTab, zName);
  78623. exit_rename_table:
  78624. sqlite3SrcListDelete(db, pSrc);
  78625. sqlite3DbFree(db, zName);
  78626. db->flags = savedDbFlags;
  78627. }
  78628. /*
  78629. ** Generate code to make sure the file format number is at least minFormat.
  78630. ** The generated code will increase the file format number if necessary.
  78631. */
  78632. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  78633. Vdbe *v;
  78634. v = sqlite3GetVdbe(pParse);
  78635. /* The VDBE should have been allocated before this routine is called.
  78636. ** If that allocation failed, we would have quit before reaching this
  78637. ** point */
  78638. if( ALWAYS(v) ){
  78639. int r1 = sqlite3GetTempReg(pParse);
  78640. int r2 = sqlite3GetTempReg(pParse);
  78641. int j1;
  78642. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  78643. sqlite3VdbeUsesBtree(v, iDb);
  78644. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  78645. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  78646. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  78647. sqlite3VdbeJumpHere(v, j1);
  78648. sqlite3ReleaseTempReg(pParse, r1);
  78649. sqlite3ReleaseTempReg(pParse, r2);
  78650. }
  78651. }
  78652. /*
  78653. ** This function is called after an "ALTER TABLE ... ADD" statement
  78654. ** has been parsed. Argument pColDef contains the text of the new
  78655. ** column definition.
  78656. **
  78657. ** The Table structure pParse->pNewTable was extended to include
  78658. ** the new column during parsing.
  78659. */
  78660. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  78661. Table *pNew; /* Copy of pParse->pNewTable */
  78662. Table *pTab; /* Table being altered */
  78663. int iDb; /* Database number */
  78664. const char *zDb; /* Database name */
  78665. const char *zTab; /* Table name */
  78666. char *zCol; /* Null-terminated column definition */
  78667. Column *pCol; /* The new column */
  78668. Expr *pDflt; /* Default value for the new column */
  78669. sqlite3 *db; /* The database connection; */
  78670. db = pParse->db;
  78671. if( pParse->nErr || db->mallocFailed ) return;
  78672. pNew = pParse->pNewTable;
  78673. assert( pNew );
  78674. assert( sqlite3BtreeHoldsAllMutexes(db) );
  78675. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  78676. zDb = db->aDb[iDb].zName;
  78677. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  78678. pCol = &pNew->aCol[pNew->nCol-1];
  78679. pDflt = pCol->pDflt;
  78680. pTab = sqlite3FindTable(db, zTab, zDb);
  78681. assert( pTab );
  78682. #ifndef SQLITE_OMIT_AUTHORIZATION
  78683. /* Invoke the authorization callback. */
  78684. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  78685. return;
  78686. }
  78687. #endif
  78688. /* If the default value for the new column was specified with a
  78689. ** literal NULL, then set pDflt to 0. This simplifies checking
  78690. ** for an SQL NULL default below.
  78691. */
  78692. if( pDflt && pDflt->op==TK_NULL ){
  78693. pDflt = 0;
  78694. }
  78695. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  78696. ** If there is a NOT NULL constraint, then the default value for the
  78697. ** column must not be NULL.
  78698. */
  78699. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  78700. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  78701. return;
  78702. }
  78703. if( pNew->pIndex ){
  78704. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  78705. return;
  78706. }
  78707. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  78708. sqlite3ErrorMsg(pParse,
  78709. "Cannot add a REFERENCES column with non-NULL default value");
  78710. return;
  78711. }
  78712. if( pCol->notNull && !pDflt ){
  78713. sqlite3ErrorMsg(pParse,
  78714. "Cannot add a NOT NULL column with default value NULL");
  78715. return;
  78716. }
  78717. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  78718. ** can handle (i.e. not CURRENT_TIME etc.)
  78719. */
  78720. if( pDflt ){
  78721. sqlite3_value *pVal = 0;
  78722. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  78723. db->mallocFailed = 1;
  78724. return;
  78725. }
  78726. if( !pVal ){
  78727. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  78728. return;
  78729. }
  78730. sqlite3ValueFree(pVal);
  78731. }
  78732. /* Modify the CREATE TABLE statement. */
  78733. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  78734. if( zCol ){
  78735. char *zEnd = &zCol[pColDef->n-1];
  78736. int savedDbFlags = db->flags;
  78737. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  78738. *zEnd-- = '\0';
  78739. }
  78740. db->flags |= SQLITE_PreferBuiltin;
  78741. sqlite3NestedParse(pParse,
  78742. "UPDATE \"%w\".%s SET "
  78743. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  78744. "WHERE type = 'table' AND name = %Q",
  78745. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  78746. zTab
  78747. );
  78748. sqlite3DbFree(db, zCol);
  78749. db->flags = savedDbFlags;
  78750. }
  78751. /* If the default value of the new column is NULL, then set the file
  78752. ** format to 2. If the default value of the new column is not NULL,
  78753. ** the file format becomes 3.
  78754. */
  78755. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  78756. /* Reload the schema of the modified table. */
  78757. reloadTableSchema(pParse, pTab, pTab->zName);
  78758. }
  78759. /*
  78760. ** This function is called by the parser after the table-name in
  78761. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  78762. ** pSrc is the full-name of the table being altered.
  78763. **
  78764. ** This routine makes a (partial) copy of the Table structure
  78765. ** for the table being altered and sets Parse.pNewTable to point
  78766. ** to it. Routines called by the parser as the column definition
  78767. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  78768. ** the copy. The copy of the Table structure is deleted by tokenize.c
  78769. ** after parsing is finished.
  78770. **
  78771. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  78772. ** coding the "ALTER TABLE ... ADD" statement.
  78773. */
  78774. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  78775. Table *pNew;
  78776. Table *pTab;
  78777. Vdbe *v;
  78778. int iDb;
  78779. int i;
  78780. int nAlloc;
  78781. sqlite3 *db = pParse->db;
  78782. /* Look up the table being altered. */
  78783. assert( pParse->pNewTable==0 );
  78784. assert( sqlite3BtreeHoldsAllMutexes(db) );
  78785. if( db->mallocFailed ) goto exit_begin_add_column;
  78786. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  78787. if( !pTab ) goto exit_begin_add_column;
  78788. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78789. if( IsVirtual(pTab) ){
  78790. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  78791. goto exit_begin_add_column;
  78792. }
  78793. #endif
  78794. /* Make sure this is not an attempt to ALTER a view. */
  78795. if( pTab->pSelect ){
  78796. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  78797. goto exit_begin_add_column;
  78798. }
  78799. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  78800. goto exit_begin_add_column;
  78801. }
  78802. assert( pTab->addColOffset>0 );
  78803. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  78804. /* Put a copy of the Table struct in Parse.pNewTable for the
  78805. ** sqlite3AddColumn() function and friends to modify. But modify
  78806. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  78807. ** prefix, we insure that the name will not collide with an existing
  78808. ** table because user table are not allowed to have the "sqlite_"
  78809. ** prefix on their name.
  78810. */
  78811. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  78812. if( !pNew ) goto exit_begin_add_column;
  78813. pParse->pNewTable = pNew;
  78814. pNew->nRef = 1;
  78815. pNew->nCol = pTab->nCol;
  78816. assert( pNew->nCol>0 );
  78817. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  78818. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  78819. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  78820. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  78821. if( !pNew->aCol || !pNew->zName ){
  78822. db->mallocFailed = 1;
  78823. goto exit_begin_add_column;
  78824. }
  78825. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  78826. for(i=0; i<pNew->nCol; i++){
  78827. Column *pCol = &pNew->aCol[i];
  78828. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  78829. pCol->zColl = 0;
  78830. pCol->zType = 0;
  78831. pCol->pDflt = 0;
  78832. pCol->zDflt = 0;
  78833. }
  78834. pNew->pSchema = db->aDb[iDb].pSchema;
  78835. pNew->addColOffset = pTab->addColOffset;
  78836. pNew->nRef = 1;
  78837. /* Begin a transaction and increment the schema cookie. */
  78838. sqlite3BeginWriteOperation(pParse, 0, iDb);
  78839. v = sqlite3GetVdbe(pParse);
  78840. if( !v ) goto exit_begin_add_column;
  78841. sqlite3ChangeCookie(pParse, iDb);
  78842. exit_begin_add_column:
  78843. sqlite3SrcListDelete(db, pSrc);
  78844. return;
  78845. }
  78846. #endif /* SQLITE_ALTER_TABLE */
  78847. /************** End of alter.c ***********************************************/
  78848. /************** Begin file analyze.c *****************************************/
  78849. /*
  78850. ** 2005-07-08
  78851. **
  78852. ** The author disclaims copyright to this source code. In place of
  78853. ** a legal notice, here is a blessing:
  78854. **
  78855. ** May you do good and not evil.
  78856. ** May you find forgiveness for yourself and forgive others.
  78857. ** May you share freely, never taking more than you give.
  78858. **
  78859. *************************************************************************
  78860. ** This file contains code associated with the ANALYZE command.
  78861. **
  78862. ** The ANALYZE command gather statistics about the content of tables
  78863. ** and indices. These statistics are made available to the query planner
  78864. ** to help it make better decisions about how to perform queries.
  78865. **
  78866. ** The following system tables are or have been supported:
  78867. **
  78868. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  78869. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  78870. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  78871. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  78872. **
  78873. ** Additional tables might be added in future releases of SQLite.
  78874. ** The sqlite_stat2 table is not created or used unless the SQLite version
  78875. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  78876. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  78877. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  78878. ** created and used by SQLite versions 3.7.9 and later and with
  78879. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  78880. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  78881. ** version of sqlite_stat3 and is only available when compiled with
  78882. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  78883. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  78884. ** are both enabled, then STAT4 takes precedence.
  78885. **
  78886. ** For most applications, sqlite_stat1 provides all the statisics required
  78887. ** for the query planner to make good choices.
  78888. **
  78889. ** Format of sqlite_stat1:
  78890. **
  78891. ** There is normally one row per index, with the index identified by the
  78892. ** name in the idx column. The tbl column is the name of the table to
  78893. ** which the index belongs. In each such row, the stat column will be
  78894. ** a string consisting of a list of integers. The first integer in this
  78895. ** list is the number of rows in the index. (This is the same as the
  78896. ** number of rows in the table, except for partial indices.) The second
  78897. ** integer is the average number of rows in the index that have the same
  78898. ** value in the first column of the index. The third integer is the average
  78899. ** number of rows in the index that have the same value for the first two
  78900. ** columns. The N-th integer (for N>1) is the average number of rows in
  78901. ** the index which have the same value for the first N-1 columns. For
  78902. ** a K-column index, there will be K+1 integers in the stat column. If
  78903. ** the index is unique, then the last integer will be 1.
  78904. **
  78905. ** The list of integers in the stat column can optionally be followed
  78906. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  78907. ** must be separated from the last integer by a single space. If the
  78908. ** "unordered" keyword is present, then the query planner assumes that
  78909. ** the index is unordered and will not use the index for a range query.
  78910. **
  78911. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  78912. ** column contains a single integer which is the (estimated) number of
  78913. ** rows in the table identified by sqlite_stat1.tbl.
  78914. **
  78915. ** Format of sqlite_stat2:
  78916. **
  78917. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  78918. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  78919. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  78920. ** about the distribution of keys within an index. The index is identified by
  78921. ** the "idx" column and the "tbl" column is the name of the table to which
  78922. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  78923. ** table for each index.
  78924. **
  78925. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  78926. ** inclusive are samples of the left-most key value in the index taken at
  78927. ** evenly spaced points along the index. Let the number of samples be S
  78928. ** (10 in the standard build) and let C be the number of rows in the index.
  78929. ** Then the sampled rows are given by:
  78930. **
  78931. ** rownumber = (i*C*2 + C)/(S*2)
  78932. **
  78933. ** For i between 0 and S-1. Conceptually, the index space is divided into
  78934. ** S uniform buckets and the samples are the middle row from each bucket.
  78935. **
  78936. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  78937. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  78938. ** writes the sqlite_stat2 table. This version of SQLite only supports
  78939. ** sqlite_stat3.
  78940. **
  78941. ** Format for sqlite_stat3:
  78942. **
  78943. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  78944. ** sqlite_stat4 format will be described first. Further information
  78945. ** about sqlite_stat3 follows the sqlite_stat4 description.
  78946. **
  78947. ** Format for sqlite_stat4:
  78948. **
  78949. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  78950. ** to aid the query planner in choosing good indices based on the values
  78951. ** that indexed columns are compared against in the WHERE clauses of
  78952. ** queries.
  78953. **
  78954. ** The sqlite_stat4 table contains multiple entries for each index.
  78955. ** The idx column names the index and the tbl column is the table of the
  78956. ** index. If the idx and tbl columns are the same, then the sample is
  78957. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  78958. ** binary encoding of a key from the index. The nEq column is a
  78959. ** list of integers. The first integer is the approximate number
  78960. ** of entries in the index whose left-most column exactly matches
  78961. ** the left-most column of the sample. The second integer in nEq
  78962. ** is the approximate number of entries in the index where the
  78963. ** first two columns match the first two columns of the sample.
  78964. ** And so forth. nLt is another list of integers that show the approximate
  78965. ** number of entries that are strictly less than the sample. The first
  78966. ** integer in nLt contains the number of entries in the index where the
  78967. ** left-most column is less than the left-most column of the sample.
  78968. ** The K-th integer in the nLt entry is the number of index entries
  78969. ** where the first K columns are less than the first K columns of the
  78970. ** sample. The nDLt column is like nLt except that it contains the
  78971. ** number of distinct entries in the index that are less than the
  78972. ** sample.
  78973. **
  78974. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  78975. ** The ANALYZE command will typically generate sqlite_stat4 tables
  78976. ** that contain between 10 and 40 samples which are distributed across
  78977. ** the key space, though not uniformly, and which include samples with
  78978. ** large nEq values.
  78979. **
  78980. ** Format for sqlite_stat3 redux:
  78981. **
  78982. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  78983. ** looks at the left-most column of the index. The sqlite_stat3.sample
  78984. ** column contains the actual value of the left-most column instead
  78985. ** of a blob encoding of the complete index key as is found in
  78986. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  78987. ** all contain just a single integer which is the same as the first
  78988. ** integer in the equivalent columns in sqlite_stat4.
  78989. */
  78990. #ifndef SQLITE_OMIT_ANALYZE
  78991. #if defined(SQLITE_ENABLE_STAT4)
  78992. # define IsStat4 1
  78993. # define IsStat3 0
  78994. #elif defined(SQLITE_ENABLE_STAT3)
  78995. # define IsStat4 0
  78996. # define IsStat3 1
  78997. #else
  78998. # define IsStat4 0
  78999. # define IsStat3 0
  79000. # undef SQLITE_STAT4_SAMPLES
  79001. # define SQLITE_STAT4_SAMPLES 1
  79002. #endif
  79003. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  79004. /*
  79005. ** This routine generates code that opens the sqlite_statN tables.
  79006. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  79007. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  79008. ** appropriate compile-time options are provided.
  79009. **
  79010. ** If the sqlite_statN tables do not previously exist, it is created.
  79011. **
  79012. ** Argument zWhere may be a pointer to a buffer containing a table name,
  79013. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  79014. ** the sqlite_statN tables associated with the named table are deleted.
  79015. ** If zWhere==0, then code is generated to delete all stat table entries.
  79016. */
  79017. static void openStatTable(
  79018. Parse *pParse, /* Parsing context */
  79019. int iDb, /* The database we are looking in */
  79020. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  79021. const char *zWhere, /* Delete entries for this table or index */
  79022. const char *zWhereType /* Either "tbl" or "idx" */
  79023. ){
  79024. static const struct {
  79025. const char *zName;
  79026. const char *zCols;
  79027. } aTable[] = {
  79028. { "sqlite_stat1", "tbl,idx,stat" },
  79029. #if defined(SQLITE_ENABLE_STAT4)
  79030. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  79031. { "sqlite_stat3", 0 },
  79032. #elif defined(SQLITE_ENABLE_STAT3)
  79033. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  79034. { "sqlite_stat4", 0 },
  79035. #else
  79036. { "sqlite_stat3", 0 },
  79037. { "sqlite_stat4", 0 },
  79038. #endif
  79039. };
  79040. int i;
  79041. sqlite3 *db = pParse->db;
  79042. Db *pDb;
  79043. Vdbe *v = sqlite3GetVdbe(pParse);
  79044. int aRoot[ArraySize(aTable)];
  79045. u8 aCreateTbl[ArraySize(aTable)];
  79046. if( v==0 ) return;
  79047. assert( sqlite3BtreeHoldsAllMutexes(db) );
  79048. assert( sqlite3VdbeDb(v)==db );
  79049. pDb = &db->aDb[iDb];
  79050. /* Create new statistic tables if they do not exist, or clear them
  79051. ** if they do already exist.
  79052. */
  79053. for(i=0; i<ArraySize(aTable); i++){
  79054. const char *zTab = aTable[i].zName;
  79055. Table *pStat;
  79056. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  79057. if( aTable[i].zCols ){
  79058. /* The sqlite_statN table does not exist. Create it. Note that a
  79059. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  79060. ** of the new table in register pParse->regRoot. This is important
  79061. ** because the OpenWrite opcode below will be needing it. */
  79062. sqlite3NestedParse(pParse,
  79063. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  79064. );
  79065. aRoot[i] = pParse->regRoot;
  79066. aCreateTbl[i] = OPFLAG_P2ISREG;
  79067. }
  79068. }else{
  79069. /* The table already exists. If zWhere is not NULL, delete all entries
  79070. ** associated with the table zWhere. If zWhere is NULL, delete the
  79071. ** entire contents of the table. */
  79072. aRoot[i] = pStat->tnum;
  79073. aCreateTbl[i] = 0;
  79074. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  79075. if( zWhere ){
  79076. sqlite3NestedParse(pParse,
  79077. "DELETE FROM %Q.%s WHERE %s=%Q",
  79078. pDb->zName, zTab, zWhereType, zWhere
  79079. );
  79080. }else{
  79081. /* The sqlite_stat[134] table already exists. Delete all rows. */
  79082. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  79083. }
  79084. }
  79085. }
  79086. /* Open the sqlite_stat[134] tables for writing. */
  79087. for(i=0; aTable[i].zCols; i++){
  79088. assert( i<ArraySize(aTable) );
  79089. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  79090. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  79091. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  79092. }
  79093. }
  79094. /*
  79095. ** Recommended number of samples for sqlite_stat4
  79096. */
  79097. #ifndef SQLITE_STAT4_SAMPLES
  79098. # define SQLITE_STAT4_SAMPLES 24
  79099. #endif
  79100. /*
  79101. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  79102. ** share an instance of the following structure to hold their state
  79103. ** information.
  79104. */
  79105. typedef struct Stat4Accum Stat4Accum;
  79106. typedef struct Stat4Sample Stat4Sample;
  79107. struct Stat4Sample {
  79108. tRowcnt *anEq; /* sqlite_stat4.nEq */
  79109. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  79110. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79111. tRowcnt *anLt; /* sqlite_stat4.nLt */
  79112. i64 iRowid; /* Rowid in main table of the key */
  79113. u8 isPSample; /* True if a periodic sample */
  79114. int iCol; /* If !isPSample, the reason for inclusion */
  79115. u32 iHash; /* Tiebreaker hash */
  79116. #endif
  79117. };
  79118. struct Stat4Accum {
  79119. tRowcnt nRow; /* Number of rows in the entire table */
  79120. tRowcnt nPSample; /* How often to do a periodic sample */
  79121. int nCol; /* Number of columns in index + rowid */
  79122. int mxSample; /* Maximum number of samples to accumulate */
  79123. Stat4Sample current; /* Current row as a Stat4Sample */
  79124. u32 iPrn; /* Pseudo-random number used for sampling */
  79125. Stat4Sample *aBest; /* Array of (nCol-1) best samples */
  79126. int iMin; /* Index in a[] of entry with minimum score */
  79127. int nSample; /* Current number of samples */
  79128. int iGet; /* Index of current sample accessed by stat_get() */
  79129. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  79130. };
  79131. /*
  79132. ** Implementation of the stat_init(N,C) SQL function. The two parameters
  79133. ** are the number of rows in the table or index (C) and the number of columns
  79134. ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
  79135. **
  79136. ** This routine allocates the Stat4Accum object in heap memory. The return
  79137. ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
  79138. ** the size of the blob is sizeof(void*) bytes).
  79139. */
  79140. static void statInit(
  79141. sqlite3_context *context,
  79142. int argc,
  79143. sqlite3_value **argv
  79144. ){
  79145. Stat4Accum *p;
  79146. int nCol; /* Number of columns in index being sampled */
  79147. int nColUp; /* nCol rounded up for alignment */
  79148. int n; /* Bytes of space to allocate */
  79149. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79150. int mxSample = SQLITE_STAT4_SAMPLES;
  79151. #endif
  79152. /* Decode the three function arguments */
  79153. UNUSED_PARAMETER(argc);
  79154. nCol = sqlite3_value_int(argv[0]);
  79155. assert( nCol>1 ); /* >1 because it includes the rowid column */
  79156. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  79157. /* Allocate the space required for the Stat4Accum object */
  79158. n = sizeof(*p)
  79159. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  79160. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  79161. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79162. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  79163. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  79164. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  79165. #endif
  79166. ;
  79167. p = sqlite3MallocZero(n);
  79168. if( p==0 ){
  79169. sqlite3_result_error_nomem(context);
  79170. return;
  79171. }
  79172. p->nRow = 0;
  79173. p->nCol = nCol;
  79174. p->current.anDLt = (tRowcnt*)&p[1];
  79175. p->current.anEq = &p->current.anDLt[nColUp];
  79176. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79177. {
  79178. u8 *pSpace; /* Allocated space not yet assigned */
  79179. int i; /* Used to iterate through p->aSample[] */
  79180. p->iGet = -1;
  79181. p->mxSample = mxSample;
  79182. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
  79183. p->current.anLt = &p->current.anEq[nColUp];
  79184. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
  79185. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  79186. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  79187. p->aBest = &p->a[mxSample];
  79188. pSpace = (u8*)(&p->a[mxSample+nCol]);
  79189. for(i=0; i<(mxSample+nCol); i++){
  79190. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79191. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79192. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79193. }
  79194. assert( (pSpace - (u8*)p)==n );
  79195. for(i=0; i<nCol; i++){
  79196. p->aBest[i].iCol = i;
  79197. }
  79198. }
  79199. #endif
  79200. /* Return a pointer to the allocated object to the caller */
  79201. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  79202. }
  79203. static const FuncDef statInitFuncdef = {
  79204. 1+IsStat34, /* nArg */
  79205. SQLITE_UTF8, /* funcFlags */
  79206. 0, /* pUserData */
  79207. 0, /* pNext */
  79208. statInit, /* xFunc */
  79209. 0, /* xStep */
  79210. 0, /* xFinalize */
  79211. "stat_init", /* zName */
  79212. 0, /* pHash */
  79213. 0 /* pDestructor */
  79214. };
  79215. #ifdef SQLITE_ENABLE_STAT4
  79216. /*
  79217. ** pNew and pOld are both candidate non-periodic samples selected for
  79218. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  79219. ** considering only any trailing columns and the sample hash value, this
  79220. ** function returns true if sample pNew is to be preferred over pOld.
  79221. ** In other words, if we assume that the cardinalities of the selected
  79222. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  79223. **
  79224. ** This function assumes that for each argument sample, the contents of
  79225. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  79226. */
  79227. static int sampleIsBetterPost(
  79228. Stat4Accum *pAccum,
  79229. Stat4Sample *pNew,
  79230. Stat4Sample *pOld
  79231. ){
  79232. int nCol = pAccum->nCol;
  79233. int i;
  79234. assert( pNew->iCol==pOld->iCol );
  79235. for(i=pNew->iCol+1; i<nCol; i++){
  79236. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  79237. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  79238. }
  79239. if( pNew->iHash>pOld->iHash ) return 1;
  79240. return 0;
  79241. }
  79242. #endif
  79243. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79244. /*
  79245. ** Return true if pNew is to be preferred over pOld.
  79246. **
  79247. ** This function assumes that for each argument sample, the contents of
  79248. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  79249. */
  79250. static int sampleIsBetter(
  79251. Stat4Accum *pAccum,
  79252. Stat4Sample *pNew,
  79253. Stat4Sample *pOld
  79254. ){
  79255. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  79256. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  79257. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  79258. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  79259. if( (nEqNew>nEqOld) ) return 1;
  79260. #ifdef SQLITE_ENABLE_STAT4
  79261. if( nEqNew==nEqOld ){
  79262. if( pNew->iCol<pOld->iCol ) return 1;
  79263. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  79264. }
  79265. return 0;
  79266. #else
  79267. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  79268. #endif
  79269. }
  79270. /*
  79271. ** Copy the contents of object (*pFrom) into (*pTo).
  79272. */
  79273. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  79274. pTo->iRowid = pFrom->iRowid;
  79275. pTo->isPSample = pFrom->isPSample;
  79276. pTo->iCol = pFrom->iCol;
  79277. pTo->iHash = pFrom->iHash;
  79278. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  79279. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  79280. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  79281. }
  79282. /*
  79283. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  79284. ** remove the least desirable sample from p->a[] to make room.
  79285. */
  79286. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  79287. Stat4Sample *pSample;
  79288. int i;
  79289. assert( IsStat4 || nEqZero==0 );
  79290. #ifdef SQLITE_ENABLE_STAT4
  79291. if( pNew->isPSample==0 ){
  79292. Stat4Sample *pUpgrade = 0;
  79293. assert( pNew->anEq[pNew->iCol]>0 );
  79294. /* This sample is being added because the prefix that ends in column
  79295. ** iCol occurs many times in the table. However, if we have already
  79296. ** added a sample that shares this prefix, there is no need to add
  79297. ** this one. Instead, upgrade the priority of the highest priority
  79298. ** existing sample that shares this prefix. */
  79299. for(i=p->nSample-1; i>=0; i--){
  79300. Stat4Sample *pOld = &p->a[i];
  79301. if( pOld->anEq[pNew->iCol]==0 ){
  79302. if( pOld->isPSample ) return;
  79303. assert( pOld->iCol>pNew->iCol );
  79304. assert( sampleIsBetter(p, pNew, pOld) );
  79305. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  79306. pUpgrade = pOld;
  79307. }
  79308. }
  79309. }
  79310. if( pUpgrade ){
  79311. pUpgrade->iCol = pNew->iCol;
  79312. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  79313. goto find_new_min;
  79314. }
  79315. }
  79316. #endif
  79317. /* If necessary, remove sample iMin to make room for the new sample. */
  79318. if( p->nSample>=p->mxSample ){
  79319. Stat4Sample *pMin = &p->a[p->iMin];
  79320. tRowcnt *anEq = pMin->anEq;
  79321. tRowcnt *anLt = pMin->anLt;
  79322. tRowcnt *anDLt = pMin->anDLt;
  79323. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  79324. pSample = &p->a[p->nSample-1];
  79325. pSample->anEq = anEq;
  79326. pSample->anDLt = anDLt;
  79327. pSample->anLt = anLt;
  79328. p->nSample = p->mxSample-1;
  79329. }
  79330. /* The "rows less-than" for the rowid column must be greater than that
  79331. ** for the last sample in the p->a[] array. Otherwise, the samples would
  79332. ** be out of order. */
  79333. #ifdef SQLITE_ENABLE_STAT4
  79334. assert( p->nSample==0
  79335. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  79336. #endif
  79337. /* Insert the new sample */
  79338. pSample = &p->a[p->nSample];
  79339. sampleCopy(p, pSample, pNew);
  79340. p->nSample++;
  79341. /* Zero the first nEqZero entries in the anEq[] array. */
  79342. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  79343. #ifdef SQLITE_ENABLE_STAT4
  79344. find_new_min:
  79345. #endif
  79346. if( p->nSample>=p->mxSample ){
  79347. int iMin = -1;
  79348. for(i=0; i<p->mxSample; i++){
  79349. if( p->a[i].isPSample ) continue;
  79350. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  79351. iMin = i;
  79352. }
  79353. }
  79354. assert( iMin>=0 );
  79355. p->iMin = iMin;
  79356. }
  79357. }
  79358. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79359. /*
  79360. ** Field iChng of the index being scanned has changed. So at this point
  79361. ** p->current contains a sample that reflects the previous row of the
  79362. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  79363. ** correct at this point.
  79364. */
  79365. static void samplePushPrevious(Stat4Accum *p, int iChng){
  79366. #ifdef SQLITE_ENABLE_STAT4
  79367. int i;
  79368. /* Check if any samples from the aBest[] array should be pushed
  79369. ** into IndexSample.a[] at this point. */
  79370. for(i=(p->nCol-2); i>=iChng; i--){
  79371. Stat4Sample *pBest = &p->aBest[i];
  79372. pBest->anEq[i] = p->current.anEq[i];
  79373. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  79374. sampleInsert(p, pBest, i);
  79375. }
  79376. }
  79377. /* Update the anEq[] fields of any samples already collected. */
  79378. for(i=p->nSample-1; i>=0; i--){
  79379. int j;
  79380. for(j=iChng; j<p->nCol; j++){
  79381. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  79382. }
  79383. }
  79384. #endif
  79385. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  79386. if( iChng==0 ){
  79387. tRowcnt nLt = p->current.anLt[0];
  79388. tRowcnt nEq = p->current.anEq[0];
  79389. /* Check if this is to be a periodic sample. If so, add it. */
  79390. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  79391. p->current.isPSample = 1;
  79392. sampleInsert(p, &p->current, 0);
  79393. p->current.isPSample = 0;
  79394. }else
  79395. /* Or if it is a non-periodic sample. Add it in this case too. */
  79396. if( p->nSample<p->mxSample
  79397. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  79398. ){
  79399. sampleInsert(p, &p->current, 0);
  79400. }
  79401. }
  79402. #endif
  79403. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  79404. UNUSED_PARAMETER( p );
  79405. UNUSED_PARAMETER( iChng );
  79406. #endif
  79407. }
  79408. /*
  79409. ** Implementation of the stat_push SQL function: stat_push(P,R,C)
  79410. ** Arguments:
  79411. **
  79412. ** P Pointer to the Stat4Accum object created by stat_init()
  79413. ** C Index of left-most column to differ from previous row
  79414. ** R Rowid for the current row
  79415. **
  79416. ** The SQL function always returns NULL.
  79417. **
  79418. ** The R parameter is only used for STAT3 and STAT4.
  79419. */
  79420. static void statPush(
  79421. sqlite3_context *context,
  79422. int argc,
  79423. sqlite3_value **argv
  79424. ){
  79425. int i;
  79426. /* The three function arguments */
  79427. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  79428. int iChng = sqlite3_value_int(argv[1]);
  79429. UNUSED_PARAMETER( argc );
  79430. UNUSED_PARAMETER( context );
  79431. assert( p->nCol>1 ); /* Includes rowid field */
  79432. assert( iChng<p->nCol );
  79433. if( p->nRow==0 ){
  79434. /* This is the first call to this function. Do initialization. */
  79435. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  79436. }else{
  79437. /* Second and subsequent calls get processed here */
  79438. samplePushPrevious(p, iChng);
  79439. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  79440. ** to the current row of the index. */
  79441. for(i=0; i<iChng; i++){
  79442. p->current.anEq[i]++;
  79443. }
  79444. for(i=iChng; i<p->nCol; i++){
  79445. p->current.anDLt[i]++;
  79446. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79447. p->current.anLt[i] += p->current.anEq[i];
  79448. #endif
  79449. p->current.anEq[i] = 1;
  79450. }
  79451. }
  79452. p->nRow++;
  79453. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79454. p->current.iRowid = sqlite3_value_int64(argv[2]);
  79455. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  79456. #endif
  79457. #ifdef SQLITE_ENABLE_STAT4
  79458. {
  79459. tRowcnt nLt = p->current.anLt[p->nCol-1];
  79460. /* Check if this is to be a periodic sample. If so, add it. */
  79461. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  79462. p->current.isPSample = 1;
  79463. p->current.iCol = 0;
  79464. sampleInsert(p, &p->current, p->nCol-1);
  79465. p->current.isPSample = 0;
  79466. }
  79467. /* Update the aBest[] array. */
  79468. for(i=0; i<(p->nCol-1); i++){
  79469. p->current.iCol = i;
  79470. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  79471. sampleCopy(p, &p->aBest[i], &p->current);
  79472. }
  79473. }
  79474. }
  79475. #endif
  79476. }
  79477. static const FuncDef statPushFuncdef = {
  79478. 2+IsStat34, /* nArg */
  79479. SQLITE_UTF8, /* funcFlags */
  79480. 0, /* pUserData */
  79481. 0, /* pNext */
  79482. statPush, /* xFunc */
  79483. 0, /* xStep */
  79484. 0, /* xFinalize */
  79485. "stat_push", /* zName */
  79486. 0, /* pHash */
  79487. 0 /* pDestructor */
  79488. };
  79489. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  79490. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  79491. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  79492. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  79493. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  79494. /*
  79495. ** Implementation of the stat_get(P,J) SQL function. This routine is
  79496. ** used to query the results. Content is returned for parameter J
  79497. ** which is one of the STAT_GET_xxxx values defined above.
  79498. **
  79499. ** If neither STAT3 nor STAT4 are enabled, then J is always
  79500. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  79501. ** a one-parameter function, stat_get(P), that always returns the
  79502. ** stat1 table entry information.
  79503. */
  79504. static void statGet(
  79505. sqlite3_context *context,
  79506. int argc,
  79507. sqlite3_value **argv
  79508. ){
  79509. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  79510. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79511. /* STAT3 and STAT4 have a parameter on this routine. */
  79512. int eCall = sqlite3_value_int(argv[1]);
  79513. assert( argc==2 );
  79514. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  79515. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  79516. || eCall==STAT_GET_NDLT
  79517. );
  79518. if( eCall==STAT_GET_STAT1 )
  79519. #else
  79520. assert( argc==1 );
  79521. #endif
  79522. {
  79523. /* Return the value to store in the "stat" column of the sqlite_stat1
  79524. ** table for this index.
  79525. **
  79526. ** The value is a string composed of a list of integers describing
  79527. ** the index. The first integer in the list is the total number of
  79528. ** entries in the index. There is one additional integer in the list
  79529. ** for each indexed column. This additional integer is an estimate of
  79530. ** the number of rows matched by a stabbing query on the index using
  79531. ** a key with the corresponding number of fields. In other words,
  79532. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  79533. ** "100 10 2", then SQLite estimates that:
  79534. **
  79535. ** * the index contains 100 rows,
  79536. ** * "WHERE a=?" matches 10 rows, and
  79537. ** * "WHERE a=? AND b=?" matches 2 rows.
  79538. **
  79539. ** If D is the count of distinct values and K is the total number of
  79540. ** rows, then each estimate is computed as:
  79541. **
  79542. ** I = (K+D-1)/D
  79543. */
  79544. char *z;
  79545. int i;
  79546. char *zRet = sqlite3MallocZero(p->nCol * 25);
  79547. if( zRet==0 ){
  79548. sqlite3_result_error_nomem(context);
  79549. return;
  79550. }
  79551. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  79552. z = zRet + sqlite3Strlen30(zRet);
  79553. for(i=0; i<(p->nCol-1); i++){
  79554. u64 nDistinct = p->current.anDLt[i] + 1;
  79555. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  79556. sqlite3_snprintf(24, z, " %llu", iVal);
  79557. z += sqlite3Strlen30(z);
  79558. assert( p->current.anEq[i] );
  79559. }
  79560. assert( z[0]=='\0' && z>zRet );
  79561. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  79562. }
  79563. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79564. else if( eCall==STAT_GET_ROWID ){
  79565. if( p->iGet<0 ){
  79566. samplePushPrevious(p, 0);
  79567. p->iGet = 0;
  79568. }
  79569. if( p->iGet<p->nSample ){
  79570. sqlite3_result_int64(context, p->a[p->iGet].iRowid);
  79571. }
  79572. }else{
  79573. tRowcnt *aCnt = 0;
  79574. assert( p->iGet<p->nSample );
  79575. switch( eCall ){
  79576. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  79577. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  79578. default: {
  79579. aCnt = p->a[p->iGet].anDLt;
  79580. p->iGet++;
  79581. break;
  79582. }
  79583. }
  79584. if( IsStat3 ){
  79585. sqlite3_result_int64(context, (i64)aCnt[0]);
  79586. }else{
  79587. char *zRet = sqlite3MallocZero(p->nCol * 25);
  79588. if( zRet==0 ){
  79589. sqlite3_result_error_nomem(context);
  79590. }else{
  79591. int i;
  79592. char *z = zRet;
  79593. for(i=0; i<p->nCol; i++){
  79594. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  79595. z += sqlite3Strlen30(z);
  79596. }
  79597. assert( z[0]=='\0' && z>zRet );
  79598. z[-1] = '\0';
  79599. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  79600. }
  79601. }
  79602. }
  79603. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79604. #ifndef SQLITE_DEBUG
  79605. UNUSED_PARAMETER( argc );
  79606. #endif
  79607. }
  79608. static const FuncDef statGetFuncdef = {
  79609. 1+IsStat34, /* nArg */
  79610. SQLITE_UTF8, /* funcFlags */
  79611. 0, /* pUserData */
  79612. 0, /* pNext */
  79613. statGet, /* xFunc */
  79614. 0, /* xStep */
  79615. 0, /* xFinalize */
  79616. "stat_get", /* zName */
  79617. 0, /* pHash */
  79618. 0 /* pDestructor */
  79619. };
  79620. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  79621. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  79622. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79623. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  79624. #elif SQLITE_DEBUG
  79625. assert( iParam==STAT_GET_STAT1 );
  79626. #else
  79627. UNUSED_PARAMETER( iParam );
  79628. #endif
  79629. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  79630. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  79631. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  79632. }
  79633. /*
  79634. ** Generate code to do an analysis of all indices associated with
  79635. ** a single table.
  79636. */
  79637. static void analyzeOneTable(
  79638. Parse *pParse, /* Parser context */
  79639. Table *pTab, /* Table whose indices are to be analyzed */
  79640. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  79641. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  79642. int iMem, /* Available memory locations begin here */
  79643. int iTab /* Next available cursor */
  79644. ){
  79645. sqlite3 *db = pParse->db; /* Database handle */
  79646. Index *pIdx; /* An index to being analyzed */
  79647. int iIdxCur; /* Cursor open on index being analyzed */
  79648. int iTabCur; /* Table cursor */
  79649. Vdbe *v; /* The virtual machine being built up */
  79650. int i; /* Loop counter */
  79651. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  79652. int iDb; /* Index of database containing pTab */
  79653. u8 needTableCnt = 1; /* True to count the table */
  79654. int regNewRowid = iMem++; /* Rowid for the inserted record */
  79655. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  79656. int regChng = iMem++; /* Index of changed index field */
  79657. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79658. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  79659. #endif
  79660. int regTemp = iMem++; /* Temporary use register */
  79661. int regTabname = iMem++; /* Register containing table name */
  79662. int regIdxname = iMem++; /* Register containing index name */
  79663. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  79664. int regPrev = iMem; /* MUST BE LAST (see below) */
  79665. pParse->nMem = MAX(pParse->nMem, iMem);
  79666. v = sqlite3GetVdbe(pParse);
  79667. if( v==0 || NEVER(pTab==0) ){
  79668. return;
  79669. }
  79670. if( pTab->tnum==0 ){
  79671. /* Do not gather statistics on views or virtual tables */
  79672. return;
  79673. }
  79674. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  79675. /* Do not gather statistics on system tables */
  79676. return;
  79677. }
  79678. assert( sqlite3BtreeHoldsAllMutexes(db) );
  79679. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  79680. assert( iDb>=0 );
  79681. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79682. #ifndef SQLITE_OMIT_AUTHORIZATION
  79683. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  79684. db->aDb[iDb].zName ) ){
  79685. return;
  79686. }
  79687. #endif
  79688. /* Establish a read-lock on the table at the shared-cache level.
  79689. ** Open a read-only cursor on the table. Also allocate a cursor number
  79690. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  79691. ** this time though. */
  79692. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  79693. iTabCur = iTab++;
  79694. iIdxCur = iTab++;
  79695. pParse->nTab = MAX(pParse->nTab, iTab);
  79696. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  79697. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  79698. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  79699. int nCol; /* Number of columns indexed by pIdx */
  79700. KeyInfo *pKey; /* KeyInfo structure for pIdx */
  79701. int *aGotoChng; /* Array of jump instruction addresses */
  79702. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  79703. int addrGotoChng0; /* Address of "Goto addr_chng_0" */
  79704. int addrNextRow; /* Address of "next_row:" */
  79705. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  79706. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  79707. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  79708. nCol = pIdx->nColumn;
  79709. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
  79710. if( aGotoChng==0 ) continue;
  79711. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  79712. /* Populate the register containing the index name. */
  79713. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  79714. /*
  79715. ** Pseudo-code for loop that calls stat_push():
  79716. **
  79717. ** Rewind csr
  79718. ** if eof(csr) goto end_of_scan;
  79719. ** regChng = 0
  79720. ** goto chng_addr_0;
  79721. **
  79722. ** next_row:
  79723. ** regChng = 0
  79724. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  79725. ** regChng = 1
  79726. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  79727. ** ...
  79728. ** regChng = N
  79729. ** goto chng_addr_N
  79730. **
  79731. ** chng_addr_0:
  79732. ** regPrev(0) = idx(0)
  79733. ** chng_addr_1:
  79734. ** regPrev(1) = idx(1)
  79735. ** ...
  79736. **
  79737. ** chng_addr_N:
  79738. ** regRowid = idx(rowid)
  79739. ** stat_push(P, regChng, regRowid)
  79740. ** Next csr
  79741. ** if !eof(csr) goto next_row;
  79742. **
  79743. ** end_of_scan:
  79744. */
  79745. /* Make sure there are enough memory cells allocated to accommodate
  79746. ** the regPrev array and a trailing rowid (the rowid slot is required
  79747. ** when building a record to insert into the sample column of
  79748. ** the sqlite_stat4 table. */
  79749. pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
  79750. /* Open a read-only cursor on the index being analyzed. */
  79751. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  79752. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  79753. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  79754. VdbeComment((v, "%s", pIdx->zName));
  79755. /* Invoke the stat_init() function. The arguments are:
  79756. **
  79757. ** (1) the number of columns in the index including the rowid,
  79758. ** (2) the number of rows in the index,
  79759. **
  79760. ** The second argument is only used for STAT3 and STAT4
  79761. */
  79762. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79763. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
  79764. #endif
  79765. sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
  79766. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  79767. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  79768. sqlite3VdbeChangeP5(v, 1+IsStat34);
  79769. /* Implementation of the following:
  79770. **
  79771. ** Rewind csr
  79772. ** if eof(csr) goto end_of_scan;
  79773. ** regChng = 0
  79774. ** goto next_push_0;
  79775. **
  79776. */
  79777. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  79778. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  79779. addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  79780. /*
  79781. ** next_row:
  79782. ** regChng = 0
  79783. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  79784. ** regChng = 1
  79785. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  79786. ** ...
  79787. ** regChng = N
  79788. ** goto chng_addr_N
  79789. */
  79790. addrNextRow = sqlite3VdbeCurrentAddr(v);
  79791. for(i=0; i<nCol; i++){
  79792. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  79793. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  79794. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  79795. aGotoChng[i] =
  79796. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  79797. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  79798. }
  79799. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  79800. aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  79801. /*
  79802. ** chng_addr_0:
  79803. ** regPrev(0) = idx(0)
  79804. ** chng_addr_1:
  79805. ** regPrev(1) = idx(1)
  79806. ** ...
  79807. */
  79808. sqlite3VdbeJumpHere(v, addrGotoChng0);
  79809. for(i=0; i<nCol; i++){
  79810. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  79811. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  79812. }
  79813. /*
  79814. ** chng_addr_N:
  79815. ** regRowid = idx(rowid) // STAT34 only
  79816. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  79817. ** Next csr
  79818. ** if !eof(csr) goto next_row;
  79819. */
  79820. sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
  79821. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79822. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  79823. assert( regRowid==(regStat4+2) );
  79824. #endif
  79825. assert( regChng==(regStat4+1) );
  79826. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  79827. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  79828. sqlite3VdbeChangeP5(v, 2+IsStat34);
  79829. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
  79830. /* Add the entry to the stat1 table. */
  79831. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  79832. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  79833. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  79834. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  79835. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79836. /* Add the entries to the stat3 or stat4 table. */
  79837. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79838. {
  79839. int regEq = regStat1;
  79840. int regLt = regStat1+1;
  79841. int regDLt = regStat1+2;
  79842. int regSample = regStat1+3;
  79843. int regCol = regStat1+4;
  79844. int regSampleRowid = regCol + nCol;
  79845. int addrNext;
  79846. int addrIsNull;
  79847. pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  79848. addrNext = sqlite3VdbeCurrentAddr(v);
  79849. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  79850. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  79851. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  79852. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  79853. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  79854. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
  79855. #ifdef SQLITE_ENABLE_STAT3
  79856. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  79857. pIdx->aiColumn[0], regSample);
  79858. #else
  79859. for(i=0; i<nCol; i++){
  79860. int iCol = pIdx->aiColumn[i];
  79861. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  79862. }
  79863. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  79864. #endif
  79865. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
  79866. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  79867. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  79868. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  79869. sqlite3VdbeJumpHere(v, addrIsNull);
  79870. }
  79871. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79872. /* End of analysis */
  79873. sqlite3VdbeJumpHere(v, addrRewind);
  79874. sqlite3DbFree(db, aGotoChng);
  79875. }
  79876. /* Create a single sqlite_stat1 entry containing NULL as the index
  79877. ** name and the row count as the content.
  79878. */
  79879. if( pOnlyIdx==0 && needTableCnt ){
  79880. VdbeComment((v, "%s", pTab->zName));
  79881. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  79882. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  79883. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  79884. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  79885. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  79886. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  79887. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79888. sqlite3VdbeJumpHere(v, jZeroRows);
  79889. }
  79890. }
  79891. /*
  79892. ** Generate code that will cause the most recent index analysis to
  79893. ** be loaded into internal hash tables where is can be used.
  79894. */
  79895. static void loadAnalysis(Parse *pParse, int iDb){
  79896. Vdbe *v = sqlite3GetVdbe(pParse);
  79897. if( v ){
  79898. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  79899. }
  79900. }
  79901. /*
  79902. ** Generate code that will do an analysis of an entire database
  79903. */
  79904. static void analyzeDatabase(Parse *pParse, int iDb){
  79905. sqlite3 *db = pParse->db;
  79906. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  79907. HashElem *k;
  79908. int iStatCur;
  79909. int iMem;
  79910. int iTab;
  79911. sqlite3BeginWriteOperation(pParse, 0, iDb);
  79912. iStatCur = pParse->nTab;
  79913. pParse->nTab += 3;
  79914. openStatTable(pParse, iDb, iStatCur, 0, 0);
  79915. iMem = pParse->nMem+1;
  79916. iTab = pParse->nTab;
  79917. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79918. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  79919. Table *pTab = (Table*)sqliteHashData(k);
  79920. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  79921. }
  79922. loadAnalysis(pParse, iDb);
  79923. }
  79924. /*
  79925. ** Generate code that will do an analysis of a single table in
  79926. ** a database. If pOnlyIdx is not NULL then it is a single index
  79927. ** in pTab that should be analyzed.
  79928. */
  79929. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  79930. int iDb;
  79931. int iStatCur;
  79932. assert( pTab!=0 );
  79933. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79934. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  79935. sqlite3BeginWriteOperation(pParse, 0, iDb);
  79936. iStatCur = pParse->nTab;
  79937. pParse->nTab += 3;
  79938. if( pOnlyIdx ){
  79939. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  79940. }else{
  79941. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  79942. }
  79943. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  79944. loadAnalysis(pParse, iDb);
  79945. }
  79946. /*
  79947. ** Generate code for the ANALYZE command. The parser calls this routine
  79948. ** when it recognizes an ANALYZE command.
  79949. **
  79950. ** ANALYZE -- 1
  79951. ** ANALYZE <database> -- 2
  79952. ** ANALYZE ?<database>.?<tablename> -- 3
  79953. **
  79954. ** Form 1 causes all indices in all attached databases to be analyzed.
  79955. ** Form 2 analyzes all indices the single database named.
  79956. ** Form 3 analyzes all indices associated with the named table.
  79957. */
  79958. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  79959. sqlite3 *db = pParse->db;
  79960. int iDb;
  79961. int i;
  79962. char *z, *zDb;
  79963. Table *pTab;
  79964. Index *pIdx;
  79965. Token *pTableName;
  79966. /* Read the database schema. If an error occurs, leave an error message
  79967. ** and code in pParse and return NULL. */
  79968. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79969. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  79970. return;
  79971. }
  79972. assert( pName2!=0 || pName1==0 );
  79973. if( pName1==0 ){
  79974. /* Form 1: Analyze everything */
  79975. for(i=0; i<db->nDb; i++){
  79976. if( i==1 ) continue; /* Do not analyze the TEMP database */
  79977. analyzeDatabase(pParse, i);
  79978. }
  79979. }else if( pName2->n==0 ){
  79980. /* Form 2: Analyze the database or table named */
  79981. iDb = sqlite3FindDb(db, pName1);
  79982. if( iDb>=0 ){
  79983. analyzeDatabase(pParse, iDb);
  79984. }else{
  79985. z = sqlite3NameFromToken(db, pName1);
  79986. if( z ){
  79987. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  79988. analyzeTable(pParse, pIdx->pTable, pIdx);
  79989. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  79990. analyzeTable(pParse, pTab, 0);
  79991. }
  79992. sqlite3DbFree(db, z);
  79993. }
  79994. }
  79995. }else{
  79996. /* Form 3: Analyze the fully qualified table name */
  79997. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  79998. if( iDb>=0 ){
  79999. zDb = db->aDb[iDb].zName;
  80000. z = sqlite3NameFromToken(db, pTableName);
  80001. if( z ){
  80002. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  80003. analyzeTable(pParse, pIdx->pTable, pIdx);
  80004. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  80005. analyzeTable(pParse, pTab, 0);
  80006. }
  80007. sqlite3DbFree(db, z);
  80008. }
  80009. }
  80010. }
  80011. }
  80012. /*
  80013. ** Used to pass information from the analyzer reader through to the
  80014. ** callback routine.
  80015. */
  80016. typedef struct analysisInfo analysisInfo;
  80017. struct analysisInfo {
  80018. sqlite3 *db;
  80019. const char *zDatabase;
  80020. };
  80021. /*
  80022. ** The first argument points to a nul-terminated string containing a
  80023. ** list of space separated integers. Read the first nOut of these into
  80024. ** the array aOut[].
  80025. */
  80026. static void decodeIntArray(
  80027. char *zIntArray, /* String containing int array to decode */
  80028. int nOut, /* Number of slots in aOut[] */
  80029. tRowcnt *aOut, /* Store integers here */
  80030. Index *pIndex /* Handle extra flags for this index, if not NULL */
  80031. ){
  80032. char *z = zIntArray;
  80033. int c;
  80034. int i;
  80035. tRowcnt v;
  80036. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80037. if( z==0 ) z = "";
  80038. #else
  80039. if( NEVER(z==0) ) z = "";
  80040. #endif
  80041. for(i=0; *z && i<nOut; i++){
  80042. v = 0;
  80043. while( (c=z[0])>='0' && c<='9' ){
  80044. v = v*10 + c - '0';
  80045. z++;
  80046. }
  80047. aOut[i] = v;
  80048. if( *z==' ' ) z++;
  80049. }
  80050. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  80051. assert( pIndex!=0 );
  80052. #else
  80053. if( pIndex )
  80054. #endif
  80055. {
  80056. if( strcmp(z, "unordered")==0 ){
  80057. pIndex->bUnordered = 1;
  80058. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  80059. int v32 = 0;
  80060. sqlite3GetInt32(z+3, &v32);
  80061. pIndex->szIdxRow = sqlite3LogEst(v32);
  80062. }
  80063. }
  80064. }
  80065. /*
  80066. ** This callback is invoked once for each index when reading the
  80067. ** sqlite_stat1 table.
  80068. **
  80069. ** argv[0] = name of the table
  80070. ** argv[1] = name of the index (might be NULL)
  80071. ** argv[2] = results of analysis - on integer for each column
  80072. **
  80073. ** Entries for which argv[1]==NULL simply record the number of rows in
  80074. ** the table.
  80075. */
  80076. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  80077. analysisInfo *pInfo = (analysisInfo*)pData;
  80078. Index *pIndex;
  80079. Table *pTable;
  80080. const char *z;
  80081. assert( argc==3 );
  80082. UNUSED_PARAMETER2(NotUsed, argc);
  80083. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  80084. return 0;
  80085. }
  80086. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  80087. if( pTable==0 ){
  80088. return 0;
  80089. }
  80090. if( argv[1] ){
  80091. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  80092. }else{
  80093. pIndex = 0;
  80094. }
  80095. z = argv[2];
  80096. if( pIndex ){
  80097. decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
  80098. if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
  80099. }else{
  80100. Index fakeIdx;
  80101. fakeIdx.szIdxRow = pTable->szTabRow;
  80102. decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
  80103. pTable->szTabRow = fakeIdx.szIdxRow;
  80104. }
  80105. return 0;
  80106. }
  80107. /*
  80108. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  80109. ** and its contents.
  80110. */
  80111. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  80112. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80113. if( pIdx->aSample ){
  80114. int j;
  80115. for(j=0; j<pIdx->nSample; j++){
  80116. IndexSample *p = &pIdx->aSample[j];
  80117. sqlite3DbFree(db, p->p);
  80118. }
  80119. sqlite3DbFree(db, pIdx->aSample);
  80120. }
  80121. if( db && db->pnBytesFreed==0 ){
  80122. pIdx->nSample = 0;
  80123. pIdx->aSample = 0;
  80124. }
  80125. #else
  80126. UNUSED_PARAMETER(db);
  80127. UNUSED_PARAMETER(pIdx);
  80128. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  80129. }
  80130. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80131. /*
  80132. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  80133. ** stored in pIdx->aSample[].
  80134. */
  80135. static void initAvgEq(Index *pIdx){
  80136. if( pIdx ){
  80137. IndexSample *aSample = pIdx->aSample;
  80138. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  80139. int iCol;
  80140. for(iCol=0; iCol<pIdx->nColumn; iCol++){
  80141. int i; /* Used to iterate through samples */
  80142. tRowcnt sumEq = 0; /* Sum of the nEq values */
  80143. tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
  80144. tRowcnt avgEq = 0;
  80145. tRowcnt nDLt = pFinal->anDLt[iCol];
  80146. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  80147. ** occur in the stat4 table for this index before pFinal. Set
  80148. ** sumEq to the sum of the nEq values for column iCol for the same
  80149. ** set (adding the value only once where there exist dupicate
  80150. ** prefixes). */
  80151. for(i=0; i<(pIdx->nSample-1); i++){
  80152. if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
  80153. sumEq += aSample[i].anEq[iCol];
  80154. nSum++;
  80155. }
  80156. }
  80157. if( nDLt>nSum ){
  80158. avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
  80159. }
  80160. if( avgEq==0 ) avgEq = 1;
  80161. pIdx->aAvgEq[iCol] = avgEq;
  80162. if( pIdx->nSampleCol==1 ) break;
  80163. }
  80164. }
  80165. }
  80166. /*
  80167. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  80168. ** into the relevant Index.aSample[] arrays.
  80169. **
  80170. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  80171. ** data equivalent to the following (statements are different for stat3,
  80172. ** see the caller of this function for details):
  80173. **
  80174. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  80175. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  80176. **
  80177. ** where %Q is replaced with the database name before the SQL is executed.
  80178. */
  80179. static int loadStatTbl(
  80180. sqlite3 *db, /* Database handle */
  80181. int bStat3, /* Assume single column records only */
  80182. const char *zSql1, /* SQL statement 1 (see above) */
  80183. const char *zSql2, /* SQL statement 2 (see above) */
  80184. const char *zDb /* Database name (e.g. "main") */
  80185. ){
  80186. int rc; /* Result codes from subroutines */
  80187. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  80188. char *zSql; /* Text of the SQL statement */
  80189. Index *pPrevIdx = 0; /* Previous index in the loop */
  80190. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  80191. assert( db->lookaside.bEnabled==0 );
  80192. zSql = sqlite3MPrintf(db, zSql1, zDb);
  80193. if( !zSql ){
  80194. return SQLITE_NOMEM;
  80195. }
  80196. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  80197. sqlite3DbFree(db, zSql);
  80198. if( rc ) return rc;
  80199. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  80200. int nIdxCol = 1; /* Number of columns in stat4 records */
  80201. int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
  80202. char *zIndex; /* Index name */
  80203. Index *pIdx; /* Pointer to the index object */
  80204. int nSample; /* Number of samples */
  80205. int nByte; /* Bytes of space required */
  80206. int i; /* Bytes of space required */
  80207. tRowcnt *pSpace;
  80208. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  80209. if( zIndex==0 ) continue;
  80210. nSample = sqlite3_column_int(pStmt, 1);
  80211. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  80212. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  80213. /* Index.nSample is non-zero at this point if data has already been
  80214. ** loaded from the stat4 table. In this case ignore stat3 data. */
  80215. if( pIdx==0 || pIdx->nSample ) continue;
  80216. if( bStat3==0 ){
  80217. nIdxCol = pIdx->nColumn+1;
  80218. nAvgCol = pIdx->nColumn;
  80219. }
  80220. pIdx->nSampleCol = nIdxCol;
  80221. nByte = sizeof(IndexSample) * nSample;
  80222. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  80223. nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  80224. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  80225. if( pIdx->aSample==0 ){
  80226. sqlite3_finalize(pStmt);
  80227. return SQLITE_NOMEM;
  80228. }
  80229. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  80230. pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
  80231. for(i=0; i<nSample; i++){
  80232. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  80233. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  80234. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  80235. }
  80236. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  80237. }
  80238. rc = sqlite3_finalize(pStmt);
  80239. if( rc ) return rc;
  80240. zSql = sqlite3MPrintf(db, zSql2, zDb);
  80241. if( !zSql ){
  80242. return SQLITE_NOMEM;
  80243. }
  80244. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  80245. sqlite3DbFree(db, zSql);
  80246. if( rc ) return rc;
  80247. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  80248. char *zIndex; /* Index name */
  80249. Index *pIdx; /* Pointer to the index object */
  80250. int nCol = 1; /* Number of columns in index */
  80251. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  80252. if( zIndex==0 ) continue;
  80253. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  80254. if( pIdx==0 ) continue;
  80255. /* This next condition is true if data has already been loaded from
  80256. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  80257. nCol = pIdx->nSampleCol;
  80258. if( bStat3 && nCol>1 ) continue;
  80259. if( pIdx!=pPrevIdx ){
  80260. initAvgEq(pPrevIdx);
  80261. pPrevIdx = pIdx;
  80262. }
  80263. pSample = &pIdx->aSample[pIdx->nSample];
  80264. decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
  80265. decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
  80266. decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
  80267. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  80268. ** This is in case the sample record is corrupted. In that case, the
  80269. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  80270. ** end of the allocated buffer before it realizes it is dealing with
  80271. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  80272. ** a buffer overread. */
  80273. pSample->n = sqlite3_column_bytes(pStmt, 4);
  80274. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  80275. if( pSample->p==0 ){
  80276. sqlite3_finalize(pStmt);
  80277. return SQLITE_NOMEM;
  80278. }
  80279. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  80280. pIdx->nSample++;
  80281. }
  80282. rc = sqlite3_finalize(pStmt);
  80283. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  80284. return rc;
  80285. }
  80286. /*
  80287. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  80288. ** the Index.aSample[] arrays of all indices.
  80289. */
  80290. static int loadStat4(sqlite3 *db, const char *zDb){
  80291. int rc = SQLITE_OK; /* Result codes from subroutines */
  80292. assert( db->lookaside.bEnabled==0 );
  80293. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  80294. rc = loadStatTbl(db, 0,
  80295. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  80296. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  80297. zDb
  80298. );
  80299. }
  80300. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  80301. rc = loadStatTbl(db, 1,
  80302. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  80303. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  80304. zDb
  80305. );
  80306. }
  80307. return rc;
  80308. }
  80309. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  80310. /*
  80311. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  80312. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  80313. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  80314. ** Index.aSample[] arrays.
  80315. **
  80316. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  80317. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  80318. ** during compilation and the sqlite_stat3/4 table is present, no data is
  80319. ** read from it.
  80320. **
  80321. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  80322. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  80323. ** returned. However, in this case, data is read from the sqlite_stat1
  80324. ** table (if it is present) before returning.
  80325. **
  80326. ** If an OOM error occurs, this function always sets db->mallocFailed.
  80327. ** This means if the caller does not care about other errors, the return
  80328. ** code may be ignored.
  80329. */
  80330. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  80331. analysisInfo sInfo;
  80332. HashElem *i;
  80333. char *zSql;
  80334. int rc;
  80335. assert( iDb>=0 && iDb<db->nDb );
  80336. assert( db->aDb[iDb].pBt!=0 );
  80337. /* Clear any prior statistics */
  80338. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80339. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  80340. Index *pIdx = sqliteHashData(i);
  80341. sqlite3DefaultRowEst(pIdx);
  80342. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80343. sqlite3DeleteIndexSamples(db, pIdx);
  80344. pIdx->aSample = 0;
  80345. #endif
  80346. }
  80347. /* Check to make sure the sqlite_stat1 table exists */
  80348. sInfo.db = db;
  80349. sInfo.zDatabase = db->aDb[iDb].zName;
  80350. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  80351. return SQLITE_ERROR;
  80352. }
  80353. /* Load new statistics out of the sqlite_stat1 table */
  80354. zSql = sqlite3MPrintf(db,
  80355. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  80356. if( zSql==0 ){
  80357. rc = SQLITE_NOMEM;
  80358. }else{
  80359. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  80360. sqlite3DbFree(db, zSql);
  80361. }
  80362. /* Load the statistics from the sqlite_stat4 table. */
  80363. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80364. if( rc==SQLITE_OK ){
  80365. int lookasideEnabled = db->lookaside.bEnabled;
  80366. db->lookaside.bEnabled = 0;
  80367. rc = loadStat4(db, sInfo.zDatabase);
  80368. db->lookaside.bEnabled = lookasideEnabled;
  80369. }
  80370. #endif
  80371. if( rc==SQLITE_NOMEM ){
  80372. db->mallocFailed = 1;
  80373. }
  80374. return rc;
  80375. }
  80376. #endif /* SQLITE_OMIT_ANALYZE */
  80377. /************** End of analyze.c *********************************************/
  80378. /************** Begin file attach.c ******************************************/
  80379. /*
  80380. ** 2003 April 6
  80381. **
  80382. ** The author disclaims copyright to this source code. In place of
  80383. ** a legal notice, here is a blessing:
  80384. **
  80385. ** May you do good and not evil.
  80386. ** May you find forgiveness for yourself and forgive others.
  80387. ** May you share freely, never taking more than you give.
  80388. **
  80389. *************************************************************************
  80390. ** This file contains code used to implement the ATTACH and DETACH commands.
  80391. */
  80392. #ifndef SQLITE_OMIT_ATTACH
  80393. /*
  80394. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  80395. ** is slightly different from resolving a normal SQL expression, because simple
  80396. ** identifiers are treated as strings, not possible column names or aliases.
  80397. **
  80398. ** i.e. if the parser sees:
  80399. **
  80400. ** ATTACH DATABASE abc AS def
  80401. **
  80402. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  80403. ** looking for columns of the same name.
  80404. **
  80405. ** This only applies to the root node of pExpr, so the statement:
  80406. **
  80407. ** ATTACH DATABASE abc||def AS 'db2'
  80408. **
  80409. ** will fail because neither abc or def can be resolved.
  80410. */
  80411. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  80412. {
  80413. int rc = SQLITE_OK;
  80414. if( pExpr ){
  80415. if( pExpr->op!=TK_ID ){
  80416. rc = sqlite3ResolveExprNames(pName, pExpr);
  80417. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  80418. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  80419. return SQLITE_ERROR;
  80420. }
  80421. }else{
  80422. pExpr->op = TK_STRING;
  80423. }
  80424. }
  80425. return rc;
  80426. }
  80427. /*
  80428. ** An SQL user-function registered to do the work of an ATTACH statement. The
  80429. ** three arguments to the function come directly from an attach statement:
  80430. **
  80431. ** ATTACH DATABASE x AS y KEY z
  80432. **
  80433. ** SELECT sqlite_attach(x, y, z)
  80434. **
  80435. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  80436. ** third argument.
  80437. */
  80438. static void attachFunc(
  80439. sqlite3_context *context,
  80440. int NotUsed,
  80441. sqlite3_value **argv
  80442. ){
  80443. int i;
  80444. int rc = 0;
  80445. sqlite3 *db = sqlite3_context_db_handle(context);
  80446. const char *zName;
  80447. const char *zFile;
  80448. char *zPath = 0;
  80449. char *zErr = 0;
  80450. unsigned int flags;
  80451. Db *aNew;
  80452. char *zErrDyn = 0;
  80453. sqlite3_vfs *pVfs;
  80454. UNUSED_PARAMETER(NotUsed);
  80455. zFile = (const char *)sqlite3_value_text(argv[0]);
  80456. zName = (const char *)sqlite3_value_text(argv[1]);
  80457. if( zFile==0 ) zFile = "";
  80458. if( zName==0 ) zName = "";
  80459. /* Check for the following errors:
  80460. **
  80461. ** * Too many attached databases,
  80462. ** * Transaction currently open
  80463. ** * Specified database name already being used.
  80464. */
  80465. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  80466. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  80467. db->aLimit[SQLITE_LIMIT_ATTACHED]
  80468. );
  80469. goto attach_error;
  80470. }
  80471. if( !db->autoCommit ){
  80472. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  80473. goto attach_error;
  80474. }
  80475. for(i=0; i<db->nDb; i++){
  80476. char *z = db->aDb[i].zName;
  80477. assert( z && zName );
  80478. if( sqlite3StrICmp(z, zName)==0 ){
  80479. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  80480. goto attach_error;
  80481. }
  80482. }
  80483. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  80484. ** hash tables.
  80485. */
  80486. if( db->aDb==db->aDbStatic ){
  80487. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  80488. if( aNew==0 ) return;
  80489. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  80490. }else{
  80491. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  80492. if( aNew==0 ) return;
  80493. }
  80494. db->aDb = aNew;
  80495. aNew = &db->aDb[db->nDb];
  80496. memset(aNew, 0, sizeof(*aNew));
  80497. /* Open the database file. If the btree is successfully opened, use
  80498. ** it to obtain the database schema. At this point the schema may
  80499. ** or may not be initialized.
  80500. */
  80501. flags = db->openFlags;
  80502. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  80503. if( rc!=SQLITE_OK ){
  80504. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  80505. sqlite3_result_error(context, zErr, -1);
  80506. sqlite3_free(zErr);
  80507. return;
  80508. }
  80509. assert( pVfs );
  80510. flags |= SQLITE_OPEN_MAIN_DB;
  80511. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  80512. sqlite3_free( zPath );
  80513. db->nDb++;
  80514. if( rc==SQLITE_CONSTRAINT ){
  80515. rc = SQLITE_ERROR;
  80516. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  80517. }else if( rc==SQLITE_OK ){
  80518. Pager *pPager;
  80519. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  80520. if( !aNew->pSchema ){
  80521. rc = SQLITE_NOMEM;
  80522. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  80523. zErrDyn = sqlite3MPrintf(db,
  80524. "attached databases must use the same text encoding as main database");
  80525. rc = SQLITE_ERROR;
  80526. }
  80527. pPager = sqlite3BtreePager(aNew->pBt);
  80528. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  80529. sqlite3BtreeSecureDelete(aNew->pBt,
  80530. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  80531. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80532. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  80533. #endif
  80534. }
  80535. aNew->safety_level = 3;
  80536. aNew->zName = sqlite3DbStrDup(db, zName);
  80537. if( rc==SQLITE_OK && aNew->zName==0 ){
  80538. rc = SQLITE_NOMEM;
  80539. }
  80540. #ifdef SQLITE_HAS_CODEC
  80541. if( rc==SQLITE_OK ){
  80542. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  80543. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  80544. int nKey;
  80545. char *zKey;
  80546. int t = sqlite3_value_type(argv[2]);
  80547. switch( t ){
  80548. case SQLITE_INTEGER:
  80549. case SQLITE_FLOAT:
  80550. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  80551. rc = SQLITE_ERROR;
  80552. break;
  80553. case SQLITE_TEXT:
  80554. case SQLITE_BLOB:
  80555. nKey = sqlite3_value_bytes(argv[2]);
  80556. zKey = (char *)sqlite3_value_blob(argv[2]);
  80557. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  80558. break;
  80559. case SQLITE_NULL:
  80560. /* No key specified. Use the key from the main database */
  80561. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  80562. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  80563. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  80564. }
  80565. break;
  80566. }
  80567. }
  80568. #endif
  80569. /* If the file was opened successfully, read the schema for the new database.
  80570. ** If this fails, or if opening the file failed, then close the file and
  80571. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  80572. ** we found it.
  80573. */
  80574. if( rc==SQLITE_OK ){
  80575. sqlite3BtreeEnterAll(db);
  80576. rc = sqlite3Init(db, &zErrDyn);
  80577. sqlite3BtreeLeaveAll(db);
  80578. }
  80579. if( rc ){
  80580. int iDb = db->nDb - 1;
  80581. assert( iDb>=2 );
  80582. if( db->aDb[iDb].pBt ){
  80583. sqlite3BtreeClose(db->aDb[iDb].pBt);
  80584. db->aDb[iDb].pBt = 0;
  80585. db->aDb[iDb].pSchema = 0;
  80586. }
  80587. sqlite3ResetAllSchemasOfConnection(db);
  80588. db->nDb = iDb;
  80589. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  80590. db->mallocFailed = 1;
  80591. sqlite3DbFree(db, zErrDyn);
  80592. zErrDyn = sqlite3MPrintf(db, "out of memory");
  80593. }else if( zErrDyn==0 ){
  80594. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  80595. }
  80596. goto attach_error;
  80597. }
  80598. return;
  80599. attach_error:
  80600. /* Return an error if we get here */
  80601. if( zErrDyn ){
  80602. sqlite3_result_error(context, zErrDyn, -1);
  80603. sqlite3DbFree(db, zErrDyn);
  80604. }
  80605. if( rc ) sqlite3_result_error_code(context, rc);
  80606. }
  80607. /*
  80608. ** An SQL user-function registered to do the work of an DETACH statement. The
  80609. ** three arguments to the function come directly from a detach statement:
  80610. **
  80611. ** DETACH DATABASE x
  80612. **
  80613. ** SELECT sqlite_detach(x)
  80614. */
  80615. static void detachFunc(
  80616. sqlite3_context *context,
  80617. int NotUsed,
  80618. sqlite3_value **argv
  80619. ){
  80620. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  80621. sqlite3 *db = sqlite3_context_db_handle(context);
  80622. int i;
  80623. Db *pDb = 0;
  80624. char zErr[128];
  80625. UNUSED_PARAMETER(NotUsed);
  80626. if( zName==0 ) zName = "";
  80627. for(i=0; i<db->nDb; i++){
  80628. pDb = &db->aDb[i];
  80629. if( pDb->pBt==0 ) continue;
  80630. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  80631. }
  80632. if( i>=db->nDb ){
  80633. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  80634. goto detach_error;
  80635. }
  80636. if( i<2 ){
  80637. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  80638. goto detach_error;
  80639. }
  80640. if( !db->autoCommit ){
  80641. sqlite3_snprintf(sizeof(zErr), zErr,
  80642. "cannot DETACH database within transaction");
  80643. goto detach_error;
  80644. }
  80645. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  80646. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  80647. goto detach_error;
  80648. }
  80649. sqlite3BtreeClose(pDb->pBt);
  80650. pDb->pBt = 0;
  80651. pDb->pSchema = 0;
  80652. sqlite3ResetAllSchemasOfConnection(db);
  80653. return;
  80654. detach_error:
  80655. sqlite3_result_error(context, zErr, -1);
  80656. }
  80657. /*
  80658. ** This procedure generates VDBE code for a single invocation of either the
  80659. ** sqlite_detach() or sqlite_attach() SQL user functions.
  80660. */
  80661. static void codeAttach(
  80662. Parse *pParse, /* The parser context */
  80663. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  80664. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  80665. Expr *pAuthArg, /* Expression to pass to authorization callback */
  80666. Expr *pFilename, /* Name of database file */
  80667. Expr *pDbname, /* Name of the database to use internally */
  80668. Expr *pKey /* Database key for encryption extension */
  80669. ){
  80670. int rc;
  80671. NameContext sName;
  80672. Vdbe *v;
  80673. sqlite3* db = pParse->db;
  80674. int regArgs;
  80675. memset(&sName, 0, sizeof(NameContext));
  80676. sName.pParse = pParse;
  80677. if(
  80678. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  80679. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  80680. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  80681. ){
  80682. pParse->nErr++;
  80683. goto attach_end;
  80684. }
  80685. #ifndef SQLITE_OMIT_AUTHORIZATION
  80686. if( pAuthArg ){
  80687. char *zAuthArg;
  80688. if( pAuthArg->op==TK_STRING ){
  80689. zAuthArg = pAuthArg->u.zToken;
  80690. }else{
  80691. zAuthArg = 0;
  80692. }
  80693. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  80694. if(rc!=SQLITE_OK ){
  80695. goto attach_end;
  80696. }
  80697. }
  80698. #endif /* SQLITE_OMIT_AUTHORIZATION */
  80699. v = sqlite3GetVdbe(pParse);
  80700. regArgs = sqlite3GetTempRange(pParse, 4);
  80701. sqlite3ExprCode(pParse, pFilename, regArgs);
  80702. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  80703. sqlite3ExprCode(pParse, pKey, regArgs+2);
  80704. assert( v || db->mallocFailed );
  80705. if( v ){
  80706. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  80707. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  80708. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  80709. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  80710. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  80711. ** statement only). For DETACH, set it to false (expire all existing
  80712. ** statements).
  80713. */
  80714. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  80715. }
  80716. attach_end:
  80717. sqlite3ExprDelete(db, pFilename);
  80718. sqlite3ExprDelete(db, pDbname);
  80719. sqlite3ExprDelete(db, pKey);
  80720. }
  80721. /*
  80722. ** Called by the parser to compile a DETACH statement.
  80723. **
  80724. ** DETACH pDbname
  80725. */
  80726. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  80727. static const FuncDef detach_func = {
  80728. 1, /* nArg */
  80729. SQLITE_UTF8, /* funcFlags */
  80730. 0, /* pUserData */
  80731. 0, /* pNext */
  80732. detachFunc, /* xFunc */
  80733. 0, /* xStep */
  80734. 0, /* xFinalize */
  80735. "sqlite_detach", /* zName */
  80736. 0, /* pHash */
  80737. 0 /* pDestructor */
  80738. };
  80739. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  80740. }
  80741. /*
  80742. ** Called by the parser to compile an ATTACH statement.
  80743. **
  80744. ** ATTACH p AS pDbname KEY pKey
  80745. */
  80746. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  80747. static const FuncDef attach_func = {
  80748. 3, /* nArg */
  80749. SQLITE_UTF8, /* funcFlags */
  80750. 0, /* pUserData */
  80751. 0, /* pNext */
  80752. attachFunc, /* xFunc */
  80753. 0, /* xStep */
  80754. 0, /* xFinalize */
  80755. "sqlite_attach", /* zName */
  80756. 0, /* pHash */
  80757. 0 /* pDestructor */
  80758. };
  80759. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  80760. }
  80761. #endif /* SQLITE_OMIT_ATTACH */
  80762. /*
  80763. ** Initialize a DbFixer structure. This routine must be called prior
  80764. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  80765. */
  80766. SQLITE_PRIVATE void sqlite3FixInit(
  80767. DbFixer *pFix, /* The fixer to be initialized */
  80768. Parse *pParse, /* Error messages will be written here */
  80769. int iDb, /* This is the database that must be used */
  80770. const char *zType, /* "view", "trigger", or "index" */
  80771. const Token *pName /* Name of the view, trigger, or index */
  80772. ){
  80773. sqlite3 *db;
  80774. db = pParse->db;
  80775. assert( db->nDb>iDb );
  80776. pFix->pParse = pParse;
  80777. pFix->zDb = db->aDb[iDb].zName;
  80778. pFix->pSchema = db->aDb[iDb].pSchema;
  80779. pFix->zType = zType;
  80780. pFix->pName = pName;
  80781. pFix->bVarOnly = (iDb==1);
  80782. }
  80783. /*
  80784. ** The following set of routines walk through the parse tree and assign
  80785. ** a specific database to all table references where the database name
  80786. ** was left unspecified in the original SQL statement. The pFix structure
  80787. ** must have been initialized by a prior call to sqlite3FixInit().
  80788. **
  80789. ** These routines are used to make sure that an index, trigger, or
  80790. ** view in one database does not refer to objects in a different database.
  80791. ** (Exception: indices, triggers, and views in the TEMP database are
  80792. ** allowed to refer to anything.) If a reference is explicitly made
  80793. ** to an object in a different database, an error message is added to
  80794. ** pParse->zErrMsg and these routines return non-zero. If everything
  80795. ** checks out, these routines return 0.
  80796. */
  80797. SQLITE_PRIVATE int sqlite3FixSrcList(
  80798. DbFixer *pFix, /* Context of the fixation */
  80799. SrcList *pList /* The Source list to check and modify */
  80800. ){
  80801. int i;
  80802. const char *zDb;
  80803. struct SrcList_item *pItem;
  80804. if( NEVER(pList==0) ) return 0;
  80805. zDb = pFix->zDb;
  80806. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  80807. if( pFix->bVarOnly==0 ){
  80808. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  80809. sqlite3ErrorMsg(pFix->pParse,
  80810. "%s %T cannot reference objects in database %s",
  80811. pFix->zType, pFix->pName, pItem->zDatabase);
  80812. return 1;
  80813. }
  80814. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  80815. pItem->zDatabase = 0;
  80816. pItem->pSchema = pFix->pSchema;
  80817. }
  80818. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  80819. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  80820. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  80821. #endif
  80822. }
  80823. return 0;
  80824. }
  80825. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  80826. SQLITE_PRIVATE int sqlite3FixSelect(
  80827. DbFixer *pFix, /* Context of the fixation */
  80828. Select *pSelect /* The SELECT statement to be fixed to one database */
  80829. ){
  80830. while( pSelect ){
  80831. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  80832. return 1;
  80833. }
  80834. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  80835. return 1;
  80836. }
  80837. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  80838. return 1;
  80839. }
  80840. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  80841. return 1;
  80842. }
  80843. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  80844. return 1;
  80845. }
  80846. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  80847. return 1;
  80848. }
  80849. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  80850. return 1;
  80851. }
  80852. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  80853. return 1;
  80854. }
  80855. pSelect = pSelect->pPrior;
  80856. }
  80857. return 0;
  80858. }
  80859. SQLITE_PRIVATE int sqlite3FixExpr(
  80860. DbFixer *pFix, /* Context of the fixation */
  80861. Expr *pExpr /* The expression to be fixed to one database */
  80862. ){
  80863. while( pExpr ){
  80864. if( pExpr->op==TK_VARIABLE ){
  80865. if( pFix->pParse->db->init.busy ){
  80866. pExpr->op = TK_NULL;
  80867. }else{
  80868. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  80869. return 1;
  80870. }
  80871. }
  80872. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  80873. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80874. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  80875. }else{
  80876. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  80877. }
  80878. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  80879. return 1;
  80880. }
  80881. pExpr = pExpr->pLeft;
  80882. }
  80883. return 0;
  80884. }
  80885. SQLITE_PRIVATE int sqlite3FixExprList(
  80886. DbFixer *pFix, /* Context of the fixation */
  80887. ExprList *pList /* The expression to be fixed to one database */
  80888. ){
  80889. int i;
  80890. struct ExprList_item *pItem;
  80891. if( pList==0 ) return 0;
  80892. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  80893. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  80894. return 1;
  80895. }
  80896. }
  80897. return 0;
  80898. }
  80899. #endif
  80900. #ifndef SQLITE_OMIT_TRIGGER
  80901. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  80902. DbFixer *pFix, /* Context of the fixation */
  80903. TriggerStep *pStep /* The trigger step be fixed to one database */
  80904. ){
  80905. while( pStep ){
  80906. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  80907. return 1;
  80908. }
  80909. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  80910. return 1;
  80911. }
  80912. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  80913. return 1;
  80914. }
  80915. pStep = pStep->pNext;
  80916. }
  80917. return 0;
  80918. }
  80919. #endif
  80920. /************** End of attach.c **********************************************/
  80921. /************** Begin file auth.c ********************************************/
  80922. /*
  80923. ** 2003 January 11
  80924. **
  80925. ** The author disclaims copyright to this source code. In place of
  80926. ** a legal notice, here is a blessing:
  80927. **
  80928. ** May you do good and not evil.
  80929. ** May you find forgiveness for yourself and forgive others.
  80930. ** May you share freely, never taking more than you give.
  80931. **
  80932. *************************************************************************
  80933. ** This file contains code used to implement the sqlite3_set_authorizer()
  80934. ** API. This facility is an optional feature of the library. Embedded
  80935. ** systems that do not need this facility may omit it by recompiling
  80936. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  80937. */
  80938. /*
  80939. ** All of the code in this file may be omitted by defining a single
  80940. ** macro.
  80941. */
  80942. #ifndef SQLITE_OMIT_AUTHORIZATION
  80943. /*
  80944. ** Set or clear the access authorization function.
  80945. **
  80946. ** The access authorization function is be called during the compilation
  80947. ** phase to verify that the user has read and/or write access permission on
  80948. ** various fields of the database. The first argument to the auth function
  80949. ** is a copy of the 3rd argument to this routine. The second argument
  80950. ** to the auth function is one of these constants:
  80951. **
  80952. ** SQLITE_CREATE_INDEX
  80953. ** SQLITE_CREATE_TABLE
  80954. ** SQLITE_CREATE_TEMP_INDEX
  80955. ** SQLITE_CREATE_TEMP_TABLE
  80956. ** SQLITE_CREATE_TEMP_TRIGGER
  80957. ** SQLITE_CREATE_TEMP_VIEW
  80958. ** SQLITE_CREATE_TRIGGER
  80959. ** SQLITE_CREATE_VIEW
  80960. ** SQLITE_DELETE
  80961. ** SQLITE_DROP_INDEX
  80962. ** SQLITE_DROP_TABLE
  80963. ** SQLITE_DROP_TEMP_INDEX
  80964. ** SQLITE_DROP_TEMP_TABLE
  80965. ** SQLITE_DROP_TEMP_TRIGGER
  80966. ** SQLITE_DROP_TEMP_VIEW
  80967. ** SQLITE_DROP_TRIGGER
  80968. ** SQLITE_DROP_VIEW
  80969. ** SQLITE_INSERT
  80970. ** SQLITE_PRAGMA
  80971. ** SQLITE_READ
  80972. ** SQLITE_SELECT
  80973. ** SQLITE_TRANSACTION
  80974. ** SQLITE_UPDATE
  80975. **
  80976. ** The third and fourth arguments to the auth function are the name of
  80977. ** the table and the column that are being accessed. The auth function
  80978. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  80979. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  80980. ** means that the SQL statement will never-run - the sqlite3_exec() call
  80981. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  80982. ** should run but attempts to read the specified column will return NULL
  80983. ** and attempts to write the column will be ignored.
  80984. **
  80985. ** Setting the auth function to NULL disables this hook. The default
  80986. ** setting of the auth function is NULL.
  80987. */
  80988. SQLITE_API int sqlite3_set_authorizer(
  80989. sqlite3 *db,
  80990. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  80991. void *pArg
  80992. ){
  80993. sqlite3_mutex_enter(db->mutex);
  80994. db->xAuth = xAuth;
  80995. db->pAuthArg = pArg;
  80996. sqlite3ExpirePreparedStatements(db);
  80997. sqlite3_mutex_leave(db->mutex);
  80998. return SQLITE_OK;
  80999. }
  81000. /*
  81001. ** Write an error message into pParse->zErrMsg that explains that the
  81002. ** user-supplied authorization function returned an illegal value.
  81003. */
  81004. static void sqliteAuthBadReturnCode(Parse *pParse){
  81005. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  81006. pParse->rc = SQLITE_ERROR;
  81007. }
  81008. /*
  81009. ** Invoke the authorization callback for permission to read column zCol from
  81010. ** table zTab in database zDb. This function assumes that an authorization
  81011. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  81012. **
  81013. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  81014. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  81015. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  81016. */
  81017. SQLITE_PRIVATE int sqlite3AuthReadCol(
  81018. Parse *pParse, /* The parser context */
  81019. const char *zTab, /* Table name */
  81020. const char *zCol, /* Column name */
  81021. int iDb /* Index of containing database. */
  81022. ){
  81023. sqlite3 *db = pParse->db; /* Database handle */
  81024. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  81025. int rc; /* Auth callback return code */
  81026. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  81027. if( rc==SQLITE_DENY ){
  81028. if( db->nDb>2 || iDb!=0 ){
  81029. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  81030. }else{
  81031. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  81032. }
  81033. pParse->rc = SQLITE_AUTH;
  81034. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  81035. sqliteAuthBadReturnCode(pParse);
  81036. }
  81037. return rc;
  81038. }
  81039. /*
  81040. ** The pExpr should be a TK_COLUMN expression. The table referred to
  81041. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  81042. ** Check to see if it is OK to read this particular column.
  81043. **
  81044. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  81045. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  81046. ** then generate an error.
  81047. */
  81048. SQLITE_PRIVATE void sqlite3AuthRead(
  81049. Parse *pParse, /* The parser context */
  81050. Expr *pExpr, /* The expression to check authorization on */
  81051. Schema *pSchema, /* The schema of the expression */
  81052. SrcList *pTabList /* All table that pExpr might refer to */
  81053. ){
  81054. sqlite3 *db = pParse->db;
  81055. Table *pTab = 0; /* The table being read */
  81056. const char *zCol; /* Name of the column of the table */
  81057. int iSrc; /* Index in pTabList->a[] of table being read */
  81058. int iDb; /* The index of the database the expression refers to */
  81059. int iCol; /* Index of column in table */
  81060. if( db->xAuth==0 ) return;
  81061. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  81062. if( iDb<0 ){
  81063. /* An attempt to read a column out of a subquery or other
  81064. ** temporary table. */
  81065. return;
  81066. }
  81067. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  81068. if( pExpr->op==TK_TRIGGER ){
  81069. pTab = pParse->pTriggerTab;
  81070. }else{
  81071. assert( pTabList );
  81072. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  81073. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  81074. pTab = pTabList->a[iSrc].pTab;
  81075. break;
  81076. }
  81077. }
  81078. }
  81079. iCol = pExpr->iColumn;
  81080. if( NEVER(pTab==0) ) return;
  81081. if( iCol>=0 ){
  81082. assert( iCol<pTab->nCol );
  81083. zCol = pTab->aCol[iCol].zName;
  81084. }else if( pTab->iPKey>=0 ){
  81085. assert( pTab->iPKey<pTab->nCol );
  81086. zCol = pTab->aCol[pTab->iPKey].zName;
  81087. }else{
  81088. zCol = "ROWID";
  81089. }
  81090. assert( iDb>=0 && iDb<db->nDb );
  81091. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  81092. pExpr->op = TK_NULL;
  81093. }
  81094. }
  81095. /*
  81096. ** Do an authorization check using the code and arguments given. Return
  81097. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  81098. ** is returned, then the error count and error message in pParse are
  81099. ** modified appropriately.
  81100. */
  81101. SQLITE_PRIVATE int sqlite3AuthCheck(
  81102. Parse *pParse,
  81103. int code,
  81104. const char *zArg1,
  81105. const char *zArg2,
  81106. const char *zArg3
  81107. ){
  81108. sqlite3 *db = pParse->db;
  81109. int rc;
  81110. /* Don't do any authorization checks if the database is initialising
  81111. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  81112. */
  81113. if( db->init.busy || IN_DECLARE_VTAB ){
  81114. return SQLITE_OK;
  81115. }
  81116. if( db->xAuth==0 ){
  81117. return SQLITE_OK;
  81118. }
  81119. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  81120. if( rc==SQLITE_DENY ){
  81121. sqlite3ErrorMsg(pParse, "not authorized");
  81122. pParse->rc = SQLITE_AUTH;
  81123. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  81124. rc = SQLITE_DENY;
  81125. sqliteAuthBadReturnCode(pParse);
  81126. }
  81127. return rc;
  81128. }
  81129. /*
  81130. ** Push an authorization context. After this routine is called, the
  81131. ** zArg3 argument to authorization callbacks will be zContext until
  81132. ** popped. Or if pParse==0, this routine is a no-op.
  81133. */
  81134. SQLITE_PRIVATE void sqlite3AuthContextPush(
  81135. Parse *pParse,
  81136. AuthContext *pContext,
  81137. const char *zContext
  81138. ){
  81139. assert( pParse );
  81140. pContext->pParse = pParse;
  81141. pContext->zAuthContext = pParse->zAuthContext;
  81142. pParse->zAuthContext = zContext;
  81143. }
  81144. /*
  81145. ** Pop an authorization context that was previously pushed
  81146. ** by sqlite3AuthContextPush
  81147. */
  81148. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  81149. if( pContext->pParse ){
  81150. pContext->pParse->zAuthContext = pContext->zAuthContext;
  81151. pContext->pParse = 0;
  81152. }
  81153. }
  81154. #endif /* SQLITE_OMIT_AUTHORIZATION */
  81155. /************** End of auth.c ************************************************/
  81156. /************** Begin file build.c *******************************************/
  81157. /*
  81158. ** 2001 September 15
  81159. **
  81160. ** The author disclaims copyright to this source code. In place of
  81161. ** a legal notice, here is a blessing:
  81162. **
  81163. ** May you do good and not evil.
  81164. ** May you find forgiveness for yourself and forgive others.
  81165. ** May you share freely, never taking more than you give.
  81166. **
  81167. *************************************************************************
  81168. ** This file contains C code routines that are called by the SQLite parser
  81169. ** when syntax rules are reduced. The routines in this file handle the
  81170. ** following kinds of SQL syntax:
  81171. **
  81172. ** CREATE TABLE
  81173. ** DROP TABLE
  81174. ** CREATE INDEX
  81175. ** DROP INDEX
  81176. ** creating ID lists
  81177. ** BEGIN TRANSACTION
  81178. ** COMMIT
  81179. ** ROLLBACK
  81180. */
  81181. /*
  81182. ** This routine is called when a new SQL statement is beginning to
  81183. ** be parsed. Initialize the pParse structure as needed.
  81184. */
  81185. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  81186. pParse->explain = (u8)explainFlag;
  81187. pParse->nVar = 0;
  81188. }
  81189. #ifndef SQLITE_OMIT_SHARED_CACHE
  81190. /*
  81191. ** The TableLock structure is only used by the sqlite3TableLock() and
  81192. ** codeTableLocks() functions.
  81193. */
  81194. struct TableLock {
  81195. int iDb; /* The database containing the table to be locked */
  81196. int iTab; /* The root page of the table to be locked */
  81197. u8 isWriteLock; /* True for write lock. False for a read lock */
  81198. const char *zName; /* Name of the table */
  81199. };
  81200. /*
  81201. ** Record the fact that we want to lock a table at run-time.
  81202. **
  81203. ** The table to be locked has root page iTab and is found in database iDb.
  81204. ** A read or a write lock can be taken depending on isWritelock.
  81205. **
  81206. ** This routine just records the fact that the lock is desired. The
  81207. ** code to make the lock occur is generated by a later call to
  81208. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  81209. */
  81210. SQLITE_PRIVATE void sqlite3TableLock(
  81211. Parse *pParse, /* Parsing context */
  81212. int iDb, /* Index of the database containing the table to lock */
  81213. int iTab, /* Root page number of the table to be locked */
  81214. u8 isWriteLock, /* True for a write lock */
  81215. const char *zName /* Name of the table to be locked */
  81216. ){
  81217. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81218. int i;
  81219. int nBytes;
  81220. TableLock *p;
  81221. assert( iDb>=0 );
  81222. for(i=0; i<pToplevel->nTableLock; i++){
  81223. p = &pToplevel->aTableLock[i];
  81224. if( p->iDb==iDb && p->iTab==iTab ){
  81225. p->isWriteLock = (p->isWriteLock || isWriteLock);
  81226. return;
  81227. }
  81228. }
  81229. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  81230. pToplevel->aTableLock =
  81231. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  81232. if( pToplevel->aTableLock ){
  81233. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  81234. p->iDb = iDb;
  81235. p->iTab = iTab;
  81236. p->isWriteLock = isWriteLock;
  81237. p->zName = zName;
  81238. }else{
  81239. pToplevel->nTableLock = 0;
  81240. pToplevel->db->mallocFailed = 1;
  81241. }
  81242. }
  81243. /*
  81244. ** Code an OP_TableLock instruction for each table locked by the
  81245. ** statement (configured by calls to sqlite3TableLock()).
  81246. */
  81247. static void codeTableLocks(Parse *pParse){
  81248. int i;
  81249. Vdbe *pVdbe;
  81250. pVdbe = sqlite3GetVdbe(pParse);
  81251. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  81252. for(i=0; i<pParse->nTableLock; i++){
  81253. TableLock *p = &pParse->aTableLock[i];
  81254. int p1 = p->iDb;
  81255. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  81256. p->zName, P4_STATIC);
  81257. }
  81258. }
  81259. #else
  81260. #define codeTableLocks(x)
  81261. #endif
  81262. /*
  81263. ** This routine is called after a single SQL statement has been
  81264. ** parsed and a VDBE program to execute that statement has been
  81265. ** prepared. This routine puts the finishing touches on the
  81266. ** VDBE program and resets the pParse structure for the next
  81267. ** parse.
  81268. **
  81269. ** Note that if an error occurred, it might be the case that
  81270. ** no VDBE code was generated.
  81271. */
  81272. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  81273. sqlite3 *db;
  81274. Vdbe *v;
  81275. assert( pParse->pToplevel==0 );
  81276. db = pParse->db;
  81277. if( db->mallocFailed ) return;
  81278. if( pParse->nested ) return;
  81279. if( pParse->nErr ) return;
  81280. /* Begin by generating some termination code at the end of the
  81281. ** vdbe program
  81282. */
  81283. v = sqlite3GetVdbe(pParse);
  81284. assert( !pParse->isMultiWrite
  81285. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  81286. if( v ){
  81287. sqlite3VdbeAddOp0(v, OP_Halt);
  81288. /* The cookie mask contains one bit for each database file open.
  81289. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  81290. ** set for each database that is used. Generate code to start a
  81291. ** transaction on each used database and to verify the schema cookie
  81292. ** on each used database.
  81293. */
  81294. if( pParse->cookieGoto>0 ){
  81295. yDbMask mask;
  81296. int iDb;
  81297. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  81298. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  81299. if( (mask & pParse->cookieMask)==0 ) continue;
  81300. sqlite3VdbeUsesBtree(v, iDb);
  81301. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  81302. if( db->init.busy==0 ){
  81303. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81304. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  81305. iDb, pParse->cookieValue[iDb],
  81306. db->aDb[iDb].pSchema->iGeneration);
  81307. }
  81308. }
  81309. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81310. {
  81311. int i;
  81312. for(i=0; i<pParse->nVtabLock; i++){
  81313. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  81314. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  81315. }
  81316. pParse->nVtabLock = 0;
  81317. }
  81318. #endif
  81319. /* Once all the cookies have been verified and transactions opened,
  81320. ** obtain the required table-locks. This is a no-op unless the
  81321. ** shared-cache feature is enabled.
  81322. */
  81323. codeTableLocks(pParse);
  81324. /* Initialize any AUTOINCREMENT data structures required.
  81325. */
  81326. sqlite3AutoincrementBegin(pParse);
  81327. /* Finally, jump back to the beginning of the executable code. */
  81328. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  81329. }
  81330. }
  81331. /* Get the VDBE program ready for execution
  81332. */
  81333. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  81334. #ifdef SQLITE_DEBUG
  81335. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  81336. sqlite3VdbeTrace(v, trace);
  81337. #endif
  81338. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  81339. /* A minimum of one cursor is required if autoincrement is used
  81340. * See ticket [a696379c1f08866] */
  81341. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  81342. sqlite3VdbeMakeReady(v, pParse);
  81343. pParse->rc = SQLITE_DONE;
  81344. pParse->colNamesSet = 0;
  81345. }else{
  81346. pParse->rc = SQLITE_ERROR;
  81347. }
  81348. pParse->nTab = 0;
  81349. pParse->nMem = 0;
  81350. pParse->nSet = 0;
  81351. pParse->nVar = 0;
  81352. pParse->cookieMask = 0;
  81353. pParse->cookieGoto = 0;
  81354. }
  81355. /*
  81356. ** Run the parser and code generator recursively in order to generate
  81357. ** code for the SQL statement given onto the end of the pParse context
  81358. ** currently under construction. When the parser is run recursively
  81359. ** this way, the final OP_Halt is not appended and other initialization
  81360. ** and finalization steps are omitted because those are handling by the
  81361. ** outermost parser.
  81362. **
  81363. ** Not everything is nestable. This facility is designed to permit
  81364. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  81365. ** care if you decide to try to use this routine for some other purposes.
  81366. */
  81367. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  81368. va_list ap;
  81369. char *zSql;
  81370. char *zErrMsg = 0;
  81371. sqlite3 *db = pParse->db;
  81372. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  81373. char saveBuf[SAVE_SZ];
  81374. if( pParse->nErr ) return;
  81375. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  81376. va_start(ap, zFormat);
  81377. zSql = sqlite3VMPrintf(db, zFormat, ap);
  81378. va_end(ap);
  81379. if( zSql==0 ){
  81380. return; /* A malloc must have failed */
  81381. }
  81382. pParse->nested++;
  81383. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  81384. memset(&pParse->nVar, 0, SAVE_SZ);
  81385. sqlite3RunParser(pParse, zSql, &zErrMsg);
  81386. sqlite3DbFree(db, zErrMsg);
  81387. sqlite3DbFree(db, zSql);
  81388. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  81389. pParse->nested--;
  81390. }
  81391. /*
  81392. ** Locate the in-memory structure that describes a particular database
  81393. ** table given the name of that table and (optionally) the name of the
  81394. ** database containing the table. Return NULL if not found.
  81395. **
  81396. ** If zDatabase is 0, all databases are searched for the table and the
  81397. ** first matching table is returned. (No checking for duplicate table
  81398. ** names is done.) The search order is TEMP first, then MAIN, then any
  81399. ** auxiliary databases added using the ATTACH command.
  81400. **
  81401. ** See also sqlite3LocateTable().
  81402. */
  81403. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  81404. Table *p = 0;
  81405. int i;
  81406. int nName;
  81407. assert( zName!=0 );
  81408. nName = sqlite3Strlen30(zName);
  81409. /* All mutexes are required for schema access. Make sure we hold them. */
  81410. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  81411. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  81412. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  81413. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  81414. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  81415. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  81416. if( p ) break;
  81417. }
  81418. return p;
  81419. }
  81420. /*
  81421. ** Locate the in-memory structure that describes a particular database
  81422. ** table given the name of that table and (optionally) the name of the
  81423. ** database containing the table. Return NULL if not found. Also leave an
  81424. ** error message in pParse->zErrMsg.
  81425. **
  81426. ** The difference between this routine and sqlite3FindTable() is that this
  81427. ** routine leaves an error message in pParse->zErrMsg where
  81428. ** sqlite3FindTable() does not.
  81429. */
  81430. SQLITE_PRIVATE Table *sqlite3LocateTable(
  81431. Parse *pParse, /* context in which to report errors */
  81432. int isView, /* True if looking for a VIEW rather than a TABLE */
  81433. const char *zName, /* Name of the table we are looking for */
  81434. const char *zDbase /* Name of the database. Might be NULL */
  81435. ){
  81436. Table *p;
  81437. /* Read the database schema. If an error occurs, leave an error message
  81438. ** and code in pParse and return NULL. */
  81439. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81440. return 0;
  81441. }
  81442. p = sqlite3FindTable(pParse->db, zName, zDbase);
  81443. if( p==0 ){
  81444. const char *zMsg = isView ? "no such view" : "no such table";
  81445. if( zDbase ){
  81446. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  81447. }else{
  81448. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  81449. }
  81450. pParse->checkSchema = 1;
  81451. }
  81452. return p;
  81453. }
  81454. /*
  81455. ** Locate the table identified by *p.
  81456. **
  81457. ** This is a wrapper around sqlite3LocateTable(). The difference between
  81458. ** sqlite3LocateTable() and this function is that this function restricts
  81459. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  81460. ** non-NULL if it is part of a view or trigger program definition. See
  81461. ** sqlite3FixSrcList() for details.
  81462. */
  81463. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  81464. Parse *pParse,
  81465. int isView,
  81466. struct SrcList_item *p
  81467. ){
  81468. const char *zDb;
  81469. assert( p->pSchema==0 || p->zDatabase==0 );
  81470. if( p->pSchema ){
  81471. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  81472. zDb = pParse->db->aDb[iDb].zName;
  81473. }else{
  81474. zDb = p->zDatabase;
  81475. }
  81476. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  81477. }
  81478. /*
  81479. ** Locate the in-memory structure that describes
  81480. ** a particular index given the name of that index
  81481. ** and the name of the database that contains the index.
  81482. ** Return NULL if not found.
  81483. **
  81484. ** If zDatabase is 0, all databases are searched for the
  81485. ** table and the first matching index is returned. (No checking
  81486. ** for duplicate index names is done.) The search order is
  81487. ** TEMP first, then MAIN, then any auxiliary databases added
  81488. ** using the ATTACH command.
  81489. */
  81490. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  81491. Index *p = 0;
  81492. int i;
  81493. int nName = sqlite3Strlen30(zName);
  81494. /* All mutexes are required for schema access. Make sure we hold them. */
  81495. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  81496. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  81497. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  81498. Schema *pSchema = db->aDb[j].pSchema;
  81499. assert( pSchema );
  81500. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  81501. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  81502. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  81503. if( p ) break;
  81504. }
  81505. return p;
  81506. }
  81507. /*
  81508. ** Reclaim the memory used by an index
  81509. */
  81510. static void freeIndex(sqlite3 *db, Index *p){
  81511. #ifndef SQLITE_OMIT_ANALYZE
  81512. sqlite3DeleteIndexSamples(db, p);
  81513. #endif
  81514. sqlite3ExprDelete(db, p->pPartIdxWhere);
  81515. sqlite3DbFree(db, p->zColAff);
  81516. sqlite3DbFree(db, p);
  81517. }
  81518. /*
  81519. ** For the index called zIdxName which is found in the database iDb,
  81520. ** unlike that index from its Table then remove the index from
  81521. ** the index hash table and free all memory structures associated
  81522. ** with the index.
  81523. */
  81524. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  81525. Index *pIndex;
  81526. int len;
  81527. Hash *pHash;
  81528. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81529. pHash = &db->aDb[iDb].pSchema->idxHash;
  81530. len = sqlite3Strlen30(zIdxName);
  81531. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  81532. if( ALWAYS(pIndex) ){
  81533. if( pIndex->pTable->pIndex==pIndex ){
  81534. pIndex->pTable->pIndex = pIndex->pNext;
  81535. }else{
  81536. Index *p;
  81537. /* Justification of ALWAYS(); The index must be on the list of
  81538. ** indices. */
  81539. p = pIndex->pTable->pIndex;
  81540. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  81541. if( ALWAYS(p && p->pNext==pIndex) ){
  81542. p->pNext = pIndex->pNext;
  81543. }
  81544. }
  81545. freeIndex(db, pIndex);
  81546. }
  81547. db->flags |= SQLITE_InternChanges;
  81548. }
  81549. /*
  81550. ** Look through the list of open database files in db->aDb[] and if
  81551. ** any have been closed, remove them from the list. Reallocate the
  81552. ** db->aDb[] structure to a smaller size, if possible.
  81553. **
  81554. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  81555. ** are never candidates for being collapsed.
  81556. */
  81557. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  81558. int i, j;
  81559. for(i=j=2; i<db->nDb; i++){
  81560. struct Db *pDb = &db->aDb[i];
  81561. if( pDb->pBt==0 ){
  81562. sqlite3DbFree(db, pDb->zName);
  81563. pDb->zName = 0;
  81564. continue;
  81565. }
  81566. if( j<i ){
  81567. db->aDb[j] = db->aDb[i];
  81568. }
  81569. j++;
  81570. }
  81571. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  81572. db->nDb = j;
  81573. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  81574. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  81575. sqlite3DbFree(db, db->aDb);
  81576. db->aDb = db->aDbStatic;
  81577. }
  81578. }
  81579. /*
  81580. ** Reset the schema for the database at index iDb. Also reset the
  81581. ** TEMP schema.
  81582. */
  81583. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  81584. Db *pDb;
  81585. assert( iDb<db->nDb );
  81586. /* Case 1: Reset the single schema identified by iDb */
  81587. pDb = &db->aDb[iDb];
  81588. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81589. assert( pDb->pSchema!=0 );
  81590. sqlite3SchemaClear(pDb->pSchema);
  81591. /* If any database other than TEMP is reset, then also reset TEMP
  81592. ** since TEMP might be holding triggers that reference tables in the
  81593. ** other database.
  81594. */
  81595. if( iDb!=1 ){
  81596. pDb = &db->aDb[1];
  81597. assert( pDb->pSchema!=0 );
  81598. sqlite3SchemaClear(pDb->pSchema);
  81599. }
  81600. return;
  81601. }
  81602. /*
  81603. ** Erase all schema information from all attached databases (including
  81604. ** "main" and "temp") for a single database connection.
  81605. */
  81606. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  81607. int i;
  81608. sqlite3BtreeEnterAll(db);
  81609. for(i=0; i<db->nDb; i++){
  81610. Db *pDb = &db->aDb[i];
  81611. if( pDb->pSchema ){
  81612. sqlite3SchemaClear(pDb->pSchema);
  81613. }
  81614. }
  81615. db->flags &= ~SQLITE_InternChanges;
  81616. sqlite3VtabUnlockList(db);
  81617. sqlite3BtreeLeaveAll(db);
  81618. sqlite3CollapseDatabaseArray(db);
  81619. }
  81620. /*
  81621. ** This routine is called when a commit occurs.
  81622. */
  81623. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  81624. db->flags &= ~SQLITE_InternChanges;
  81625. }
  81626. /*
  81627. ** Delete memory allocated for the column names of a table or view (the
  81628. ** Table.aCol[] array).
  81629. */
  81630. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  81631. int i;
  81632. Column *pCol;
  81633. assert( pTable!=0 );
  81634. if( (pCol = pTable->aCol)!=0 ){
  81635. for(i=0; i<pTable->nCol; i++, pCol++){
  81636. sqlite3DbFree(db, pCol->zName);
  81637. sqlite3ExprDelete(db, pCol->pDflt);
  81638. sqlite3DbFree(db, pCol->zDflt);
  81639. sqlite3DbFree(db, pCol->zType);
  81640. sqlite3DbFree(db, pCol->zColl);
  81641. }
  81642. sqlite3DbFree(db, pTable->aCol);
  81643. }
  81644. }
  81645. /*
  81646. ** Remove the memory data structures associated with the given
  81647. ** Table. No changes are made to disk by this routine.
  81648. **
  81649. ** This routine just deletes the data structure. It does not unlink
  81650. ** the table data structure from the hash table. But it does destroy
  81651. ** memory structures of the indices and foreign keys associated with
  81652. ** the table.
  81653. **
  81654. ** The db parameter is optional. It is needed if the Table object
  81655. ** contains lookaside memory. (Table objects in the schema do not use
  81656. ** lookaside memory, but some ephemeral Table objects do.) Or the
  81657. ** db parameter can be used with db->pnBytesFreed to measure the memory
  81658. ** used by the Table object.
  81659. */
  81660. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  81661. Index *pIndex, *pNext;
  81662. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  81663. assert( !pTable || pTable->nRef>0 );
  81664. /* Do not delete the table until the reference count reaches zero. */
  81665. if( !pTable ) return;
  81666. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  81667. /* Record the number of outstanding lookaside allocations in schema Tables
  81668. ** prior to doing any free() operations. Since schema Tables do not use
  81669. ** lookaside, this number should not change. */
  81670. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  81671. db->lookaside.nOut : 0 );
  81672. /* Delete all indices associated with this table. */
  81673. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  81674. pNext = pIndex->pNext;
  81675. assert( pIndex->pSchema==pTable->pSchema );
  81676. if( !db || db->pnBytesFreed==0 ){
  81677. char *zName = pIndex->zName;
  81678. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  81679. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  81680. );
  81681. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  81682. assert( pOld==pIndex || pOld==0 );
  81683. }
  81684. freeIndex(db, pIndex);
  81685. }
  81686. /* Delete any foreign keys attached to this table. */
  81687. sqlite3FkDelete(db, pTable);
  81688. /* Delete the Table structure itself.
  81689. */
  81690. sqliteDeleteColumnNames(db, pTable);
  81691. sqlite3DbFree(db, pTable->zName);
  81692. sqlite3DbFree(db, pTable->zColAff);
  81693. sqlite3SelectDelete(db, pTable->pSelect);
  81694. #ifndef SQLITE_OMIT_CHECK
  81695. sqlite3ExprListDelete(db, pTable->pCheck);
  81696. #endif
  81697. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81698. sqlite3VtabClear(db, pTable);
  81699. #endif
  81700. sqlite3DbFree(db, pTable);
  81701. /* Verify that no lookaside memory was used by schema tables */
  81702. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  81703. }
  81704. /*
  81705. ** Unlink the given table from the hash tables and the delete the
  81706. ** table structure with all its indices and foreign keys.
  81707. */
  81708. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  81709. Table *p;
  81710. Db *pDb;
  81711. assert( db!=0 );
  81712. assert( iDb>=0 && iDb<db->nDb );
  81713. assert( zTabName );
  81714. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81715. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  81716. pDb = &db->aDb[iDb];
  81717. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  81718. sqlite3Strlen30(zTabName),0);
  81719. sqlite3DeleteTable(db, p);
  81720. db->flags |= SQLITE_InternChanges;
  81721. }
  81722. /*
  81723. ** Given a token, return a string that consists of the text of that
  81724. ** token. Space to hold the returned string
  81725. ** is obtained from sqliteMalloc() and must be freed by the calling
  81726. ** function.
  81727. **
  81728. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  81729. ** surround the body of the token are removed.
  81730. **
  81731. ** Tokens are often just pointers into the original SQL text and so
  81732. ** are not \000 terminated and are not persistent. The returned string
  81733. ** is \000 terminated and is persistent.
  81734. */
  81735. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  81736. char *zName;
  81737. if( pName ){
  81738. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  81739. sqlite3Dequote(zName);
  81740. }else{
  81741. zName = 0;
  81742. }
  81743. return zName;
  81744. }
  81745. /*
  81746. ** Open the sqlite_master table stored in database number iDb for
  81747. ** writing. The table is opened using cursor 0.
  81748. */
  81749. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  81750. Vdbe *v = sqlite3GetVdbe(p);
  81751. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  81752. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  81753. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  81754. if( p->nTab==0 ){
  81755. p->nTab = 1;
  81756. }
  81757. }
  81758. /*
  81759. ** Parameter zName points to a nul-terminated buffer containing the name
  81760. ** of a database ("main", "temp" or the name of an attached db). This
  81761. ** function returns the index of the named database in db->aDb[], or
  81762. ** -1 if the named db cannot be found.
  81763. */
  81764. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  81765. int i = -1; /* Database number */
  81766. if( zName ){
  81767. Db *pDb;
  81768. int n = sqlite3Strlen30(zName);
  81769. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  81770. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  81771. 0==sqlite3StrICmp(pDb->zName, zName) ){
  81772. break;
  81773. }
  81774. }
  81775. }
  81776. return i;
  81777. }
  81778. /*
  81779. ** The token *pName contains the name of a database (either "main" or
  81780. ** "temp" or the name of an attached db). This routine returns the
  81781. ** index of the named database in db->aDb[], or -1 if the named db
  81782. ** does not exist.
  81783. */
  81784. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  81785. int i; /* Database number */
  81786. char *zName; /* Name we are searching for */
  81787. zName = sqlite3NameFromToken(db, pName);
  81788. i = sqlite3FindDbName(db, zName);
  81789. sqlite3DbFree(db, zName);
  81790. return i;
  81791. }
  81792. /* The table or view or trigger name is passed to this routine via tokens
  81793. ** pName1 and pName2. If the table name was fully qualified, for example:
  81794. **
  81795. ** CREATE TABLE xxx.yyy (...);
  81796. **
  81797. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  81798. ** the table name is not fully qualified, i.e.:
  81799. **
  81800. ** CREATE TABLE yyy(...);
  81801. **
  81802. ** Then pName1 is set to "yyy" and pName2 is "".
  81803. **
  81804. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  81805. ** pName2) that stores the unqualified table name. The index of the
  81806. ** database "xxx" is returned.
  81807. */
  81808. SQLITE_PRIVATE int sqlite3TwoPartName(
  81809. Parse *pParse, /* Parsing and code generating context */
  81810. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  81811. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  81812. Token **pUnqual /* Write the unqualified object name here */
  81813. ){
  81814. int iDb; /* Database holding the object */
  81815. sqlite3 *db = pParse->db;
  81816. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  81817. if( db->init.busy ) {
  81818. sqlite3ErrorMsg(pParse, "corrupt database");
  81819. pParse->nErr++;
  81820. return -1;
  81821. }
  81822. *pUnqual = pName2;
  81823. iDb = sqlite3FindDb(db, pName1);
  81824. if( iDb<0 ){
  81825. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  81826. pParse->nErr++;
  81827. return -1;
  81828. }
  81829. }else{
  81830. assert( db->init.iDb==0 || db->init.busy );
  81831. iDb = db->init.iDb;
  81832. *pUnqual = pName1;
  81833. }
  81834. return iDb;
  81835. }
  81836. /*
  81837. ** This routine is used to check if the UTF-8 string zName is a legal
  81838. ** unqualified name for a new schema object (table, index, view or
  81839. ** trigger). All names are legal except those that begin with the string
  81840. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  81841. ** is reserved for internal use.
  81842. */
  81843. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  81844. if( !pParse->db->init.busy && pParse->nested==0
  81845. && (pParse->db->flags & SQLITE_WriteSchema)==0
  81846. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  81847. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  81848. return SQLITE_ERROR;
  81849. }
  81850. return SQLITE_OK;
  81851. }
  81852. /*
  81853. ** Begin constructing a new table representation in memory. This is
  81854. ** the first of several action routines that get called in response
  81855. ** to a CREATE TABLE statement. In particular, this routine is called
  81856. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  81857. ** flag is true if the table should be stored in the auxiliary database
  81858. ** file instead of in the main database file. This is normally the case
  81859. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  81860. ** CREATE and TABLE.
  81861. **
  81862. ** The new table record is initialized and put in pParse->pNewTable.
  81863. ** As more of the CREATE TABLE statement is parsed, additional action
  81864. ** routines will be called to add more information to this record.
  81865. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  81866. ** is called to complete the construction of the new table record.
  81867. */
  81868. SQLITE_PRIVATE void sqlite3StartTable(
  81869. Parse *pParse, /* Parser context */
  81870. Token *pName1, /* First part of the name of the table or view */
  81871. Token *pName2, /* Second part of the name of the table or view */
  81872. int isTemp, /* True if this is a TEMP table */
  81873. int isView, /* True if this is a VIEW */
  81874. int isVirtual, /* True if this is a VIRTUAL table */
  81875. int noErr /* Do nothing if table already exists */
  81876. ){
  81877. Table *pTable;
  81878. char *zName = 0; /* The name of the new table */
  81879. sqlite3 *db = pParse->db;
  81880. Vdbe *v;
  81881. int iDb; /* Database number to create the table in */
  81882. Token *pName; /* Unqualified name of the table to create */
  81883. /* The table or view name to create is passed to this routine via tokens
  81884. ** pName1 and pName2. If the table name was fully qualified, for example:
  81885. **
  81886. ** CREATE TABLE xxx.yyy (...);
  81887. **
  81888. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  81889. ** the table name is not fully qualified, i.e.:
  81890. **
  81891. ** CREATE TABLE yyy(...);
  81892. **
  81893. ** Then pName1 is set to "yyy" and pName2 is "".
  81894. **
  81895. ** The call below sets the pName pointer to point at the token (pName1 or
  81896. ** pName2) that stores the unqualified table name. The variable iDb is
  81897. ** set to the index of the database that the table or view is to be
  81898. ** created in.
  81899. */
  81900. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  81901. if( iDb<0 ) return;
  81902. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  81903. /* If creating a temp table, the name may not be qualified. Unless
  81904. ** the database name is "temp" anyway. */
  81905. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  81906. return;
  81907. }
  81908. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  81909. pParse->sNameToken = *pName;
  81910. zName = sqlite3NameFromToken(db, pName);
  81911. if( zName==0 ) return;
  81912. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  81913. goto begin_table_error;
  81914. }
  81915. if( db->init.iDb==1 ) isTemp = 1;
  81916. #ifndef SQLITE_OMIT_AUTHORIZATION
  81917. assert( (isTemp & 1)==isTemp );
  81918. {
  81919. int code;
  81920. char *zDb = db->aDb[iDb].zName;
  81921. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  81922. goto begin_table_error;
  81923. }
  81924. if( isView ){
  81925. if( !OMIT_TEMPDB && isTemp ){
  81926. code = SQLITE_CREATE_TEMP_VIEW;
  81927. }else{
  81928. code = SQLITE_CREATE_VIEW;
  81929. }
  81930. }else{
  81931. if( !OMIT_TEMPDB && isTemp ){
  81932. code = SQLITE_CREATE_TEMP_TABLE;
  81933. }else{
  81934. code = SQLITE_CREATE_TABLE;
  81935. }
  81936. }
  81937. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  81938. goto begin_table_error;
  81939. }
  81940. }
  81941. #endif
  81942. /* Make sure the new table name does not collide with an existing
  81943. ** index or table name in the same database. Issue an error message if
  81944. ** it does. The exception is if the statement being parsed was passed
  81945. ** to an sqlite3_declare_vtab() call. In that case only the column names
  81946. ** and types will be used, so there is no need to test for namespace
  81947. ** collisions.
  81948. */
  81949. if( !IN_DECLARE_VTAB ){
  81950. char *zDb = db->aDb[iDb].zName;
  81951. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81952. goto begin_table_error;
  81953. }
  81954. pTable = sqlite3FindTable(db, zName, zDb);
  81955. if( pTable ){
  81956. if( !noErr ){
  81957. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  81958. }else{
  81959. assert( !db->init.busy );
  81960. sqlite3CodeVerifySchema(pParse, iDb);
  81961. }
  81962. goto begin_table_error;
  81963. }
  81964. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  81965. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  81966. goto begin_table_error;
  81967. }
  81968. }
  81969. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  81970. if( pTable==0 ){
  81971. db->mallocFailed = 1;
  81972. pParse->rc = SQLITE_NOMEM;
  81973. pParse->nErr++;
  81974. goto begin_table_error;
  81975. }
  81976. pTable->zName = zName;
  81977. pTable->iPKey = -1;
  81978. pTable->pSchema = db->aDb[iDb].pSchema;
  81979. pTable->nRef = 1;
  81980. pTable->nRowEst = 1048576;
  81981. assert( pParse->pNewTable==0 );
  81982. pParse->pNewTable = pTable;
  81983. /* If this is the magic sqlite_sequence table used by autoincrement,
  81984. ** then record a pointer to this table in the main database structure
  81985. ** so that INSERT can find the table easily.
  81986. */
  81987. #ifndef SQLITE_OMIT_AUTOINCREMENT
  81988. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  81989. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81990. pTable->pSchema->pSeqTab = pTable;
  81991. }
  81992. #endif
  81993. /* Begin generating the code that will insert the table record into
  81994. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  81995. ** and allocate the record number for the table entry now. Before any
  81996. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  81997. ** indices to be created and the table record must come before the
  81998. ** indices. Hence, the record number for the table must be allocated
  81999. ** now.
  82000. */
  82001. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  82002. int j1;
  82003. int fileFormat;
  82004. int reg1, reg2, reg3;
  82005. sqlite3BeginWriteOperation(pParse, 0, iDb);
  82006. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82007. if( isVirtual ){
  82008. sqlite3VdbeAddOp0(v, OP_VBegin);
  82009. }
  82010. #endif
  82011. /* If the file format and encoding in the database have not been set,
  82012. ** set them now.
  82013. */
  82014. reg1 = pParse->regRowid = ++pParse->nMem;
  82015. reg2 = pParse->regRoot = ++pParse->nMem;
  82016. reg3 = ++pParse->nMem;
  82017. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  82018. sqlite3VdbeUsesBtree(v, iDb);
  82019. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  82020. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  82021. 1 : SQLITE_MAX_FILE_FORMAT;
  82022. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  82023. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  82024. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  82025. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  82026. sqlite3VdbeJumpHere(v, j1);
  82027. /* This just creates a place-holder record in the sqlite_master table.
  82028. ** The record created does not contain anything yet. It will be replaced
  82029. ** by the real entry in code generated at sqlite3EndTable().
  82030. **
  82031. ** The rowid for the new entry is left in register pParse->regRowid.
  82032. ** The root page number of the new table is left in reg pParse->regRoot.
  82033. ** The rowid and root page number values are needed by the code that
  82034. ** sqlite3EndTable will generate.
  82035. */
  82036. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  82037. if( isView || isVirtual ){
  82038. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  82039. }else
  82040. #endif
  82041. {
  82042. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  82043. }
  82044. sqlite3OpenMasterTable(pParse, iDb);
  82045. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  82046. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  82047. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  82048. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  82049. sqlite3VdbeAddOp0(v, OP_Close);
  82050. }
  82051. /* Normal (non-error) return. */
  82052. return;
  82053. /* If an error occurs, we jump here */
  82054. begin_table_error:
  82055. sqlite3DbFree(db, zName);
  82056. return;
  82057. }
  82058. /*
  82059. ** This macro is used to compare two strings in a case-insensitive manner.
  82060. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  82061. ** produces larger code.
  82062. **
  82063. ** WARNING: This macro is not compatible with the strcmp() family. It
  82064. ** returns true if the two strings are equal, otherwise false.
  82065. */
  82066. #define STRICMP(x, y) (\
  82067. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  82068. sqlite3UpperToLower[*(unsigned char *)(y)] \
  82069. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  82070. /*
  82071. ** Add a new column to the table currently being constructed.
  82072. **
  82073. ** The parser calls this routine once for each column declaration
  82074. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  82075. ** first to get things going. Then this routine is called for each
  82076. ** column.
  82077. */
  82078. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  82079. Table *p;
  82080. int i;
  82081. char *z;
  82082. Column *pCol;
  82083. sqlite3 *db = pParse->db;
  82084. if( (p = pParse->pNewTable)==0 ) return;
  82085. #if SQLITE_MAX_COLUMN
  82086. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  82087. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  82088. return;
  82089. }
  82090. #endif
  82091. z = sqlite3NameFromToken(db, pName);
  82092. if( z==0 ) return;
  82093. for(i=0; i<p->nCol; i++){
  82094. if( STRICMP(z, p->aCol[i].zName) ){
  82095. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  82096. sqlite3DbFree(db, z);
  82097. return;
  82098. }
  82099. }
  82100. if( (p->nCol & 0x7)==0 ){
  82101. Column *aNew;
  82102. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  82103. if( aNew==0 ){
  82104. sqlite3DbFree(db, z);
  82105. return;
  82106. }
  82107. p->aCol = aNew;
  82108. }
  82109. pCol = &p->aCol[p->nCol];
  82110. memset(pCol, 0, sizeof(p->aCol[0]));
  82111. pCol->zName = z;
  82112. /* If there is no type specified, columns have the default affinity
  82113. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  82114. ** be called next to set pCol->affinity correctly.
  82115. */
  82116. pCol->affinity = SQLITE_AFF_NONE;
  82117. pCol->szEst = 1;
  82118. p->nCol++;
  82119. }
  82120. /*
  82121. ** This routine is called by the parser while in the middle of
  82122. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  82123. ** been seen on a column. This routine sets the notNull flag on
  82124. ** the column currently under construction.
  82125. */
  82126. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  82127. Table *p;
  82128. p = pParse->pNewTable;
  82129. if( p==0 || NEVER(p->nCol<1) ) return;
  82130. p->aCol[p->nCol-1].notNull = (u8)onError;
  82131. }
  82132. /*
  82133. ** Scan the column type name zType (length nType) and return the
  82134. ** associated affinity type.
  82135. **
  82136. ** This routine does a case-independent search of zType for the
  82137. ** substrings in the following table. If one of the substrings is
  82138. ** found, the corresponding affinity is returned. If zType contains
  82139. ** more than one of the substrings, entries toward the top of
  82140. ** the table take priority. For example, if zType is 'BLOBINT',
  82141. ** SQLITE_AFF_INTEGER is returned.
  82142. **
  82143. ** Substring | Affinity
  82144. ** --------------------------------
  82145. ** 'INT' | SQLITE_AFF_INTEGER
  82146. ** 'CHAR' | SQLITE_AFF_TEXT
  82147. ** 'CLOB' | SQLITE_AFF_TEXT
  82148. ** 'TEXT' | SQLITE_AFF_TEXT
  82149. ** 'BLOB' | SQLITE_AFF_NONE
  82150. ** 'REAL' | SQLITE_AFF_REAL
  82151. ** 'FLOA' | SQLITE_AFF_REAL
  82152. ** 'DOUB' | SQLITE_AFF_REAL
  82153. **
  82154. ** If none of the substrings in the above table are found,
  82155. ** SQLITE_AFF_NUMERIC is returned.
  82156. */
  82157. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  82158. u32 h = 0;
  82159. char aff = SQLITE_AFF_NUMERIC;
  82160. const char *zChar = 0;
  82161. if( zIn==0 ) return aff;
  82162. while( zIn[0] ){
  82163. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  82164. zIn++;
  82165. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  82166. aff = SQLITE_AFF_TEXT;
  82167. zChar = zIn;
  82168. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  82169. aff = SQLITE_AFF_TEXT;
  82170. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  82171. aff = SQLITE_AFF_TEXT;
  82172. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  82173. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  82174. aff = SQLITE_AFF_NONE;
  82175. if( zIn[0]=='(' ) zChar = zIn;
  82176. #ifndef SQLITE_OMIT_FLOATING_POINT
  82177. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  82178. && aff==SQLITE_AFF_NUMERIC ){
  82179. aff = SQLITE_AFF_REAL;
  82180. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  82181. && aff==SQLITE_AFF_NUMERIC ){
  82182. aff = SQLITE_AFF_REAL;
  82183. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  82184. && aff==SQLITE_AFF_NUMERIC ){
  82185. aff = SQLITE_AFF_REAL;
  82186. #endif
  82187. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  82188. aff = SQLITE_AFF_INTEGER;
  82189. break;
  82190. }
  82191. }
  82192. /* If pszEst is not NULL, store an estimate of the field size. The
  82193. ** estimate is scaled so that the size of an integer is 1. */
  82194. if( pszEst ){
  82195. *pszEst = 1; /* default size is approx 4 bytes */
  82196. if( aff<=SQLITE_AFF_NONE ){
  82197. if( zChar ){
  82198. while( zChar[0] ){
  82199. if( sqlite3Isdigit(zChar[0]) ){
  82200. int v = 0;
  82201. sqlite3GetInt32(zChar, &v);
  82202. v = v/4 + 1;
  82203. if( v>255 ) v = 255;
  82204. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  82205. break;
  82206. }
  82207. zChar++;
  82208. }
  82209. }else{
  82210. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  82211. }
  82212. }
  82213. }
  82214. return aff;
  82215. }
  82216. /*
  82217. ** This routine is called by the parser while in the middle of
  82218. ** parsing a CREATE TABLE statement. The pFirst token is the first
  82219. ** token in the sequence of tokens that describe the type of the
  82220. ** column currently under construction. pLast is the last token
  82221. ** in the sequence. Use this information to construct a string
  82222. ** that contains the typename of the column and store that string
  82223. ** in zType.
  82224. */
  82225. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  82226. Table *p;
  82227. Column *pCol;
  82228. p = pParse->pNewTable;
  82229. if( p==0 || NEVER(p->nCol<1) ) return;
  82230. pCol = &p->aCol[p->nCol-1];
  82231. assert( pCol->zType==0 );
  82232. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  82233. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  82234. }
  82235. /*
  82236. ** The expression is the default value for the most recently added column
  82237. ** of the table currently under construction.
  82238. **
  82239. ** Default value expressions must be constant. Raise an exception if this
  82240. ** is not the case.
  82241. **
  82242. ** This routine is called by the parser while in the middle of
  82243. ** parsing a CREATE TABLE statement.
  82244. */
  82245. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  82246. Table *p;
  82247. Column *pCol;
  82248. sqlite3 *db = pParse->db;
  82249. p = pParse->pNewTable;
  82250. if( p!=0 ){
  82251. pCol = &(p->aCol[p->nCol-1]);
  82252. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  82253. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  82254. pCol->zName);
  82255. }else{
  82256. /* A copy of pExpr is used instead of the original, as pExpr contains
  82257. ** tokens that point to volatile memory. The 'span' of the expression
  82258. ** is required by pragma table_info.
  82259. */
  82260. sqlite3ExprDelete(db, pCol->pDflt);
  82261. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  82262. sqlite3DbFree(db, pCol->zDflt);
  82263. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  82264. (int)(pSpan->zEnd - pSpan->zStart));
  82265. }
  82266. }
  82267. sqlite3ExprDelete(db, pSpan->pExpr);
  82268. }
  82269. /*
  82270. ** Designate the PRIMARY KEY for the table. pList is a list of names
  82271. ** of columns that form the primary key. If pList is NULL, then the
  82272. ** most recently added column of the table is the primary key.
  82273. **
  82274. ** A table can have at most one primary key. If the table already has
  82275. ** a primary key (and this is the second primary key) then create an
  82276. ** error.
  82277. **
  82278. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  82279. ** then we will try to use that column as the rowid. Set the Table.iPKey
  82280. ** field of the table under construction to be the index of the
  82281. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  82282. ** no INTEGER PRIMARY KEY.
  82283. **
  82284. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  82285. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  82286. */
  82287. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  82288. Parse *pParse, /* Parsing context */
  82289. ExprList *pList, /* List of field names to be indexed */
  82290. int onError, /* What to do with a uniqueness conflict */
  82291. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  82292. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  82293. ){
  82294. Table *pTab = pParse->pNewTable;
  82295. char *zType = 0;
  82296. int iCol = -1, i;
  82297. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  82298. if( pTab->tabFlags & TF_HasPrimaryKey ){
  82299. sqlite3ErrorMsg(pParse,
  82300. "table \"%s\" has more than one primary key", pTab->zName);
  82301. goto primary_key_exit;
  82302. }
  82303. pTab->tabFlags |= TF_HasPrimaryKey;
  82304. if( pList==0 ){
  82305. iCol = pTab->nCol - 1;
  82306. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  82307. }else{
  82308. for(i=0; i<pList->nExpr; i++){
  82309. for(iCol=0; iCol<pTab->nCol; iCol++){
  82310. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  82311. break;
  82312. }
  82313. }
  82314. if( iCol<pTab->nCol ){
  82315. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  82316. }
  82317. }
  82318. if( pList->nExpr>1 ) iCol = -1;
  82319. }
  82320. if( iCol>=0 && iCol<pTab->nCol ){
  82321. zType = pTab->aCol[iCol].zType;
  82322. }
  82323. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  82324. && sortOrder==SQLITE_SO_ASC ){
  82325. pTab->iPKey = iCol;
  82326. pTab->keyConf = (u8)onError;
  82327. assert( autoInc==0 || autoInc==1 );
  82328. pTab->tabFlags |= autoInc*TF_Autoincrement;
  82329. }else if( autoInc ){
  82330. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82331. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  82332. "INTEGER PRIMARY KEY");
  82333. #endif
  82334. }else{
  82335. Index *p;
  82336. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  82337. 0, sortOrder, 0);
  82338. if( p ){
  82339. p->autoIndex = 2;
  82340. }
  82341. pList = 0;
  82342. }
  82343. primary_key_exit:
  82344. sqlite3ExprListDelete(pParse->db, pList);
  82345. return;
  82346. }
  82347. /*
  82348. ** Add a new CHECK constraint to the table currently under construction.
  82349. */
  82350. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  82351. Parse *pParse, /* Parsing context */
  82352. Expr *pCheckExpr /* The check expression */
  82353. ){
  82354. #ifndef SQLITE_OMIT_CHECK
  82355. Table *pTab = pParse->pNewTable;
  82356. if( pTab && !IN_DECLARE_VTAB ){
  82357. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  82358. if( pParse->constraintName.n ){
  82359. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  82360. }
  82361. }else
  82362. #endif
  82363. {
  82364. sqlite3ExprDelete(pParse->db, pCheckExpr);
  82365. }
  82366. }
  82367. /*
  82368. ** Set the collation function of the most recently parsed table column
  82369. ** to the CollSeq given.
  82370. */
  82371. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  82372. Table *p;
  82373. int i;
  82374. char *zColl; /* Dequoted name of collation sequence */
  82375. sqlite3 *db;
  82376. if( (p = pParse->pNewTable)==0 ) return;
  82377. i = p->nCol-1;
  82378. db = pParse->db;
  82379. zColl = sqlite3NameFromToken(db, pToken);
  82380. if( !zColl ) return;
  82381. if( sqlite3LocateCollSeq(pParse, zColl) ){
  82382. Index *pIdx;
  82383. sqlite3DbFree(db, p->aCol[i].zColl);
  82384. p->aCol[i].zColl = zColl;
  82385. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  82386. ** then an index may have been created on this column before the
  82387. ** collation type was added. Correct this if it is the case.
  82388. */
  82389. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  82390. assert( pIdx->nColumn==1 );
  82391. if( pIdx->aiColumn[0]==i ){
  82392. pIdx->azColl[0] = p->aCol[i].zColl;
  82393. }
  82394. }
  82395. }else{
  82396. sqlite3DbFree(db, zColl);
  82397. }
  82398. }
  82399. /*
  82400. ** This function returns the collation sequence for database native text
  82401. ** encoding identified by the string zName, length nName.
  82402. **
  82403. ** If the requested collation sequence is not available, or not available
  82404. ** in the database native encoding, the collation factory is invoked to
  82405. ** request it. If the collation factory does not supply such a sequence,
  82406. ** and the sequence is available in another text encoding, then that is
  82407. ** returned instead.
  82408. **
  82409. ** If no versions of the requested collations sequence are available, or
  82410. ** another error occurs, NULL is returned and an error message written into
  82411. ** pParse.
  82412. **
  82413. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  82414. ** invokes the collation factory if the named collation cannot be found
  82415. ** and generates an error message.
  82416. **
  82417. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  82418. */
  82419. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  82420. sqlite3 *db = pParse->db;
  82421. u8 enc = ENC(db);
  82422. u8 initbusy = db->init.busy;
  82423. CollSeq *pColl;
  82424. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  82425. if( !initbusy && (!pColl || !pColl->xCmp) ){
  82426. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  82427. }
  82428. return pColl;
  82429. }
  82430. /*
  82431. ** Generate code that will increment the schema cookie.
  82432. **
  82433. ** The schema cookie is used to determine when the schema for the
  82434. ** database changes. After each schema change, the cookie value
  82435. ** changes. When a process first reads the schema it records the
  82436. ** cookie. Thereafter, whenever it goes to access the database,
  82437. ** it checks the cookie to make sure the schema has not changed
  82438. ** since it was last read.
  82439. **
  82440. ** This plan is not completely bullet-proof. It is possible for
  82441. ** the schema to change multiple times and for the cookie to be
  82442. ** set back to prior value. But schema changes are infrequent
  82443. ** and the probability of hitting the same cookie value is only
  82444. ** 1 chance in 2^32. So we're safe enough.
  82445. */
  82446. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  82447. int r1 = sqlite3GetTempReg(pParse);
  82448. sqlite3 *db = pParse->db;
  82449. Vdbe *v = pParse->pVdbe;
  82450. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82451. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  82452. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  82453. sqlite3ReleaseTempReg(pParse, r1);
  82454. }
  82455. /*
  82456. ** Measure the number of characters needed to output the given
  82457. ** identifier. The number returned includes any quotes used
  82458. ** but does not include the null terminator.
  82459. **
  82460. ** The estimate is conservative. It might be larger that what is
  82461. ** really needed.
  82462. */
  82463. static int identLength(const char *z){
  82464. int n;
  82465. for(n=0; *z; n++, z++){
  82466. if( *z=='"' ){ n++; }
  82467. }
  82468. return n + 2;
  82469. }
  82470. /*
  82471. ** The first parameter is a pointer to an output buffer. The second
  82472. ** parameter is a pointer to an integer that contains the offset at
  82473. ** which to write into the output buffer. This function copies the
  82474. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  82475. ** to the specified offset in the buffer and updates *pIdx to refer
  82476. ** to the first byte after the last byte written before returning.
  82477. **
  82478. ** If the string zSignedIdent consists entirely of alpha-numeric
  82479. ** characters, does not begin with a digit and is not an SQL keyword,
  82480. ** then it is copied to the output buffer exactly as it is. Otherwise,
  82481. ** it is quoted using double-quotes.
  82482. */
  82483. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  82484. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  82485. int i, j, needQuote;
  82486. i = *pIdx;
  82487. for(j=0; zIdent[j]; j++){
  82488. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  82489. }
  82490. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  82491. if( !needQuote ){
  82492. needQuote = zIdent[j];
  82493. }
  82494. if( needQuote ) z[i++] = '"';
  82495. for(j=0; zIdent[j]; j++){
  82496. z[i++] = zIdent[j];
  82497. if( zIdent[j]=='"' ) z[i++] = '"';
  82498. }
  82499. if( needQuote ) z[i++] = '"';
  82500. z[i] = 0;
  82501. *pIdx = i;
  82502. }
  82503. /*
  82504. ** Generate a CREATE TABLE statement appropriate for the given
  82505. ** table. Memory to hold the text of the statement is obtained
  82506. ** from sqliteMalloc() and must be freed by the calling function.
  82507. */
  82508. static char *createTableStmt(sqlite3 *db, Table *p){
  82509. int i, k, n;
  82510. char *zStmt;
  82511. char *zSep, *zSep2, *zEnd;
  82512. Column *pCol;
  82513. n = 0;
  82514. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  82515. n += identLength(pCol->zName) + 5;
  82516. }
  82517. n += identLength(p->zName);
  82518. if( n<50 ){
  82519. zSep = "";
  82520. zSep2 = ",";
  82521. zEnd = ")";
  82522. }else{
  82523. zSep = "\n ";
  82524. zSep2 = ",\n ";
  82525. zEnd = "\n)";
  82526. }
  82527. n += 35 + 6*p->nCol;
  82528. zStmt = sqlite3DbMallocRaw(0, n);
  82529. if( zStmt==0 ){
  82530. db->mallocFailed = 1;
  82531. return 0;
  82532. }
  82533. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  82534. k = sqlite3Strlen30(zStmt);
  82535. identPut(zStmt, &k, p->zName);
  82536. zStmt[k++] = '(';
  82537. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  82538. static const char * const azType[] = {
  82539. /* SQLITE_AFF_TEXT */ " TEXT",
  82540. /* SQLITE_AFF_NONE */ "",
  82541. /* SQLITE_AFF_NUMERIC */ " NUM",
  82542. /* SQLITE_AFF_INTEGER */ " INT",
  82543. /* SQLITE_AFF_REAL */ " REAL"
  82544. };
  82545. int len;
  82546. const char *zType;
  82547. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  82548. k += sqlite3Strlen30(&zStmt[k]);
  82549. zSep = zSep2;
  82550. identPut(zStmt, &k, pCol->zName);
  82551. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  82552. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  82553. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  82554. testcase( pCol->affinity==SQLITE_AFF_NONE );
  82555. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  82556. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  82557. testcase( pCol->affinity==SQLITE_AFF_REAL );
  82558. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  82559. len = sqlite3Strlen30(zType);
  82560. assert( pCol->affinity==SQLITE_AFF_NONE
  82561. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  82562. memcpy(&zStmt[k], zType, len);
  82563. k += len;
  82564. assert( k<=n );
  82565. }
  82566. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  82567. return zStmt;
  82568. }
  82569. /*
  82570. ** Estimate the total row width for a table.
  82571. */
  82572. static void estimateTableWidth(Table *pTab){
  82573. unsigned wTable = 0;
  82574. const Column *pTabCol;
  82575. int i;
  82576. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  82577. wTable += pTabCol->szEst;
  82578. }
  82579. if( pTab->iPKey<0 ) wTable++;
  82580. pTab->szTabRow = sqlite3LogEst(wTable*4);
  82581. }
  82582. /*
  82583. ** Estimate the average size of a row for an index.
  82584. */
  82585. static void estimateIndexWidth(Index *pIdx){
  82586. unsigned wIndex = 1;
  82587. int i;
  82588. const Column *aCol = pIdx->pTable->aCol;
  82589. for(i=0; i<pIdx->nColumn; i++){
  82590. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  82591. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  82592. }
  82593. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  82594. }
  82595. /*
  82596. ** This routine is called to report the final ")" that terminates
  82597. ** a CREATE TABLE statement.
  82598. **
  82599. ** The table structure that other action routines have been building
  82600. ** is added to the internal hash tables, assuming no errors have
  82601. ** occurred.
  82602. **
  82603. ** An entry for the table is made in the master table on disk, unless
  82604. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  82605. ** it means we are reading the sqlite_master table because we just
  82606. ** connected to the database or because the sqlite_master table has
  82607. ** recently changed, so the entry for this table already exists in
  82608. ** the sqlite_master table. We do not want to create it again.
  82609. **
  82610. ** If the pSelect argument is not NULL, it means that this routine
  82611. ** was called to create a table generated from a
  82612. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  82613. ** the new table will match the result set of the SELECT.
  82614. */
  82615. SQLITE_PRIVATE void sqlite3EndTable(
  82616. Parse *pParse, /* Parse context */
  82617. Token *pCons, /* The ',' token after the last column defn. */
  82618. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  82619. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  82620. ){
  82621. Table *p; /* The new table */
  82622. sqlite3 *db = pParse->db; /* The database connection */
  82623. int iDb; /* Database in which the table lives */
  82624. Index *pIdx; /* An implied index of the table */
  82625. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  82626. return;
  82627. }
  82628. p = pParse->pNewTable;
  82629. if( p==0 ) return;
  82630. assert( !db->init.busy || !pSelect );
  82631. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  82632. #ifndef SQLITE_OMIT_CHECK
  82633. /* Resolve names in all CHECK constraint expressions.
  82634. */
  82635. if( p->pCheck ){
  82636. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  82637. }
  82638. #endif /* !defined(SQLITE_OMIT_CHECK) */
  82639. /* Estimate the average row size for the table and for all implied indices */
  82640. estimateTableWidth(p);
  82641. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  82642. estimateIndexWidth(pIdx);
  82643. }
  82644. /* If the db->init.busy is 1 it means we are reading the SQL off the
  82645. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  82646. ** So do not write to the disk again. Extract the root page number
  82647. ** for the table from the db->init.newTnum field. (The page number
  82648. ** should have been put there by the sqliteOpenCb routine.)
  82649. */
  82650. if( db->init.busy ){
  82651. p->tnum = db->init.newTnum;
  82652. }
  82653. /* If not initializing, then create a record for the new table
  82654. ** in the SQLITE_MASTER table of the database.
  82655. **
  82656. ** If this is a TEMPORARY table, write the entry into the auxiliary
  82657. ** file instead of into the main database file.
  82658. */
  82659. if( !db->init.busy ){
  82660. int n;
  82661. Vdbe *v;
  82662. char *zType; /* "view" or "table" */
  82663. char *zType2; /* "VIEW" or "TABLE" */
  82664. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  82665. v = sqlite3GetVdbe(pParse);
  82666. if( NEVER(v==0) ) return;
  82667. sqlite3VdbeAddOp1(v, OP_Close, 0);
  82668. /*
  82669. ** Initialize zType for the new view or table.
  82670. */
  82671. if( p->pSelect==0 ){
  82672. /* A regular table */
  82673. zType = "table";
  82674. zType2 = "TABLE";
  82675. #ifndef SQLITE_OMIT_VIEW
  82676. }else{
  82677. /* A view */
  82678. zType = "view";
  82679. zType2 = "VIEW";
  82680. #endif
  82681. }
  82682. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  82683. ** statement to populate the new table. The root-page number for the
  82684. ** new table is in register pParse->regRoot.
  82685. **
  82686. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  82687. ** suitable state to query for the column names and types to be used
  82688. ** by the new table.
  82689. **
  82690. ** A shared-cache write-lock is not required to write to the new table,
  82691. ** as a schema-lock must have already been obtained to create it. Since
  82692. ** a schema-lock excludes all other database users, the write-lock would
  82693. ** be redundant.
  82694. */
  82695. if( pSelect ){
  82696. SelectDest dest;
  82697. Table *pSelTab;
  82698. assert(pParse->nTab==1);
  82699. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  82700. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  82701. pParse->nTab = 2;
  82702. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  82703. sqlite3Select(pParse, pSelect, &dest);
  82704. sqlite3VdbeAddOp1(v, OP_Close, 1);
  82705. if( pParse->nErr==0 ){
  82706. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  82707. if( pSelTab==0 ) return;
  82708. assert( p->aCol==0 );
  82709. p->nCol = pSelTab->nCol;
  82710. p->aCol = pSelTab->aCol;
  82711. pSelTab->nCol = 0;
  82712. pSelTab->aCol = 0;
  82713. sqlite3DeleteTable(db, pSelTab);
  82714. }
  82715. }
  82716. /* Compute the complete text of the CREATE statement */
  82717. if( pSelect ){
  82718. zStmt = createTableStmt(db, p);
  82719. }else{
  82720. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  82721. zStmt = sqlite3MPrintf(db,
  82722. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  82723. );
  82724. }
  82725. /* A slot for the record has already been allocated in the
  82726. ** SQLITE_MASTER table. We just need to update that slot with all
  82727. ** the information we've collected.
  82728. */
  82729. sqlite3NestedParse(pParse,
  82730. "UPDATE %Q.%s "
  82731. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  82732. "WHERE rowid=#%d",
  82733. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  82734. zType,
  82735. p->zName,
  82736. p->zName,
  82737. pParse->regRoot,
  82738. zStmt,
  82739. pParse->regRowid
  82740. );
  82741. sqlite3DbFree(db, zStmt);
  82742. sqlite3ChangeCookie(pParse, iDb);
  82743. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82744. /* Check to see if we need to create an sqlite_sequence table for
  82745. ** keeping track of autoincrement keys.
  82746. */
  82747. if( p->tabFlags & TF_Autoincrement ){
  82748. Db *pDb = &db->aDb[iDb];
  82749. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82750. if( pDb->pSchema->pSeqTab==0 ){
  82751. sqlite3NestedParse(pParse,
  82752. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  82753. pDb->zName
  82754. );
  82755. }
  82756. }
  82757. #endif
  82758. /* Reparse everything to update our internal data structures */
  82759. sqlite3VdbeAddParseSchemaOp(v, iDb,
  82760. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  82761. }
  82762. /* Add the table to the in-memory representation of the database.
  82763. */
  82764. if( db->init.busy ){
  82765. Table *pOld;
  82766. Schema *pSchema = p->pSchema;
  82767. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82768. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  82769. sqlite3Strlen30(p->zName),p);
  82770. if( pOld ){
  82771. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  82772. db->mallocFailed = 1;
  82773. return;
  82774. }
  82775. pParse->pNewTable = 0;
  82776. db->flags |= SQLITE_InternChanges;
  82777. #ifndef SQLITE_OMIT_ALTERTABLE
  82778. if( !p->pSelect ){
  82779. const char *zName = (const char *)pParse->sNameToken.z;
  82780. int nName;
  82781. assert( !pSelect && pCons && pEnd );
  82782. if( pCons->z==0 ){
  82783. pCons = pEnd;
  82784. }
  82785. nName = (int)((const char *)pCons->z - zName);
  82786. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  82787. }
  82788. #endif
  82789. }
  82790. }
  82791. #ifndef SQLITE_OMIT_VIEW
  82792. /*
  82793. ** The parser calls this routine in order to create a new VIEW
  82794. */
  82795. SQLITE_PRIVATE void sqlite3CreateView(
  82796. Parse *pParse, /* The parsing context */
  82797. Token *pBegin, /* The CREATE token that begins the statement */
  82798. Token *pName1, /* The token that holds the name of the view */
  82799. Token *pName2, /* The token that holds the name of the view */
  82800. Select *pSelect, /* A SELECT statement that will become the new view */
  82801. int isTemp, /* TRUE for a TEMPORARY view */
  82802. int noErr /* Suppress error messages if VIEW already exists */
  82803. ){
  82804. Table *p;
  82805. int n;
  82806. const char *z;
  82807. Token sEnd;
  82808. DbFixer sFix;
  82809. Token *pName = 0;
  82810. int iDb;
  82811. sqlite3 *db = pParse->db;
  82812. if( pParse->nVar>0 ){
  82813. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  82814. sqlite3SelectDelete(db, pSelect);
  82815. return;
  82816. }
  82817. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  82818. p = pParse->pNewTable;
  82819. if( p==0 || pParse->nErr ){
  82820. sqlite3SelectDelete(db, pSelect);
  82821. return;
  82822. }
  82823. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  82824. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  82825. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  82826. if( sqlite3FixSelect(&sFix, pSelect) ){
  82827. sqlite3SelectDelete(db, pSelect);
  82828. return;
  82829. }
  82830. /* Make a copy of the entire SELECT statement that defines the view.
  82831. ** This will force all the Expr.token.z values to be dynamically
  82832. ** allocated rather than point to the input string - which means that
  82833. ** they will persist after the current sqlite3_exec() call returns.
  82834. */
  82835. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  82836. sqlite3SelectDelete(db, pSelect);
  82837. if( db->mallocFailed ){
  82838. return;
  82839. }
  82840. if( !db->init.busy ){
  82841. sqlite3ViewGetColumnNames(pParse, p);
  82842. }
  82843. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  82844. ** the end.
  82845. */
  82846. sEnd = pParse->sLastToken;
  82847. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  82848. sEnd.z += sEnd.n;
  82849. }
  82850. sEnd.n = 0;
  82851. n = (int)(sEnd.z - pBegin->z);
  82852. z = pBegin->z;
  82853. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  82854. sEnd.z = &z[n-1];
  82855. sEnd.n = 1;
  82856. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  82857. sqlite3EndTable(pParse, 0, &sEnd, 0);
  82858. return;
  82859. }
  82860. #endif /* SQLITE_OMIT_VIEW */
  82861. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  82862. /*
  82863. ** The Table structure pTable is really a VIEW. Fill in the names of
  82864. ** the columns of the view in the pTable structure. Return the number
  82865. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  82866. */
  82867. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  82868. Table *pSelTab; /* A fake table from which we get the result set */
  82869. Select *pSel; /* Copy of the SELECT that implements the view */
  82870. int nErr = 0; /* Number of errors encountered */
  82871. int n; /* Temporarily holds the number of cursors assigned */
  82872. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  82873. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  82874. assert( pTable );
  82875. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82876. if( sqlite3VtabCallConnect(pParse, pTable) ){
  82877. return SQLITE_ERROR;
  82878. }
  82879. if( IsVirtual(pTable) ) return 0;
  82880. #endif
  82881. #ifndef SQLITE_OMIT_VIEW
  82882. /* A positive nCol means the columns names for this view are
  82883. ** already known.
  82884. */
  82885. if( pTable->nCol>0 ) return 0;
  82886. /* A negative nCol is a special marker meaning that we are currently
  82887. ** trying to compute the column names. If we enter this routine with
  82888. ** a negative nCol, it means two or more views form a loop, like this:
  82889. **
  82890. ** CREATE VIEW one AS SELECT * FROM two;
  82891. ** CREATE VIEW two AS SELECT * FROM one;
  82892. **
  82893. ** Actually, the error above is now caught prior to reaching this point.
  82894. ** But the following test is still important as it does come up
  82895. ** in the following:
  82896. **
  82897. ** CREATE TABLE main.ex1(a);
  82898. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  82899. ** SELECT * FROM temp.ex1;
  82900. */
  82901. if( pTable->nCol<0 ){
  82902. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  82903. return 1;
  82904. }
  82905. assert( pTable->nCol>=0 );
  82906. /* If we get this far, it means we need to compute the table names.
  82907. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  82908. ** "*" elements in the results set of the view and will assign cursors
  82909. ** to the elements of the FROM clause. But we do not want these changes
  82910. ** to be permanent. So the computation is done on a copy of the SELECT
  82911. ** statement that defines the view.
  82912. */
  82913. assert( pTable->pSelect );
  82914. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  82915. if( pSel ){
  82916. u8 enableLookaside = db->lookaside.bEnabled;
  82917. n = pParse->nTab;
  82918. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  82919. pTable->nCol = -1;
  82920. db->lookaside.bEnabled = 0;
  82921. #ifndef SQLITE_OMIT_AUTHORIZATION
  82922. xAuth = db->xAuth;
  82923. db->xAuth = 0;
  82924. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  82925. db->xAuth = xAuth;
  82926. #else
  82927. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  82928. #endif
  82929. db->lookaside.bEnabled = enableLookaside;
  82930. pParse->nTab = n;
  82931. if( pSelTab ){
  82932. assert( pTable->aCol==0 );
  82933. pTable->nCol = pSelTab->nCol;
  82934. pTable->aCol = pSelTab->aCol;
  82935. pSelTab->nCol = 0;
  82936. pSelTab->aCol = 0;
  82937. sqlite3DeleteTable(db, pSelTab);
  82938. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  82939. pTable->pSchema->flags |= DB_UnresetViews;
  82940. }else{
  82941. pTable->nCol = 0;
  82942. nErr++;
  82943. }
  82944. sqlite3SelectDelete(db, pSel);
  82945. } else {
  82946. nErr++;
  82947. }
  82948. #endif /* SQLITE_OMIT_VIEW */
  82949. return nErr;
  82950. }
  82951. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  82952. #ifndef SQLITE_OMIT_VIEW
  82953. /*
  82954. ** Clear the column names from every VIEW in database idx.
  82955. */
  82956. static void sqliteViewResetAll(sqlite3 *db, int idx){
  82957. HashElem *i;
  82958. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  82959. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  82960. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  82961. Table *pTab = sqliteHashData(i);
  82962. if( pTab->pSelect ){
  82963. sqliteDeleteColumnNames(db, pTab);
  82964. pTab->aCol = 0;
  82965. pTab->nCol = 0;
  82966. }
  82967. }
  82968. DbClearProperty(db, idx, DB_UnresetViews);
  82969. }
  82970. #else
  82971. # define sqliteViewResetAll(A,B)
  82972. #endif /* SQLITE_OMIT_VIEW */
  82973. /*
  82974. ** This function is called by the VDBE to adjust the internal schema
  82975. ** used by SQLite when the btree layer moves a table root page. The
  82976. ** root-page of a table or index in database iDb has changed from iFrom
  82977. ** to iTo.
  82978. **
  82979. ** Ticket #1728: The symbol table might still contain information
  82980. ** on tables and/or indices that are the process of being deleted.
  82981. ** If you are unlucky, one of those deleted indices or tables might
  82982. ** have the same rootpage number as the real table or index that is
  82983. ** being moved. So we cannot stop searching after the first match
  82984. ** because the first match might be for one of the deleted indices
  82985. ** or tables and not the table/index that is actually being moved.
  82986. ** We must continue looping until all tables and indices with
  82987. ** rootpage==iFrom have been converted to have a rootpage of iTo
  82988. ** in order to be certain that we got the right one.
  82989. */
  82990. #ifndef SQLITE_OMIT_AUTOVACUUM
  82991. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  82992. HashElem *pElem;
  82993. Hash *pHash;
  82994. Db *pDb;
  82995. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82996. pDb = &db->aDb[iDb];
  82997. pHash = &pDb->pSchema->tblHash;
  82998. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  82999. Table *pTab = sqliteHashData(pElem);
  83000. if( pTab->tnum==iFrom ){
  83001. pTab->tnum = iTo;
  83002. }
  83003. }
  83004. pHash = &pDb->pSchema->idxHash;
  83005. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  83006. Index *pIdx = sqliteHashData(pElem);
  83007. if( pIdx->tnum==iFrom ){
  83008. pIdx->tnum = iTo;
  83009. }
  83010. }
  83011. }
  83012. #endif
  83013. /*
  83014. ** Write code to erase the table with root-page iTable from database iDb.
  83015. ** Also write code to modify the sqlite_master table and internal schema
  83016. ** if a root-page of another table is moved by the btree-layer whilst
  83017. ** erasing iTable (this can happen with an auto-vacuum database).
  83018. */
  83019. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  83020. Vdbe *v = sqlite3GetVdbe(pParse);
  83021. int r1 = sqlite3GetTempReg(pParse);
  83022. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  83023. sqlite3MayAbort(pParse);
  83024. #ifndef SQLITE_OMIT_AUTOVACUUM
  83025. /* OP_Destroy stores an in integer r1. If this integer
  83026. ** is non-zero, then it is the root page number of a table moved to
  83027. ** location iTable. The following code modifies the sqlite_master table to
  83028. ** reflect this.
  83029. **
  83030. ** The "#NNN" in the SQL is a special constant that means whatever value
  83031. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  83032. ** token for additional information.
  83033. */
  83034. sqlite3NestedParse(pParse,
  83035. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  83036. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  83037. #endif
  83038. sqlite3ReleaseTempReg(pParse, r1);
  83039. }
  83040. /*
  83041. ** Write VDBE code to erase table pTab and all associated indices on disk.
  83042. ** Code to update the sqlite_master tables and internal schema definitions
  83043. ** in case a root-page belonging to another table is moved by the btree layer
  83044. ** is also added (this can happen with an auto-vacuum database).
  83045. */
  83046. static void destroyTable(Parse *pParse, Table *pTab){
  83047. #ifdef SQLITE_OMIT_AUTOVACUUM
  83048. Index *pIdx;
  83049. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83050. destroyRootPage(pParse, pTab->tnum, iDb);
  83051. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83052. destroyRootPage(pParse, pIdx->tnum, iDb);
  83053. }
  83054. #else
  83055. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  83056. ** is not defined), then it is important to call OP_Destroy on the
  83057. ** table and index root-pages in order, starting with the numerically
  83058. ** largest root-page number. This guarantees that none of the root-pages
  83059. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  83060. ** following were coded:
  83061. **
  83062. ** OP_Destroy 4 0
  83063. ** ...
  83064. ** OP_Destroy 5 0
  83065. **
  83066. ** and root page 5 happened to be the largest root-page number in the
  83067. ** database, then root page 5 would be moved to page 4 by the
  83068. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  83069. ** a free-list page.
  83070. */
  83071. int iTab = pTab->tnum;
  83072. int iDestroyed = 0;
  83073. while( 1 ){
  83074. Index *pIdx;
  83075. int iLargest = 0;
  83076. if( iDestroyed==0 || iTab<iDestroyed ){
  83077. iLargest = iTab;
  83078. }
  83079. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83080. int iIdx = pIdx->tnum;
  83081. assert( pIdx->pSchema==pTab->pSchema );
  83082. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  83083. iLargest = iIdx;
  83084. }
  83085. }
  83086. if( iLargest==0 ){
  83087. return;
  83088. }else{
  83089. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83090. assert( iDb>=0 && iDb<pParse->db->nDb );
  83091. destroyRootPage(pParse, iLargest, iDb);
  83092. iDestroyed = iLargest;
  83093. }
  83094. }
  83095. #endif
  83096. }
  83097. /*
  83098. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  83099. ** after a DROP INDEX or DROP TABLE command.
  83100. */
  83101. static void sqlite3ClearStatTables(
  83102. Parse *pParse, /* The parsing context */
  83103. int iDb, /* The database number */
  83104. const char *zType, /* "idx" or "tbl" */
  83105. const char *zName /* Name of index or table */
  83106. ){
  83107. int i;
  83108. const char *zDbName = pParse->db->aDb[iDb].zName;
  83109. for(i=1; i<=4; i++){
  83110. char zTab[24];
  83111. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  83112. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  83113. sqlite3NestedParse(pParse,
  83114. "DELETE FROM %Q.%s WHERE %s=%Q",
  83115. zDbName, zTab, zType, zName
  83116. );
  83117. }
  83118. }
  83119. }
  83120. /*
  83121. ** Generate code to drop a table.
  83122. */
  83123. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  83124. Vdbe *v;
  83125. sqlite3 *db = pParse->db;
  83126. Trigger *pTrigger;
  83127. Db *pDb = &db->aDb[iDb];
  83128. v = sqlite3GetVdbe(pParse);
  83129. assert( v!=0 );
  83130. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83131. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83132. if( IsVirtual(pTab) ){
  83133. sqlite3VdbeAddOp0(v, OP_VBegin);
  83134. }
  83135. #endif
  83136. /* Drop all triggers associated with the table being dropped. Code
  83137. ** is generated to remove entries from sqlite_master and/or
  83138. ** sqlite_temp_master if required.
  83139. */
  83140. pTrigger = sqlite3TriggerList(pParse, pTab);
  83141. while( pTrigger ){
  83142. assert( pTrigger->pSchema==pTab->pSchema ||
  83143. pTrigger->pSchema==db->aDb[1].pSchema );
  83144. sqlite3DropTriggerPtr(pParse, pTrigger);
  83145. pTrigger = pTrigger->pNext;
  83146. }
  83147. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83148. /* Remove any entries of the sqlite_sequence table associated with
  83149. ** the table being dropped. This is done before the table is dropped
  83150. ** at the btree level, in case the sqlite_sequence table needs to
  83151. ** move as a result of the drop (can happen in auto-vacuum mode).
  83152. */
  83153. if( pTab->tabFlags & TF_Autoincrement ){
  83154. sqlite3NestedParse(pParse,
  83155. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  83156. pDb->zName, pTab->zName
  83157. );
  83158. }
  83159. #endif
  83160. /* Drop all SQLITE_MASTER table and index entries that refer to the
  83161. ** table. The program name loops through the master table and deletes
  83162. ** every row that refers to a table of the same name as the one being
  83163. ** dropped. Triggers are handled separately because a trigger can be
  83164. ** created in the temp database that refers to a table in another
  83165. ** database.
  83166. */
  83167. sqlite3NestedParse(pParse,
  83168. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  83169. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  83170. if( !isView && !IsVirtual(pTab) ){
  83171. destroyTable(pParse, pTab);
  83172. }
  83173. /* Remove the table entry from SQLite's internal schema and modify
  83174. ** the schema cookie.
  83175. */
  83176. if( IsVirtual(pTab) ){
  83177. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  83178. }
  83179. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  83180. sqlite3ChangeCookie(pParse, iDb);
  83181. sqliteViewResetAll(db, iDb);
  83182. }
  83183. /*
  83184. ** This routine is called to do the work of a DROP TABLE statement.
  83185. ** pName is the name of the table to be dropped.
  83186. */
  83187. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  83188. Table *pTab;
  83189. Vdbe *v;
  83190. sqlite3 *db = pParse->db;
  83191. int iDb;
  83192. if( db->mallocFailed ){
  83193. goto exit_drop_table;
  83194. }
  83195. assert( pParse->nErr==0 );
  83196. assert( pName->nSrc==1 );
  83197. if( noErr ) db->suppressErr++;
  83198. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  83199. if( noErr ) db->suppressErr--;
  83200. if( pTab==0 ){
  83201. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  83202. goto exit_drop_table;
  83203. }
  83204. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83205. assert( iDb>=0 && iDb<db->nDb );
  83206. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  83207. ** it is initialized.
  83208. */
  83209. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  83210. goto exit_drop_table;
  83211. }
  83212. #ifndef SQLITE_OMIT_AUTHORIZATION
  83213. {
  83214. int code;
  83215. const char *zTab = SCHEMA_TABLE(iDb);
  83216. const char *zDb = db->aDb[iDb].zName;
  83217. const char *zArg2 = 0;
  83218. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  83219. goto exit_drop_table;
  83220. }
  83221. if( isView ){
  83222. if( !OMIT_TEMPDB && iDb==1 ){
  83223. code = SQLITE_DROP_TEMP_VIEW;
  83224. }else{
  83225. code = SQLITE_DROP_VIEW;
  83226. }
  83227. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83228. }else if( IsVirtual(pTab) ){
  83229. code = SQLITE_DROP_VTABLE;
  83230. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  83231. #endif
  83232. }else{
  83233. if( !OMIT_TEMPDB && iDb==1 ){
  83234. code = SQLITE_DROP_TEMP_TABLE;
  83235. }else{
  83236. code = SQLITE_DROP_TABLE;
  83237. }
  83238. }
  83239. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  83240. goto exit_drop_table;
  83241. }
  83242. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  83243. goto exit_drop_table;
  83244. }
  83245. }
  83246. #endif
  83247. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  83248. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  83249. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  83250. goto exit_drop_table;
  83251. }
  83252. #ifndef SQLITE_OMIT_VIEW
  83253. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  83254. ** on a table.
  83255. */
  83256. if( isView && pTab->pSelect==0 ){
  83257. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  83258. goto exit_drop_table;
  83259. }
  83260. if( !isView && pTab->pSelect ){
  83261. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  83262. goto exit_drop_table;
  83263. }
  83264. #endif
  83265. /* Generate code to remove the table from the master table
  83266. ** on disk.
  83267. */
  83268. v = sqlite3GetVdbe(pParse);
  83269. if( v ){
  83270. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83271. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  83272. sqlite3FkDropTable(pParse, pName, pTab);
  83273. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  83274. }
  83275. exit_drop_table:
  83276. sqlite3SrcListDelete(db, pName);
  83277. }
  83278. /*
  83279. ** This routine is called to create a new foreign key on the table
  83280. ** currently under construction. pFromCol determines which columns
  83281. ** in the current table point to the foreign key. If pFromCol==0 then
  83282. ** connect the key to the last column inserted. pTo is the name of
  83283. ** the table referred to. pToCol is a list of tables in the other
  83284. ** pTo table that the foreign key points to. flags contains all
  83285. ** information about the conflict resolution algorithms specified
  83286. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  83287. **
  83288. ** An FKey structure is created and added to the table currently
  83289. ** under construction in the pParse->pNewTable field.
  83290. **
  83291. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  83292. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  83293. */
  83294. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  83295. Parse *pParse, /* Parsing context */
  83296. ExprList *pFromCol, /* Columns in this table that point to other table */
  83297. Token *pTo, /* Name of the other table */
  83298. ExprList *pToCol, /* Columns in the other table */
  83299. int flags /* Conflict resolution algorithms. */
  83300. ){
  83301. sqlite3 *db = pParse->db;
  83302. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83303. FKey *pFKey = 0;
  83304. FKey *pNextTo;
  83305. Table *p = pParse->pNewTable;
  83306. int nByte;
  83307. int i;
  83308. int nCol;
  83309. char *z;
  83310. assert( pTo!=0 );
  83311. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  83312. if( pFromCol==0 ){
  83313. int iCol = p->nCol-1;
  83314. if( NEVER(iCol<0) ) goto fk_end;
  83315. if( pToCol && pToCol->nExpr!=1 ){
  83316. sqlite3ErrorMsg(pParse, "foreign key on %s"
  83317. " should reference only one column of table %T",
  83318. p->aCol[iCol].zName, pTo);
  83319. goto fk_end;
  83320. }
  83321. nCol = 1;
  83322. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  83323. sqlite3ErrorMsg(pParse,
  83324. "number of columns in foreign key does not match the number of "
  83325. "columns in the referenced table");
  83326. goto fk_end;
  83327. }else{
  83328. nCol = pFromCol->nExpr;
  83329. }
  83330. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  83331. if( pToCol ){
  83332. for(i=0; i<pToCol->nExpr; i++){
  83333. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  83334. }
  83335. }
  83336. pFKey = sqlite3DbMallocZero(db, nByte );
  83337. if( pFKey==0 ){
  83338. goto fk_end;
  83339. }
  83340. pFKey->pFrom = p;
  83341. pFKey->pNextFrom = p->pFKey;
  83342. z = (char*)&pFKey->aCol[nCol];
  83343. pFKey->zTo = z;
  83344. memcpy(z, pTo->z, pTo->n);
  83345. z[pTo->n] = 0;
  83346. sqlite3Dequote(z);
  83347. z += pTo->n+1;
  83348. pFKey->nCol = nCol;
  83349. if( pFromCol==0 ){
  83350. pFKey->aCol[0].iFrom = p->nCol-1;
  83351. }else{
  83352. for(i=0; i<nCol; i++){
  83353. int j;
  83354. for(j=0; j<p->nCol; j++){
  83355. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  83356. pFKey->aCol[i].iFrom = j;
  83357. break;
  83358. }
  83359. }
  83360. if( j>=p->nCol ){
  83361. sqlite3ErrorMsg(pParse,
  83362. "unknown column \"%s\" in foreign key definition",
  83363. pFromCol->a[i].zName);
  83364. goto fk_end;
  83365. }
  83366. }
  83367. }
  83368. if( pToCol ){
  83369. for(i=0; i<nCol; i++){
  83370. int n = sqlite3Strlen30(pToCol->a[i].zName);
  83371. pFKey->aCol[i].zCol = z;
  83372. memcpy(z, pToCol->a[i].zName, n);
  83373. z[n] = 0;
  83374. z += n+1;
  83375. }
  83376. }
  83377. pFKey->isDeferred = 0;
  83378. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  83379. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  83380. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  83381. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  83382. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  83383. );
  83384. if( pNextTo==pFKey ){
  83385. db->mallocFailed = 1;
  83386. goto fk_end;
  83387. }
  83388. if( pNextTo ){
  83389. assert( pNextTo->pPrevTo==0 );
  83390. pFKey->pNextTo = pNextTo;
  83391. pNextTo->pPrevTo = pFKey;
  83392. }
  83393. /* Link the foreign key to the table as the last step.
  83394. */
  83395. p->pFKey = pFKey;
  83396. pFKey = 0;
  83397. fk_end:
  83398. sqlite3DbFree(db, pFKey);
  83399. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  83400. sqlite3ExprListDelete(db, pFromCol);
  83401. sqlite3ExprListDelete(db, pToCol);
  83402. }
  83403. /*
  83404. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  83405. ** clause is seen as part of a foreign key definition. The isDeferred
  83406. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  83407. ** The behavior of the most recently created foreign key is adjusted
  83408. ** accordingly.
  83409. */
  83410. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  83411. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83412. Table *pTab;
  83413. FKey *pFKey;
  83414. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  83415. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  83416. pFKey->isDeferred = (u8)isDeferred;
  83417. #endif
  83418. }
  83419. /*
  83420. ** Generate code that will erase and refill index *pIdx. This is
  83421. ** used to initialize a newly created index or to recompute the
  83422. ** content of an index in response to a REINDEX command.
  83423. **
  83424. ** if memRootPage is not negative, it means that the index is newly
  83425. ** created. The register specified by memRootPage contains the
  83426. ** root page number of the index. If memRootPage is negative, then
  83427. ** the index already exists and must be cleared before being refilled and
  83428. ** the root page number of the index is taken from pIndex->tnum.
  83429. */
  83430. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  83431. Table *pTab = pIndex->pTable; /* The table that is indexed */
  83432. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  83433. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  83434. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  83435. int addr1; /* Address of top of loop */
  83436. int addr2; /* Address to jump to for next iteration */
  83437. int tnum; /* Root page of index */
  83438. int iPartIdxLabel; /* Jump to this label to skip a row */
  83439. Vdbe *v; /* Generate code into this virtual machine */
  83440. KeyInfo *pKey; /* KeyInfo for index */
  83441. int regRecord; /* Register holding assemblied index record */
  83442. sqlite3 *db = pParse->db; /* The database connection */
  83443. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  83444. #ifndef SQLITE_OMIT_AUTHORIZATION
  83445. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  83446. db->aDb[iDb].zName ) ){
  83447. return;
  83448. }
  83449. #endif
  83450. /* Require a write-lock on the table to perform this operation */
  83451. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  83452. v = sqlite3GetVdbe(pParse);
  83453. if( v==0 ) return;
  83454. if( memRootPage>=0 ){
  83455. tnum = memRootPage;
  83456. }else{
  83457. tnum = pIndex->tnum;
  83458. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  83459. }
  83460. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  83461. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  83462. (char *)pKey, P4_KEYINFO_HANDOFF);
  83463. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  83464. /* Open the sorter cursor if we are to use one. */
  83465. iSorter = pParse->nTab++;
  83466. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  83467. /* Open the table. Loop through all rows of the table, inserting index
  83468. ** records into the sorter. */
  83469. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  83470. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  83471. regRecord = sqlite3GetTempReg(pParse);
  83472. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  83473. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  83474. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  83475. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  83476. sqlite3VdbeJumpHere(v, addr1);
  83477. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  83478. if( pIndex->onError!=OE_None ){
  83479. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  83480. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  83481. addr2 = sqlite3VdbeCurrentAddr(v);
  83482. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  83483. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  83484. OE_Abort, "indexed columns are not unique", P4_STATIC
  83485. );
  83486. }else{
  83487. addr2 = sqlite3VdbeCurrentAddr(v);
  83488. }
  83489. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  83490. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  83491. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  83492. sqlite3ReleaseTempReg(pParse, regRecord);
  83493. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  83494. sqlite3VdbeJumpHere(v, addr1);
  83495. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  83496. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  83497. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  83498. }
  83499. /*
  83500. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  83501. ** and pTblList is the name of the table that is to be indexed. Both will
  83502. ** be NULL for a primary key or an index that is created to satisfy a
  83503. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  83504. ** as the table to be indexed. pParse->pNewTable is a table that is
  83505. ** currently being constructed by a CREATE TABLE statement.
  83506. **
  83507. ** pList is a list of columns to be indexed. pList will be NULL if this
  83508. ** is a primary key or unique-constraint on the most recent column added
  83509. ** to the table currently under construction.
  83510. **
  83511. ** If the index is created successfully, return a pointer to the new Index
  83512. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  83513. ** as the tables primary key (Index.autoIndex==2).
  83514. */
  83515. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  83516. Parse *pParse, /* All information about this parse */
  83517. Token *pName1, /* First part of index name. May be NULL */
  83518. Token *pName2, /* Second part of index name. May be NULL */
  83519. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  83520. ExprList *pList, /* A list of columns to be indexed */
  83521. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  83522. Token *pStart, /* The CREATE token that begins this statement */
  83523. Expr *pPIWhere, /* WHERE clause for partial indices */
  83524. int sortOrder, /* Sort order of primary key when pList==NULL */
  83525. int ifNotExist /* Omit error if index already exists */
  83526. ){
  83527. Index *pRet = 0; /* Pointer to return */
  83528. Table *pTab = 0; /* Table to be indexed */
  83529. Index *pIndex = 0; /* The index to be created */
  83530. char *zName = 0; /* Name of the index */
  83531. int nName; /* Number of characters in zName */
  83532. int i, j;
  83533. Token nullId; /* Fake token for an empty ID list */
  83534. DbFixer sFix; /* For assigning database names to pTable */
  83535. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  83536. sqlite3 *db = pParse->db;
  83537. Db *pDb; /* The specific table containing the indexed database */
  83538. int iDb; /* Index of the database that is being written */
  83539. Token *pName = 0; /* Unqualified name of the index to create */
  83540. struct ExprList_item *pListItem; /* For looping over pList */
  83541. const Column *pTabCol; /* A column in the table */
  83542. int nCol; /* Number of columns */
  83543. int nExtra = 0; /* Space allocated for zExtra[] */
  83544. char *zExtra; /* Extra space after the Index object */
  83545. assert( pParse->nErr==0 ); /* Never called with prior errors */
  83546. if( db->mallocFailed || IN_DECLARE_VTAB ){
  83547. goto exit_create_index;
  83548. }
  83549. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83550. goto exit_create_index;
  83551. }
  83552. /*
  83553. ** Find the table that is to be indexed. Return early if not found.
  83554. */
  83555. if( pTblName!=0 ){
  83556. /* Use the two-part index name to determine the database
  83557. ** to search for the table. 'Fix' the table name to this db
  83558. ** before looking up the table.
  83559. */
  83560. assert( pName1 && pName2 );
  83561. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  83562. if( iDb<0 ) goto exit_create_index;
  83563. assert( pName && pName->z );
  83564. #ifndef SQLITE_OMIT_TEMPDB
  83565. /* If the index name was unqualified, check if the table
  83566. ** is a temp table. If so, set the database to 1. Do not do this
  83567. ** if initialising a database schema.
  83568. */
  83569. if( !db->init.busy ){
  83570. pTab = sqlite3SrcListLookup(pParse, pTblName);
  83571. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  83572. iDb = 1;
  83573. }
  83574. }
  83575. #endif
  83576. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  83577. if( sqlite3FixSrcList(&sFix, pTblName) ){
  83578. /* Because the parser constructs pTblName from a single identifier,
  83579. ** sqlite3FixSrcList can never fail. */
  83580. assert(0);
  83581. }
  83582. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  83583. assert( db->mallocFailed==0 || pTab==0 );
  83584. if( pTab==0 ) goto exit_create_index;
  83585. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  83586. sqlite3ErrorMsg(pParse,
  83587. "cannot create a TEMP index on non-TEMP table \"%s\"",
  83588. pTab->zName);
  83589. goto exit_create_index;
  83590. }
  83591. }else{
  83592. assert( pName==0 );
  83593. assert( pStart==0 );
  83594. pTab = pParse->pNewTable;
  83595. if( !pTab ) goto exit_create_index;
  83596. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83597. }
  83598. pDb = &db->aDb[iDb];
  83599. assert( pTab!=0 );
  83600. assert( pParse->nErr==0 );
  83601. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  83602. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  83603. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  83604. goto exit_create_index;
  83605. }
  83606. #ifndef SQLITE_OMIT_VIEW
  83607. if( pTab->pSelect ){
  83608. sqlite3ErrorMsg(pParse, "views may not be indexed");
  83609. goto exit_create_index;
  83610. }
  83611. #endif
  83612. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83613. if( IsVirtual(pTab) ){
  83614. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  83615. goto exit_create_index;
  83616. }
  83617. #endif
  83618. /*
  83619. ** Find the name of the index. Make sure there is not already another
  83620. ** index or table with the same name.
  83621. **
  83622. ** Exception: If we are reading the names of permanent indices from the
  83623. ** sqlite_master table (because some other process changed the schema) and
  83624. ** one of the index names collides with the name of a temporary table or
  83625. ** index, then we will continue to process this index.
  83626. **
  83627. ** If pName==0 it means that we are
  83628. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  83629. ** own name.
  83630. */
  83631. if( pName ){
  83632. zName = sqlite3NameFromToken(db, pName);
  83633. if( zName==0 ) goto exit_create_index;
  83634. assert( pName->z!=0 );
  83635. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  83636. goto exit_create_index;
  83637. }
  83638. if( !db->init.busy ){
  83639. if( sqlite3FindTable(db, zName, 0)!=0 ){
  83640. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  83641. goto exit_create_index;
  83642. }
  83643. }
  83644. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  83645. if( !ifNotExist ){
  83646. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  83647. }else{
  83648. assert( !db->init.busy );
  83649. sqlite3CodeVerifySchema(pParse, iDb);
  83650. }
  83651. goto exit_create_index;
  83652. }
  83653. }else{
  83654. int n;
  83655. Index *pLoop;
  83656. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  83657. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  83658. if( zName==0 ){
  83659. goto exit_create_index;
  83660. }
  83661. }
  83662. /* Check for authorization to create an index.
  83663. */
  83664. #ifndef SQLITE_OMIT_AUTHORIZATION
  83665. {
  83666. const char *zDb = pDb->zName;
  83667. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  83668. goto exit_create_index;
  83669. }
  83670. i = SQLITE_CREATE_INDEX;
  83671. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  83672. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  83673. goto exit_create_index;
  83674. }
  83675. }
  83676. #endif
  83677. /* If pList==0, it means this routine was called to make a primary
  83678. ** key out of the last column added to the table under construction.
  83679. ** So create a fake list to simulate this.
  83680. */
  83681. if( pList==0 ){
  83682. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  83683. nullId.n = sqlite3Strlen30((char*)nullId.z);
  83684. pList = sqlite3ExprListAppend(pParse, 0, 0);
  83685. if( pList==0 ) goto exit_create_index;
  83686. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  83687. pList->a[0].sortOrder = (u8)sortOrder;
  83688. }
  83689. /* Figure out how many bytes of space are required to store explicitly
  83690. ** specified collation sequence names.
  83691. */
  83692. for(i=0; i<pList->nExpr; i++){
  83693. Expr *pExpr = pList->a[i].pExpr;
  83694. if( pExpr ){
  83695. assert( pExpr->op==TK_COLLATE );
  83696. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  83697. }
  83698. }
  83699. /*
  83700. ** Allocate the index structure.
  83701. */
  83702. nName = sqlite3Strlen30(zName);
  83703. nCol = pList->nExpr;
  83704. pIndex = sqlite3DbMallocZero(db,
  83705. ROUND8(sizeof(Index)) + /* Index structure */
  83706. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  83707. sizeof(char *)*nCol + /* Index.azColl */
  83708. sizeof(int)*nCol + /* Index.aiColumn */
  83709. sizeof(u8)*nCol + /* Index.aSortOrder */
  83710. nName + 1 + /* Index.zName */
  83711. nExtra /* Collation sequence names */
  83712. );
  83713. if( db->mallocFailed ){
  83714. goto exit_create_index;
  83715. }
  83716. zExtra = (char*)pIndex;
  83717. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  83718. pIndex->azColl = (char**)
  83719. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  83720. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  83721. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  83722. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  83723. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  83724. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  83725. zExtra = (char *)(&pIndex->zName[nName+1]);
  83726. memcpy(pIndex->zName, zName, nName+1);
  83727. pIndex->pTable = pTab;
  83728. pIndex->nColumn = pList->nExpr;
  83729. pIndex->onError = (u8)onError;
  83730. pIndex->uniqNotNull = onError==OE_Abort;
  83731. pIndex->autoIndex = (u8)(pName==0);
  83732. pIndex->pSchema = db->aDb[iDb].pSchema;
  83733. if( pPIWhere ){
  83734. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  83735. pIndex->pPartIdxWhere = pPIWhere;
  83736. pPIWhere = 0;
  83737. }
  83738. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83739. /* Check to see if we should honor DESC requests on index columns
  83740. */
  83741. if( pDb->pSchema->file_format>=4 ){
  83742. sortOrderMask = -1; /* Honor DESC */
  83743. }else{
  83744. sortOrderMask = 0; /* Ignore DESC */
  83745. }
  83746. /* Scan the names of the columns of the table to be indexed and
  83747. ** load the column indices into the Index structure. Report an error
  83748. ** if any column is not found.
  83749. **
  83750. ** TODO: Add a test to make sure that the same column is not named
  83751. ** more than once within the same index. Only the first instance of
  83752. ** the column will ever be used by the optimizer. Note that using the
  83753. ** same column more than once cannot be an error because that would
  83754. ** break backwards compatibility - it needs to be a warning.
  83755. */
  83756. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  83757. const char *zColName = pListItem->zName;
  83758. int requestedSortOrder;
  83759. char *zColl; /* Collation sequence name */
  83760. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  83761. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  83762. }
  83763. if( j>=pTab->nCol ){
  83764. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  83765. pTab->zName, zColName);
  83766. pParse->checkSchema = 1;
  83767. goto exit_create_index;
  83768. }
  83769. pIndex->aiColumn[i] = j;
  83770. if( pListItem->pExpr ){
  83771. int nColl;
  83772. assert( pListItem->pExpr->op==TK_COLLATE );
  83773. zColl = pListItem->pExpr->u.zToken;
  83774. nColl = sqlite3Strlen30(zColl) + 1;
  83775. assert( nExtra>=nColl );
  83776. memcpy(zExtra, zColl, nColl);
  83777. zColl = zExtra;
  83778. zExtra += nColl;
  83779. nExtra -= nColl;
  83780. }else{
  83781. zColl = pTab->aCol[j].zColl;
  83782. if( !zColl ) zColl = "BINARY";
  83783. }
  83784. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  83785. goto exit_create_index;
  83786. }
  83787. pIndex->azColl[i] = zColl;
  83788. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  83789. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  83790. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  83791. }
  83792. sqlite3DefaultRowEst(pIndex);
  83793. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  83794. if( pTab==pParse->pNewTable ){
  83795. /* This routine has been called to create an automatic index as a
  83796. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  83797. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  83798. ** i.e. one of:
  83799. **
  83800. ** CREATE TABLE t(x PRIMARY KEY, y);
  83801. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  83802. **
  83803. ** Either way, check to see if the table already has such an index. If
  83804. ** so, don't bother creating this one. This only applies to
  83805. ** automatically created indices. Users can do as they wish with
  83806. ** explicit indices.
  83807. **
  83808. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  83809. ** (and thus suppressing the second one) even if they have different
  83810. ** sort orders.
  83811. **
  83812. ** If there are different collating sequences or if the columns of
  83813. ** the constraint occur in different orders, then the constraints are
  83814. ** considered distinct and both result in separate indices.
  83815. */
  83816. Index *pIdx;
  83817. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83818. int k;
  83819. assert( pIdx->onError!=OE_None );
  83820. assert( pIdx->autoIndex );
  83821. assert( pIndex->onError!=OE_None );
  83822. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  83823. for(k=0; k<pIdx->nColumn; k++){
  83824. const char *z1;
  83825. const char *z2;
  83826. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  83827. z1 = pIdx->azColl[k];
  83828. z2 = pIndex->azColl[k];
  83829. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  83830. }
  83831. if( k==pIdx->nColumn ){
  83832. if( pIdx->onError!=pIndex->onError ){
  83833. /* This constraint creates the same index as a previous
  83834. ** constraint specified somewhere in the CREATE TABLE statement.
  83835. ** However the ON CONFLICT clauses are different. If both this
  83836. ** constraint and the previous equivalent constraint have explicit
  83837. ** ON CONFLICT clauses this is an error. Otherwise, use the
  83838. ** explicitly specified behavior for the index.
  83839. */
  83840. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  83841. sqlite3ErrorMsg(pParse,
  83842. "conflicting ON CONFLICT clauses specified", 0);
  83843. }
  83844. if( pIdx->onError==OE_Default ){
  83845. pIdx->onError = pIndex->onError;
  83846. }
  83847. }
  83848. goto exit_create_index;
  83849. }
  83850. }
  83851. }
  83852. /* Link the new Index structure to its table and to the other
  83853. ** in-memory database structures.
  83854. */
  83855. if( db->init.busy ){
  83856. Index *p;
  83857. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  83858. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  83859. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  83860. pIndex);
  83861. if( p ){
  83862. assert( p==pIndex ); /* Malloc must have failed */
  83863. db->mallocFailed = 1;
  83864. goto exit_create_index;
  83865. }
  83866. db->flags |= SQLITE_InternChanges;
  83867. if( pTblName!=0 ){
  83868. pIndex->tnum = db->init.newTnum;
  83869. }
  83870. }
  83871. /* If the db->init.busy is 0 then create the index on disk. This
  83872. ** involves writing the index into the master table and filling in the
  83873. ** index with the current table contents.
  83874. **
  83875. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  83876. ** command. db->init.busy is 1 when a database is opened and
  83877. ** CREATE INDEX statements are read out of the master table. In
  83878. ** the latter case the index already exists on disk, which is why
  83879. ** we don't want to recreate it.
  83880. **
  83881. ** If pTblName==0 it means this index is generated as a primary key
  83882. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  83883. ** has just been created, it contains no data and the index initialization
  83884. ** step can be skipped.
  83885. */
  83886. else if( pParse->nErr==0 ){
  83887. Vdbe *v;
  83888. char *zStmt;
  83889. int iMem = ++pParse->nMem;
  83890. v = sqlite3GetVdbe(pParse);
  83891. if( v==0 ) goto exit_create_index;
  83892. /* Create the rootpage for the index
  83893. */
  83894. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83895. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  83896. /* Gather the complete text of the CREATE INDEX statement into
  83897. ** the zStmt variable
  83898. */
  83899. if( pStart ){
  83900. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  83901. if( pName->z[n-1]==';' ) n--;
  83902. /* A named index with an explicit CREATE INDEX statement */
  83903. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  83904. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  83905. }else{
  83906. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  83907. /* zStmt = sqlite3MPrintf(""); */
  83908. zStmt = 0;
  83909. }
  83910. /* Add an entry in sqlite_master for this index
  83911. */
  83912. sqlite3NestedParse(pParse,
  83913. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  83914. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  83915. pIndex->zName,
  83916. pTab->zName,
  83917. iMem,
  83918. zStmt
  83919. );
  83920. sqlite3DbFree(db, zStmt);
  83921. /* Fill the index with data and reparse the schema. Code an OP_Expire
  83922. ** to invalidate all pre-compiled statements.
  83923. */
  83924. if( pTblName ){
  83925. sqlite3RefillIndex(pParse, pIndex, iMem);
  83926. sqlite3ChangeCookie(pParse, iDb);
  83927. sqlite3VdbeAddParseSchemaOp(v, iDb,
  83928. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  83929. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  83930. }
  83931. }
  83932. /* When adding an index to the list of indices for a table, make
  83933. ** sure all indices labeled OE_Replace come after all those labeled
  83934. ** OE_Ignore. This is necessary for the correct constraint check
  83935. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  83936. ** UPDATE and INSERT statements.
  83937. */
  83938. if( db->init.busy || pTblName==0 ){
  83939. if( onError!=OE_Replace || pTab->pIndex==0
  83940. || pTab->pIndex->onError==OE_Replace){
  83941. pIndex->pNext = pTab->pIndex;
  83942. pTab->pIndex = pIndex;
  83943. }else{
  83944. Index *pOther = pTab->pIndex;
  83945. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  83946. pOther = pOther->pNext;
  83947. }
  83948. pIndex->pNext = pOther->pNext;
  83949. pOther->pNext = pIndex;
  83950. }
  83951. pRet = pIndex;
  83952. pIndex = 0;
  83953. }
  83954. /* Clean up before exiting */
  83955. exit_create_index:
  83956. if( pIndex ) freeIndex(db, pIndex);
  83957. sqlite3ExprDelete(db, pPIWhere);
  83958. sqlite3ExprListDelete(db, pList);
  83959. sqlite3SrcListDelete(db, pTblName);
  83960. sqlite3DbFree(db, zName);
  83961. return pRet;
  83962. }
  83963. /*
  83964. ** Fill the Index.aiRowEst[] array with default information - information
  83965. ** to be used when we have not run the ANALYZE command.
  83966. **
  83967. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  83968. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  83969. ** number of rows in the table that match any particular value of the
  83970. ** first column of the index. aiRowEst[2] is an estimate of the number
  83971. ** of rows that match any particular combiniation of the first 2 columns
  83972. ** of the index. And so forth. It must always be the case that
  83973. *
  83974. ** aiRowEst[N]<=aiRowEst[N-1]
  83975. ** aiRowEst[N]>=1
  83976. **
  83977. ** Apart from that, we have little to go on besides intuition as to
  83978. ** how aiRowEst[] should be initialized. The numbers generated here
  83979. ** are based on typical values found in actual indices.
  83980. */
  83981. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  83982. tRowcnt *a = pIdx->aiRowEst;
  83983. int i;
  83984. tRowcnt n;
  83985. assert( a!=0 );
  83986. a[0] = pIdx->pTable->nRowEst;
  83987. if( a[0]<10 ) a[0] = 10;
  83988. n = 10;
  83989. for(i=1; i<=pIdx->nColumn; i++){
  83990. a[i] = n;
  83991. if( n>5 ) n--;
  83992. }
  83993. if( pIdx->onError!=OE_None ){
  83994. a[pIdx->nColumn] = 1;
  83995. }
  83996. }
  83997. /*
  83998. ** This routine will drop an existing named index. This routine
  83999. ** implements the DROP INDEX statement.
  84000. */
  84001. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  84002. Index *pIndex;
  84003. Vdbe *v;
  84004. sqlite3 *db = pParse->db;
  84005. int iDb;
  84006. assert( pParse->nErr==0 ); /* Never called with prior errors */
  84007. if( db->mallocFailed ){
  84008. goto exit_drop_index;
  84009. }
  84010. assert( pName->nSrc==1 );
  84011. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  84012. goto exit_drop_index;
  84013. }
  84014. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  84015. if( pIndex==0 ){
  84016. if( !ifExists ){
  84017. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  84018. }else{
  84019. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  84020. }
  84021. pParse->checkSchema = 1;
  84022. goto exit_drop_index;
  84023. }
  84024. if( pIndex->autoIndex ){
  84025. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  84026. "or PRIMARY KEY constraint cannot be dropped", 0);
  84027. goto exit_drop_index;
  84028. }
  84029. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  84030. #ifndef SQLITE_OMIT_AUTHORIZATION
  84031. {
  84032. int code = SQLITE_DROP_INDEX;
  84033. Table *pTab = pIndex->pTable;
  84034. const char *zDb = db->aDb[iDb].zName;
  84035. const char *zTab = SCHEMA_TABLE(iDb);
  84036. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  84037. goto exit_drop_index;
  84038. }
  84039. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  84040. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  84041. goto exit_drop_index;
  84042. }
  84043. }
  84044. #endif
  84045. /* Generate code to remove the index and from the master table */
  84046. v = sqlite3GetVdbe(pParse);
  84047. if( v ){
  84048. sqlite3BeginWriteOperation(pParse, 1, iDb);
  84049. sqlite3NestedParse(pParse,
  84050. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  84051. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  84052. );
  84053. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  84054. sqlite3ChangeCookie(pParse, iDb);
  84055. destroyRootPage(pParse, pIndex->tnum, iDb);
  84056. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  84057. }
  84058. exit_drop_index:
  84059. sqlite3SrcListDelete(db, pName);
  84060. }
  84061. /*
  84062. ** pArray is a pointer to an array of objects. Each object in the
  84063. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  84064. ** to extend the array so that there is space for a new object at the end.
  84065. **
  84066. ** When this function is called, *pnEntry contains the current size of
  84067. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  84068. ** in total).
  84069. **
  84070. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  84071. ** space allocated for the new object is zeroed, *pnEntry updated to
  84072. ** reflect the new size of the array and a pointer to the new allocation
  84073. ** returned. *pIdx is set to the index of the new array entry in this case.
  84074. **
  84075. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  84076. ** unchanged and a copy of pArray returned.
  84077. */
  84078. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  84079. sqlite3 *db, /* Connection to notify of malloc failures */
  84080. void *pArray, /* Array of objects. Might be reallocated */
  84081. int szEntry, /* Size of each object in the array */
  84082. int *pnEntry, /* Number of objects currently in use */
  84083. int *pIdx /* Write the index of a new slot here */
  84084. ){
  84085. char *z;
  84086. int n = *pnEntry;
  84087. if( (n & (n-1))==0 ){
  84088. int sz = (n==0) ? 1 : 2*n;
  84089. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  84090. if( pNew==0 ){
  84091. *pIdx = -1;
  84092. return pArray;
  84093. }
  84094. pArray = pNew;
  84095. }
  84096. z = (char*)pArray;
  84097. memset(&z[n * szEntry], 0, szEntry);
  84098. *pIdx = n;
  84099. ++*pnEntry;
  84100. return pArray;
  84101. }
  84102. /*
  84103. ** Append a new element to the given IdList. Create a new IdList if
  84104. ** need be.
  84105. **
  84106. ** A new IdList is returned, or NULL if malloc() fails.
  84107. */
  84108. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  84109. int i;
  84110. if( pList==0 ){
  84111. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  84112. if( pList==0 ) return 0;
  84113. }
  84114. pList->a = sqlite3ArrayAllocate(
  84115. db,
  84116. pList->a,
  84117. sizeof(pList->a[0]),
  84118. &pList->nId,
  84119. &i
  84120. );
  84121. if( i<0 ){
  84122. sqlite3IdListDelete(db, pList);
  84123. return 0;
  84124. }
  84125. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  84126. return pList;
  84127. }
  84128. /*
  84129. ** Delete an IdList.
  84130. */
  84131. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  84132. int i;
  84133. if( pList==0 ) return;
  84134. for(i=0; i<pList->nId; i++){
  84135. sqlite3DbFree(db, pList->a[i].zName);
  84136. }
  84137. sqlite3DbFree(db, pList->a);
  84138. sqlite3DbFree(db, pList);
  84139. }
  84140. /*
  84141. ** Return the index in pList of the identifier named zId. Return -1
  84142. ** if not found.
  84143. */
  84144. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  84145. int i;
  84146. if( pList==0 ) return -1;
  84147. for(i=0; i<pList->nId; i++){
  84148. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  84149. }
  84150. return -1;
  84151. }
  84152. /*
  84153. ** Expand the space allocated for the given SrcList object by
  84154. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  84155. ** New slots are zeroed.
  84156. **
  84157. ** For example, suppose a SrcList initially contains two entries: A,B.
  84158. ** To append 3 new entries onto the end, do this:
  84159. **
  84160. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  84161. **
  84162. ** After the call above it would contain: A, B, nil, nil, nil.
  84163. ** If the iStart argument had been 1 instead of 2, then the result
  84164. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  84165. ** the iStart value would be 0. The result then would
  84166. ** be: nil, nil, nil, A, B.
  84167. **
  84168. ** If a memory allocation fails the SrcList is unchanged. The
  84169. ** db->mallocFailed flag will be set to true.
  84170. */
  84171. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  84172. sqlite3 *db, /* Database connection to notify of OOM errors */
  84173. SrcList *pSrc, /* The SrcList to be enlarged */
  84174. int nExtra, /* Number of new slots to add to pSrc->a[] */
  84175. int iStart /* Index in pSrc->a[] of first new slot */
  84176. ){
  84177. int i;
  84178. /* Sanity checking on calling parameters */
  84179. assert( iStart>=0 );
  84180. assert( nExtra>=1 );
  84181. assert( pSrc!=0 );
  84182. assert( iStart<=pSrc->nSrc );
  84183. /* Allocate additional space if needed */
  84184. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  84185. SrcList *pNew;
  84186. int nAlloc = pSrc->nSrc+nExtra;
  84187. int nGot;
  84188. pNew = sqlite3DbRealloc(db, pSrc,
  84189. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  84190. if( pNew==0 ){
  84191. assert( db->mallocFailed );
  84192. return pSrc;
  84193. }
  84194. pSrc = pNew;
  84195. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  84196. pSrc->nAlloc = (u8)nGot;
  84197. }
  84198. /* Move existing slots that come after the newly inserted slots
  84199. ** out of the way */
  84200. for(i=pSrc->nSrc-1; i>=iStart; i--){
  84201. pSrc->a[i+nExtra] = pSrc->a[i];
  84202. }
  84203. pSrc->nSrc += (i8)nExtra;
  84204. /* Zero the newly allocated slots */
  84205. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  84206. for(i=iStart; i<iStart+nExtra; i++){
  84207. pSrc->a[i].iCursor = -1;
  84208. }
  84209. /* Return a pointer to the enlarged SrcList */
  84210. return pSrc;
  84211. }
  84212. /*
  84213. ** Append a new table name to the given SrcList. Create a new SrcList if
  84214. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  84215. **
  84216. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  84217. ** SrcList might be the same as the SrcList that was input or it might be
  84218. ** a new one. If an OOM error does occurs, then the prior value of pList
  84219. ** that is input to this routine is automatically freed.
  84220. **
  84221. ** If pDatabase is not null, it means that the table has an optional
  84222. ** database name prefix. Like this: "database.table". The pDatabase
  84223. ** points to the table name and the pTable points to the database name.
  84224. ** The SrcList.a[].zName field is filled with the table name which might
  84225. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  84226. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  84227. ** or with NULL if no database is specified.
  84228. **
  84229. ** In other words, if call like this:
  84230. **
  84231. ** sqlite3SrcListAppend(D,A,B,0);
  84232. **
  84233. ** Then B is a table name and the database name is unspecified. If called
  84234. ** like this:
  84235. **
  84236. ** sqlite3SrcListAppend(D,A,B,C);
  84237. **
  84238. ** Then C is the table name and B is the database name. If C is defined
  84239. ** then so is B. In other words, we never have a case where:
  84240. **
  84241. ** sqlite3SrcListAppend(D,A,0,C);
  84242. **
  84243. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  84244. ** before being added to the SrcList.
  84245. */
  84246. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  84247. sqlite3 *db, /* Connection to notify of malloc failures */
  84248. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  84249. Token *pTable, /* Table to append */
  84250. Token *pDatabase /* Database of the table */
  84251. ){
  84252. struct SrcList_item *pItem;
  84253. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  84254. if( pList==0 ){
  84255. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  84256. if( pList==0 ) return 0;
  84257. pList->nAlloc = 1;
  84258. }
  84259. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  84260. if( db->mallocFailed ){
  84261. sqlite3SrcListDelete(db, pList);
  84262. return 0;
  84263. }
  84264. pItem = &pList->a[pList->nSrc-1];
  84265. if( pDatabase && pDatabase->z==0 ){
  84266. pDatabase = 0;
  84267. }
  84268. if( pDatabase ){
  84269. Token *pTemp = pDatabase;
  84270. pDatabase = pTable;
  84271. pTable = pTemp;
  84272. }
  84273. pItem->zName = sqlite3NameFromToken(db, pTable);
  84274. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  84275. return pList;
  84276. }
  84277. /*
  84278. ** Assign VdbeCursor index numbers to all tables in a SrcList
  84279. */
  84280. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  84281. int i;
  84282. struct SrcList_item *pItem;
  84283. assert(pList || pParse->db->mallocFailed );
  84284. if( pList ){
  84285. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  84286. if( pItem->iCursor>=0 ) break;
  84287. pItem->iCursor = pParse->nTab++;
  84288. if( pItem->pSelect ){
  84289. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  84290. }
  84291. }
  84292. }
  84293. }
  84294. /*
  84295. ** Delete an entire SrcList including all its substructure.
  84296. */
  84297. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  84298. int i;
  84299. struct SrcList_item *pItem;
  84300. if( pList==0 ) return;
  84301. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  84302. sqlite3DbFree(db, pItem->zDatabase);
  84303. sqlite3DbFree(db, pItem->zName);
  84304. sqlite3DbFree(db, pItem->zAlias);
  84305. sqlite3DbFree(db, pItem->zIndex);
  84306. sqlite3DeleteTable(db, pItem->pTab);
  84307. sqlite3SelectDelete(db, pItem->pSelect);
  84308. sqlite3ExprDelete(db, pItem->pOn);
  84309. sqlite3IdListDelete(db, pItem->pUsing);
  84310. }
  84311. sqlite3DbFree(db, pList);
  84312. }
  84313. /*
  84314. ** This routine is called by the parser to add a new term to the
  84315. ** end of a growing FROM clause. The "p" parameter is the part of
  84316. ** the FROM clause that has already been constructed. "p" is NULL
  84317. ** if this is the first term of the FROM clause. pTable and pDatabase
  84318. ** are the name of the table and database named in the FROM clause term.
  84319. ** pDatabase is NULL if the database name qualifier is missing - the
  84320. ** usual case. If the term has a alias, then pAlias points to the
  84321. ** alias token. If the term is a subquery, then pSubquery is the
  84322. ** SELECT statement that the subquery encodes. The pTable and
  84323. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  84324. ** parameters are the content of the ON and USING clauses.
  84325. **
  84326. ** Return a new SrcList which encodes is the FROM with the new
  84327. ** term added.
  84328. */
  84329. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  84330. Parse *pParse, /* Parsing context */
  84331. SrcList *p, /* The left part of the FROM clause already seen */
  84332. Token *pTable, /* Name of the table to add to the FROM clause */
  84333. Token *pDatabase, /* Name of the database containing pTable */
  84334. Token *pAlias, /* The right-hand side of the AS subexpression */
  84335. Select *pSubquery, /* A subquery used in place of a table name */
  84336. Expr *pOn, /* The ON clause of a join */
  84337. IdList *pUsing /* The USING clause of a join */
  84338. ){
  84339. struct SrcList_item *pItem;
  84340. sqlite3 *db = pParse->db;
  84341. if( !p && (pOn || pUsing) ){
  84342. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  84343. (pOn ? "ON" : "USING")
  84344. );
  84345. goto append_from_error;
  84346. }
  84347. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  84348. if( p==0 || NEVER(p->nSrc==0) ){
  84349. goto append_from_error;
  84350. }
  84351. pItem = &p->a[p->nSrc-1];
  84352. assert( pAlias!=0 );
  84353. if( pAlias->n ){
  84354. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  84355. }
  84356. pItem->pSelect = pSubquery;
  84357. pItem->pOn = pOn;
  84358. pItem->pUsing = pUsing;
  84359. return p;
  84360. append_from_error:
  84361. assert( p==0 );
  84362. sqlite3ExprDelete(db, pOn);
  84363. sqlite3IdListDelete(db, pUsing);
  84364. sqlite3SelectDelete(db, pSubquery);
  84365. return 0;
  84366. }
  84367. /*
  84368. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  84369. ** element of the source-list passed as the second argument.
  84370. */
  84371. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  84372. assert( pIndexedBy!=0 );
  84373. if( p && ALWAYS(p->nSrc>0) ){
  84374. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  84375. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  84376. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  84377. /* A "NOT INDEXED" clause was supplied. See parse.y
  84378. ** construct "indexed_opt" for details. */
  84379. pItem->notIndexed = 1;
  84380. }else{
  84381. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  84382. }
  84383. }
  84384. }
  84385. /*
  84386. ** When building up a FROM clause in the parser, the join operator
  84387. ** is initially attached to the left operand. But the code generator
  84388. ** expects the join operator to be on the right operand. This routine
  84389. ** Shifts all join operators from left to right for an entire FROM
  84390. ** clause.
  84391. **
  84392. ** Example: Suppose the join is like this:
  84393. **
  84394. ** A natural cross join B
  84395. **
  84396. ** The operator is "natural cross join". The A and B operands are stored
  84397. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  84398. ** operator with A. This routine shifts that operator over to B.
  84399. */
  84400. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  84401. if( p ){
  84402. int i;
  84403. assert( p->a || p->nSrc==0 );
  84404. for(i=p->nSrc-1; i>0; i--){
  84405. p->a[i].jointype = p->a[i-1].jointype;
  84406. }
  84407. p->a[0].jointype = 0;
  84408. }
  84409. }
  84410. /*
  84411. ** Begin a transaction
  84412. */
  84413. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  84414. sqlite3 *db;
  84415. Vdbe *v;
  84416. int i;
  84417. assert( pParse!=0 );
  84418. db = pParse->db;
  84419. assert( db!=0 );
  84420. /* if( db->aDb[0].pBt==0 ) return; */
  84421. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  84422. return;
  84423. }
  84424. v = sqlite3GetVdbe(pParse);
  84425. if( !v ) return;
  84426. if( type!=TK_DEFERRED ){
  84427. for(i=0; i<db->nDb; i++){
  84428. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  84429. sqlite3VdbeUsesBtree(v, i);
  84430. }
  84431. }
  84432. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  84433. }
  84434. /*
  84435. ** Commit a transaction
  84436. */
  84437. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  84438. Vdbe *v;
  84439. assert( pParse!=0 );
  84440. assert( pParse->db!=0 );
  84441. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  84442. return;
  84443. }
  84444. v = sqlite3GetVdbe(pParse);
  84445. if( v ){
  84446. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  84447. }
  84448. }
  84449. /*
  84450. ** Rollback a transaction
  84451. */
  84452. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  84453. Vdbe *v;
  84454. assert( pParse!=0 );
  84455. assert( pParse->db!=0 );
  84456. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  84457. return;
  84458. }
  84459. v = sqlite3GetVdbe(pParse);
  84460. if( v ){
  84461. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  84462. }
  84463. }
  84464. /*
  84465. ** This function is called by the parser when it parses a command to create,
  84466. ** release or rollback an SQL savepoint.
  84467. */
  84468. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  84469. char *zName = sqlite3NameFromToken(pParse->db, pName);
  84470. if( zName ){
  84471. Vdbe *v = sqlite3GetVdbe(pParse);
  84472. #ifndef SQLITE_OMIT_AUTHORIZATION
  84473. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  84474. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  84475. #endif
  84476. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  84477. sqlite3DbFree(pParse->db, zName);
  84478. return;
  84479. }
  84480. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  84481. }
  84482. }
  84483. /*
  84484. ** Make sure the TEMP database is open and available for use. Return
  84485. ** the number of errors. Leave any error messages in the pParse structure.
  84486. */
  84487. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  84488. sqlite3 *db = pParse->db;
  84489. if( db->aDb[1].pBt==0 && !pParse->explain ){
  84490. int rc;
  84491. Btree *pBt;
  84492. static const int flags =
  84493. SQLITE_OPEN_READWRITE |
  84494. SQLITE_OPEN_CREATE |
  84495. SQLITE_OPEN_EXCLUSIVE |
  84496. SQLITE_OPEN_DELETEONCLOSE |
  84497. SQLITE_OPEN_TEMP_DB;
  84498. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  84499. if( rc!=SQLITE_OK ){
  84500. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  84501. "file for storing temporary tables");
  84502. pParse->rc = rc;
  84503. return 1;
  84504. }
  84505. db->aDb[1].pBt = pBt;
  84506. assert( db->aDb[1].pSchema );
  84507. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  84508. db->mallocFailed = 1;
  84509. return 1;
  84510. }
  84511. }
  84512. return 0;
  84513. }
  84514. /*
  84515. ** Generate VDBE code that will verify the schema cookie and start
  84516. ** a read-transaction for all named database files.
  84517. **
  84518. ** It is important that all schema cookies be verified and all
  84519. ** read transactions be started before anything else happens in
  84520. ** the VDBE program. But this routine can be called after much other
  84521. ** code has been generated. So here is what we do:
  84522. **
  84523. ** The first time this routine is called, we code an OP_Goto that
  84524. ** will jump to a subroutine at the end of the program. Then we
  84525. ** record every database that needs its schema verified in the
  84526. ** pParse->cookieMask field. Later, after all other code has been
  84527. ** generated, the subroutine that does the cookie verifications and
  84528. ** starts the transactions will be coded and the OP_Goto P2 value
  84529. ** will be made to point to that subroutine. The generation of the
  84530. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  84531. **
  84532. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  84533. ** schema on any databases. This can be used to position the OP_Goto
  84534. ** early in the code, before we know if any database tables will be used.
  84535. */
  84536. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  84537. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84538. #ifndef SQLITE_OMIT_TRIGGER
  84539. if( pToplevel!=pParse ){
  84540. /* This branch is taken if a trigger is currently being coded. In this
  84541. ** case, set cookieGoto to a non-zero value to show that this function
  84542. ** has been called. This is used by the sqlite3ExprCodeConstants()
  84543. ** function. */
  84544. pParse->cookieGoto = -1;
  84545. }
  84546. #endif
  84547. if( pToplevel->cookieGoto==0 ){
  84548. Vdbe *v = sqlite3GetVdbe(pToplevel);
  84549. if( v==0 ) return; /* This only happens if there was a prior error */
  84550. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  84551. }
  84552. if( iDb>=0 ){
  84553. sqlite3 *db = pToplevel->db;
  84554. yDbMask mask;
  84555. assert( iDb<db->nDb );
  84556. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  84557. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  84558. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84559. mask = ((yDbMask)1)<<iDb;
  84560. if( (pToplevel->cookieMask & mask)==0 ){
  84561. pToplevel->cookieMask |= mask;
  84562. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  84563. if( !OMIT_TEMPDB && iDb==1 ){
  84564. sqlite3OpenTempDatabase(pToplevel);
  84565. }
  84566. }
  84567. }
  84568. }
  84569. /*
  84570. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  84571. ** attached database. Otherwise, invoke it for the database named zDb only.
  84572. */
  84573. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  84574. sqlite3 *db = pParse->db;
  84575. int i;
  84576. for(i=0; i<db->nDb; i++){
  84577. Db *pDb = &db->aDb[i];
  84578. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  84579. sqlite3CodeVerifySchema(pParse, i);
  84580. }
  84581. }
  84582. }
  84583. /*
  84584. ** Generate VDBE code that prepares for doing an operation that
  84585. ** might change the database.
  84586. **
  84587. ** This routine starts a new transaction if we are not already within
  84588. ** a transaction. If we are already within a transaction, then a checkpoint
  84589. ** is set if the setStatement parameter is true. A checkpoint should
  84590. ** be set for operations that might fail (due to a constraint) part of
  84591. ** the way through and which will need to undo some writes without having to
  84592. ** rollback the whole transaction. For operations where all constraints
  84593. ** can be checked before any changes are made to the database, it is never
  84594. ** necessary to undo a write and the checkpoint should not be set.
  84595. */
  84596. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  84597. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84598. sqlite3CodeVerifySchema(pParse, iDb);
  84599. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  84600. pToplevel->isMultiWrite |= setStatement;
  84601. }
  84602. /*
  84603. ** Indicate that the statement currently under construction might write
  84604. ** more than one entry (example: deleting one row then inserting another,
  84605. ** inserting multiple rows in a table, or inserting a row and index entries.)
  84606. ** If an abort occurs after some of these writes have completed, then it will
  84607. ** be necessary to undo the completed writes.
  84608. */
  84609. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  84610. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84611. pToplevel->isMultiWrite = 1;
  84612. }
  84613. /*
  84614. ** The code generator calls this routine if is discovers that it is
  84615. ** possible to abort a statement prior to completion. In order to
  84616. ** perform this abort without corrupting the database, we need to make
  84617. ** sure that the statement is protected by a statement transaction.
  84618. **
  84619. ** Technically, we only need to set the mayAbort flag if the
  84620. ** isMultiWrite flag was previously set. There is a time dependency
  84621. ** such that the abort must occur after the multiwrite. This makes
  84622. ** some statements involving the REPLACE conflict resolution algorithm
  84623. ** go a little faster. But taking advantage of this time dependency
  84624. ** makes it more difficult to prove that the code is correct (in
  84625. ** particular, it prevents us from writing an effective
  84626. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  84627. ** to take the safe route and skip the optimization.
  84628. */
  84629. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  84630. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84631. pToplevel->mayAbort = 1;
  84632. }
  84633. /*
  84634. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  84635. ** error. The onError parameter determines which (if any) of the statement
  84636. ** and/or current transaction is rolled back.
  84637. */
  84638. SQLITE_PRIVATE void sqlite3HaltConstraint(
  84639. Parse *pParse, /* Parsing context */
  84640. int errCode, /* extended error code */
  84641. int onError, /* Constraint type */
  84642. char *p4, /* Error message */
  84643. int p4type /* P4_STATIC or P4_TRANSIENT */
  84644. ){
  84645. Vdbe *v = sqlite3GetVdbe(pParse);
  84646. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  84647. if( onError==OE_Abort ){
  84648. sqlite3MayAbort(pParse);
  84649. }
  84650. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  84651. }
  84652. /*
  84653. ** Check to see if pIndex uses the collating sequence pColl. Return
  84654. ** true if it does and false if it does not.
  84655. */
  84656. #ifndef SQLITE_OMIT_REINDEX
  84657. static int collationMatch(const char *zColl, Index *pIndex){
  84658. int i;
  84659. assert( zColl!=0 );
  84660. for(i=0; i<pIndex->nColumn; i++){
  84661. const char *z = pIndex->azColl[i];
  84662. assert( z!=0 );
  84663. if( 0==sqlite3StrICmp(z, zColl) ){
  84664. return 1;
  84665. }
  84666. }
  84667. return 0;
  84668. }
  84669. #endif
  84670. /*
  84671. ** Recompute all indices of pTab that use the collating sequence pColl.
  84672. ** If pColl==0 then recompute all indices of pTab.
  84673. */
  84674. #ifndef SQLITE_OMIT_REINDEX
  84675. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  84676. Index *pIndex; /* An index associated with pTab */
  84677. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  84678. if( zColl==0 || collationMatch(zColl, pIndex) ){
  84679. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84680. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84681. sqlite3RefillIndex(pParse, pIndex, -1);
  84682. }
  84683. }
  84684. }
  84685. #endif
  84686. /*
  84687. ** Recompute all indices of all tables in all databases where the
  84688. ** indices use the collating sequence pColl. If pColl==0 then recompute
  84689. ** all indices everywhere.
  84690. */
  84691. #ifndef SQLITE_OMIT_REINDEX
  84692. static void reindexDatabases(Parse *pParse, char const *zColl){
  84693. Db *pDb; /* A single database */
  84694. int iDb; /* The database index number */
  84695. sqlite3 *db = pParse->db; /* The database connection */
  84696. HashElem *k; /* For looping over tables in pDb */
  84697. Table *pTab; /* A table in the database */
  84698. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  84699. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  84700. assert( pDb!=0 );
  84701. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  84702. pTab = (Table*)sqliteHashData(k);
  84703. reindexTable(pParse, pTab, zColl);
  84704. }
  84705. }
  84706. }
  84707. #endif
  84708. /*
  84709. ** Generate code for the REINDEX command.
  84710. **
  84711. ** REINDEX -- 1
  84712. ** REINDEX <collation> -- 2
  84713. ** REINDEX ?<database>.?<tablename> -- 3
  84714. ** REINDEX ?<database>.?<indexname> -- 4
  84715. **
  84716. ** Form 1 causes all indices in all attached databases to be rebuilt.
  84717. ** Form 2 rebuilds all indices in all databases that use the named
  84718. ** collating function. Forms 3 and 4 rebuild the named index or all
  84719. ** indices associated with the named table.
  84720. */
  84721. #ifndef SQLITE_OMIT_REINDEX
  84722. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  84723. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  84724. char *z; /* Name of a table or index */
  84725. const char *zDb; /* Name of the database */
  84726. Table *pTab; /* A table in the database */
  84727. Index *pIndex; /* An index associated with pTab */
  84728. int iDb; /* The database index number */
  84729. sqlite3 *db = pParse->db; /* The database connection */
  84730. Token *pObjName; /* Name of the table or index to be reindexed */
  84731. /* Read the database schema. If an error occurs, leave an error message
  84732. ** and code in pParse and return NULL. */
  84733. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  84734. return;
  84735. }
  84736. if( pName1==0 ){
  84737. reindexDatabases(pParse, 0);
  84738. return;
  84739. }else if( NEVER(pName2==0) || pName2->z==0 ){
  84740. char *zColl;
  84741. assert( pName1->z );
  84742. zColl = sqlite3NameFromToken(pParse->db, pName1);
  84743. if( !zColl ) return;
  84744. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  84745. if( pColl ){
  84746. reindexDatabases(pParse, zColl);
  84747. sqlite3DbFree(db, zColl);
  84748. return;
  84749. }
  84750. sqlite3DbFree(db, zColl);
  84751. }
  84752. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  84753. if( iDb<0 ) return;
  84754. z = sqlite3NameFromToken(db, pObjName);
  84755. if( z==0 ) return;
  84756. zDb = db->aDb[iDb].zName;
  84757. pTab = sqlite3FindTable(db, z, zDb);
  84758. if( pTab ){
  84759. reindexTable(pParse, pTab, 0);
  84760. sqlite3DbFree(db, z);
  84761. return;
  84762. }
  84763. pIndex = sqlite3FindIndex(db, z, zDb);
  84764. sqlite3DbFree(db, z);
  84765. if( pIndex ){
  84766. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84767. sqlite3RefillIndex(pParse, pIndex, -1);
  84768. return;
  84769. }
  84770. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  84771. }
  84772. #endif
  84773. /*
  84774. ** Return a dynamicly allocated KeyInfo structure that can be used
  84775. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  84776. **
  84777. ** If successful, a pointer to the new structure is returned. In this case
  84778. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  84779. ** pointer. If an error occurs (out of memory or missing collation
  84780. ** sequence), NULL is returned and the state of pParse updated to reflect
  84781. ** the error.
  84782. */
  84783. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  84784. int i;
  84785. int nCol = pIdx->nColumn;
  84786. KeyInfo *pKey;
  84787. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  84788. if( pKey ){
  84789. for(i=0; i<nCol; i++){
  84790. char *zColl = pIdx->azColl[i];
  84791. assert( zColl );
  84792. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  84793. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  84794. }
  84795. }
  84796. if( pParse->nErr ){
  84797. sqlite3DbFree(pParse->db, pKey);
  84798. pKey = 0;
  84799. }
  84800. return pKey;
  84801. }
  84802. /************** End of build.c ***********************************************/
  84803. /************** Begin file callback.c ****************************************/
  84804. /*
  84805. ** 2005 May 23
  84806. **
  84807. ** The author disclaims copyright to this source code. In place of
  84808. ** a legal notice, here is a blessing:
  84809. **
  84810. ** May you do good and not evil.
  84811. ** May you find forgiveness for yourself and forgive others.
  84812. ** May you share freely, never taking more than you give.
  84813. **
  84814. *************************************************************************
  84815. **
  84816. ** This file contains functions used to access the internal hash tables
  84817. ** of user defined functions and collation sequences.
  84818. */
  84819. /*
  84820. ** Invoke the 'collation needed' callback to request a collation sequence
  84821. ** in the encoding enc of name zName, length nName.
  84822. */
  84823. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  84824. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  84825. if( db->xCollNeeded ){
  84826. char *zExternal = sqlite3DbStrDup(db, zName);
  84827. if( !zExternal ) return;
  84828. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  84829. sqlite3DbFree(db, zExternal);
  84830. }
  84831. #ifndef SQLITE_OMIT_UTF16
  84832. if( db->xCollNeeded16 ){
  84833. char const *zExternal;
  84834. sqlite3_value *pTmp = sqlite3ValueNew(db);
  84835. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  84836. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  84837. if( zExternal ){
  84838. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  84839. }
  84840. sqlite3ValueFree(pTmp);
  84841. }
  84842. #endif
  84843. }
  84844. /*
  84845. ** This routine is called if the collation factory fails to deliver a
  84846. ** collation function in the best encoding but there may be other versions
  84847. ** of this collation function (for other text encodings) available. Use one
  84848. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  84849. ** possible.
  84850. */
  84851. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  84852. CollSeq *pColl2;
  84853. char *z = pColl->zName;
  84854. int i;
  84855. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  84856. for(i=0; i<3; i++){
  84857. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  84858. if( pColl2->xCmp!=0 ){
  84859. memcpy(pColl, pColl2, sizeof(CollSeq));
  84860. pColl->xDel = 0; /* Do not copy the destructor */
  84861. return SQLITE_OK;
  84862. }
  84863. }
  84864. return SQLITE_ERROR;
  84865. }
  84866. /*
  84867. ** This function is responsible for invoking the collation factory callback
  84868. ** or substituting a collation sequence of a different encoding when the
  84869. ** requested collation sequence is not available in the desired encoding.
  84870. **
  84871. ** If it is not NULL, then pColl must point to the database native encoding
  84872. ** collation sequence with name zName, length nName.
  84873. **
  84874. ** The return value is either the collation sequence to be used in database
  84875. ** db for collation type name zName, length nName, or NULL, if no collation
  84876. ** sequence can be found. If no collation is found, leave an error message.
  84877. **
  84878. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  84879. */
  84880. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  84881. Parse *pParse, /* Parsing context */
  84882. u8 enc, /* The desired encoding for the collating sequence */
  84883. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  84884. const char *zName /* Collating sequence name */
  84885. ){
  84886. CollSeq *p;
  84887. sqlite3 *db = pParse->db;
  84888. p = pColl;
  84889. if( !p ){
  84890. p = sqlite3FindCollSeq(db, enc, zName, 0);
  84891. }
  84892. if( !p || !p->xCmp ){
  84893. /* No collation sequence of this type for this encoding is registered.
  84894. ** Call the collation factory to see if it can supply us with one.
  84895. */
  84896. callCollNeeded(db, enc, zName);
  84897. p = sqlite3FindCollSeq(db, enc, zName, 0);
  84898. }
  84899. if( p && !p->xCmp && synthCollSeq(db, p) ){
  84900. p = 0;
  84901. }
  84902. assert( !p || p->xCmp );
  84903. if( p==0 ){
  84904. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  84905. }
  84906. return p;
  84907. }
  84908. /*
  84909. ** This routine is called on a collation sequence before it is used to
  84910. ** check that it is defined. An undefined collation sequence exists when
  84911. ** a database is loaded that contains references to collation sequences
  84912. ** that have not been defined by sqlite3_create_collation() etc.
  84913. **
  84914. ** If required, this routine calls the 'collation needed' callback to
  84915. ** request a definition of the collating sequence. If this doesn't work,
  84916. ** an equivalent collating sequence that uses a text encoding different
  84917. ** from the main database is substituted, if one is available.
  84918. */
  84919. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  84920. if( pColl ){
  84921. const char *zName = pColl->zName;
  84922. sqlite3 *db = pParse->db;
  84923. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  84924. if( !p ){
  84925. return SQLITE_ERROR;
  84926. }
  84927. assert( p==pColl );
  84928. }
  84929. return SQLITE_OK;
  84930. }
  84931. /*
  84932. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  84933. ** specified by zName and nName is not found and parameter 'create' is
  84934. ** true, then create a new entry. Otherwise return NULL.
  84935. **
  84936. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  84937. ** array of three CollSeq structures. The first is the collation sequence
  84938. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  84939. **
  84940. ** Stored immediately after the three collation sequences is a copy of
  84941. ** the collation sequence name. A pointer to this string is stored in
  84942. ** each collation sequence structure.
  84943. */
  84944. static CollSeq *findCollSeqEntry(
  84945. sqlite3 *db, /* Database connection */
  84946. const char *zName, /* Name of the collating sequence */
  84947. int create /* Create a new entry if true */
  84948. ){
  84949. CollSeq *pColl;
  84950. int nName = sqlite3Strlen30(zName);
  84951. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  84952. if( 0==pColl && create ){
  84953. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  84954. if( pColl ){
  84955. CollSeq *pDel = 0;
  84956. pColl[0].zName = (char*)&pColl[3];
  84957. pColl[0].enc = SQLITE_UTF8;
  84958. pColl[1].zName = (char*)&pColl[3];
  84959. pColl[1].enc = SQLITE_UTF16LE;
  84960. pColl[2].zName = (char*)&pColl[3];
  84961. pColl[2].enc = SQLITE_UTF16BE;
  84962. memcpy(pColl[0].zName, zName, nName);
  84963. pColl[0].zName[nName] = 0;
  84964. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  84965. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  84966. ** return the pColl pointer to be deleted (because it wasn't added
  84967. ** to the hash table).
  84968. */
  84969. assert( pDel==0 || pDel==pColl );
  84970. if( pDel!=0 ){
  84971. db->mallocFailed = 1;
  84972. sqlite3DbFree(db, pDel);
  84973. pColl = 0;
  84974. }
  84975. }
  84976. }
  84977. return pColl;
  84978. }
  84979. /*
  84980. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  84981. ** Return the CollSeq* pointer for the collation sequence named zName
  84982. ** for the encoding 'enc' from the database 'db'.
  84983. **
  84984. ** If the entry specified is not found and 'create' is true, then create a
  84985. ** new entry. Otherwise return NULL.
  84986. **
  84987. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  84988. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  84989. ** if necessary and generates an error message if the collating sequence
  84990. ** cannot be found.
  84991. **
  84992. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  84993. */
  84994. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  84995. sqlite3 *db,
  84996. u8 enc,
  84997. const char *zName,
  84998. int create
  84999. ){
  85000. CollSeq *pColl;
  85001. if( zName ){
  85002. pColl = findCollSeqEntry(db, zName, create);
  85003. }else{
  85004. pColl = db->pDfltColl;
  85005. }
  85006. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  85007. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  85008. if( pColl ) pColl += enc-1;
  85009. return pColl;
  85010. }
  85011. /* During the search for the best function definition, this procedure
  85012. ** is called to test how well the function passed as the first argument
  85013. ** matches the request for a function with nArg arguments in a system
  85014. ** that uses encoding enc. The value returned indicates how well the
  85015. ** request is matched. A higher value indicates a better match.
  85016. **
  85017. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  85018. ** is also -1. In other words, we are searching for a function that
  85019. ** takes a variable number of arguments.
  85020. **
  85021. ** If nArg is -2 that means that we are searching for any function
  85022. ** regardless of the number of arguments it uses, so return a positive
  85023. ** match score for any
  85024. **
  85025. ** The returned value is always between 0 and 6, as follows:
  85026. **
  85027. ** 0: Not a match.
  85028. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  85029. ** 2: UTF16 byte order change required and function takes any number of args.
  85030. ** 3: encoding matches and function takes any number of arguments
  85031. ** 4: UTF8/16 conversion required - argument count matches exactly
  85032. ** 5: UTF16 byte order conversion required - argument count matches exactly
  85033. ** 6: Perfect match: encoding and argument count match exactly.
  85034. **
  85035. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  85036. ** a perfect match and any function with both xStep and xFunc NULL is
  85037. ** a non-match.
  85038. */
  85039. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  85040. static int matchQuality(
  85041. FuncDef *p, /* The function we are evaluating for match quality */
  85042. int nArg, /* Desired number of arguments. (-1)==any */
  85043. u8 enc /* Desired text encoding */
  85044. ){
  85045. int match;
  85046. /* nArg of -2 is a special case */
  85047. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  85048. /* Wrong number of arguments means "no match" */
  85049. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  85050. /* Give a better score to a function with a specific number of arguments
  85051. ** than to function that accepts any number of arguments. */
  85052. if( p->nArg==nArg ){
  85053. match = 4;
  85054. }else{
  85055. match = 1;
  85056. }
  85057. /* Bonus points if the text encoding matches */
  85058. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  85059. match += 2; /* Exact encoding match */
  85060. }else if( (enc & p->funcFlags & 2)!=0 ){
  85061. match += 1; /* Both are UTF16, but with different byte orders */
  85062. }
  85063. return match;
  85064. }
  85065. /*
  85066. ** Search a FuncDefHash for a function with the given name. Return
  85067. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  85068. */
  85069. static FuncDef *functionSearch(
  85070. FuncDefHash *pHash, /* Hash table to search */
  85071. int h, /* Hash of the name */
  85072. const char *zFunc, /* Name of function */
  85073. int nFunc /* Number of bytes in zFunc */
  85074. ){
  85075. FuncDef *p;
  85076. for(p=pHash->a[h]; p; p=p->pHash){
  85077. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  85078. return p;
  85079. }
  85080. }
  85081. return 0;
  85082. }
  85083. /*
  85084. ** Insert a new FuncDef into a FuncDefHash hash table.
  85085. */
  85086. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  85087. FuncDefHash *pHash, /* The hash table into which to insert */
  85088. FuncDef *pDef /* The function definition to insert */
  85089. ){
  85090. FuncDef *pOther;
  85091. int nName = sqlite3Strlen30(pDef->zName);
  85092. u8 c1 = (u8)pDef->zName[0];
  85093. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  85094. pOther = functionSearch(pHash, h, pDef->zName, nName);
  85095. if( pOther ){
  85096. assert( pOther!=pDef && pOther->pNext!=pDef );
  85097. pDef->pNext = pOther->pNext;
  85098. pOther->pNext = pDef;
  85099. }else{
  85100. pDef->pNext = 0;
  85101. pDef->pHash = pHash->a[h];
  85102. pHash->a[h] = pDef;
  85103. }
  85104. }
  85105. /*
  85106. ** Locate a user function given a name, a number of arguments and a flag
  85107. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  85108. ** pointer to the FuncDef structure that defines that function, or return
  85109. ** NULL if the function does not exist.
  85110. **
  85111. ** If the createFlag argument is true, then a new (blank) FuncDef
  85112. ** structure is created and liked into the "db" structure if a
  85113. ** no matching function previously existed.
  85114. **
  85115. ** If nArg is -2, then the first valid function found is returned. A
  85116. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  85117. ** case is used to see if zName is a valid function name for some number
  85118. ** of arguments. If nArg is -2, then createFlag must be 0.
  85119. **
  85120. ** If createFlag is false, then a function with the required name and
  85121. ** number of arguments may be returned even if the eTextRep flag does not
  85122. ** match that requested.
  85123. */
  85124. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  85125. sqlite3 *db, /* An open database */
  85126. const char *zName, /* Name of the function. Not null-terminated */
  85127. int nName, /* Number of characters in the name */
  85128. int nArg, /* Number of arguments. -1 means any number */
  85129. u8 enc, /* Preferred text encoding */
  85130. u8 createFlag /* Create new entry if true and does not otherwise exist */
  85131. ){
  85132. FuncDef *p; /* Iterator variable */
  85133. FuncDef *pBest = 0; /* Best match found so far */
  85134. int bestScore = 0; /* Score of best match */
  85135. int h; /* Hash value */
  85136. assert( nArg>=(-2) );
  85137. assert( nArg>=(-1) || createFlag==0 );
  85138. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  85139. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  85140. /* First search for a match amongst the application-defined functions.
  85141. */
  85142. p = functionSearch(&db->aFunc, h, zName, nName);
  85143. while( p ){
  85144. int score = matchQuality(p, nArg, enc);
  85145. if( score>bestScore ){
  85146. pBest = p;
  85147. bestScore = score;
  85148. }
  85149. p = p->pNext;
  85150. }
  85151. /* If no match is found, search the built-in functions.
  85152. **
  85153. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  85154. ** functions even if a prior app-defined function was found. And give
  85155. ** priority to built-in functions.
  85156. **
  85157. ** Except, if createFlag is true, that means that we are trying to
  85158. ** install a new function. Whatever FuncDef structure is returned it will
  85159. ** have fields overwritten with new information appropriate for the
  85160. ** new function. But the FuncDefs for built-in functions are read-only.
  85161. ** So we must not search for built-ins when creating a new function.
  85162. */
  85163. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  85164. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  85165. bestScore = 0;
  85166. p = functionSearch(pHash, h, zName, nName);
  85167. while( p ){
  85168. int score = matchQuality(p, nArg, enc);
  85169. if( score>bestScore ){
  85170. pBest = p;
  85171. bestScore = score;
  85172. }
  85173. p = p->pNext;
  85174. }
  85175. }
  85176. /* If the createFlag parameter is true and the search did not reveal an
  85177. ** exact match for the name, number of arguments and encoding, then add a
  85178. ** new entry to the hash table and return it.
  85179. */
  85180. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  85181. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  85182. pBest->zName = (char *)&pBest[1];
  85183. pBest->nArg = (u16)nArg;
  85184. pBest->funcFlags = enc;
  85185. memcpy(pBest->zName, zName, nName);
  85186. pBest->zName[nName] = 0;
  85187. sqlite3FuncDefInsert(&db->aFunc, pBest);
  85188. }
  85189. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  85190. return pBest;
  85191. }
  85192. return 0;
  85193. }
  85194. /*
  85195. ** Free all resources held by the schema structure. The void* argument points
  85196. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  85197. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  85198. ** of the schema hash tables).
  85199. **
  85200. ** The Schema.cache_size variable is not cleared.
  85201. */
  85202. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  85203. Hash temp1;
  85204. Hash temp2;
  85205. HashElem *pElem;
  85206. Schema *pSchema = (Schema *)p;
  85207. temp1 = pSchema->tblHash;
  85208. temp2 = pSchema->trigHash;
  85209. sqlite3HashInit(&pSchema->trigHash);
  85210. sqlite3HashClear(&pSchema->idxHash);
  85211. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  85212. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  85213. }
  85214. sqlite3HashClear(&temp2);
  85215. sqlite3HashInit(&pSchema->tblHash);
  85216. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  85217. Table *pTab = sqliteHashData(pElem);
  85218. sqlite3DeleteTable(0, pTab);
  85219. }
  85220. sqlite3HashClear(&temp1);
  85221. sqlite3HashClear(&pSchema->fkeyHash);
  85222. pSchema->pSeqTab = 0;
  85223. if( pSchema->flags & DB_SchemaLoaded ){
  85224. pSchema->iGeneration++;
  85225. pSchema->flags &= ~DB_SchemaLoaded;
  85226. }
  85227. }
  85228. /*
  85229. ** Find and return the schema associated with a BTree. Create
  85230. ** a new one if necessary.
  85231. */
  85232. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  85233. Schema * p;
  85234. if( pBt ){
  85235. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  85236. }else{
  85237. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  85238. }
  85239. if( !p ){
  85240. db->mallocFailed = 1;
  85241. }else if ( 0==p->file_format ){
  85242. sqlite3HashInit(&p->tblHash);
  85243. sqlite3HashInit(&p->idxHash);
  85244. sqlite3HashInit(&p->trigHash);
  85245. sqlite3HashInit(&p->fkeyHash);
  85246. p->enc = SQLITE_UTF8;
  85247. }
  85248. return p;
  85249. }
  85250. /************** End of callback.c ********************************************/
  85251. /************** Begin file delete.c ******************************************/
  85252. /*
  85253. ** 2001 September 15
  85254. **
  85255. ** The author disclaims copyright to this source code. In place of
  85256. ** a legal notice, here is a blessing:
  85257. **
  85258. ** May you do good and not evil.
  85259. ** May you find forgiveness for yourself and forgive others.
  85260. ** May you share freely, never taking more than you give.
  85261. **
  85262. *************************************************************************
  85263. ** This file contains C code routines that are called by the parser
  85264. ** in order to generate code for DELETE FROM statements.
  85265. */
  85266. /*
  85267. ** While a SrcList can in general represent multiple tables and subqueries
  85268. ** (as in the FROM clause of a SELECT statement) in this case it contains
  85269. ** the name of a single table, as one might find in an INSERT, DELETE,
  85270. ** or UPDATE statement. Look up that table in the symbol table and
  85271. ** return a pointer. Set an error message and return NULL if the table
  85272. ** name is not found or if any other error occurs.
  85273. **
  85274. ** The following fields are initialized appropriate in pSrc:
  85275. **
  85276. ** pSrc->a[0].pTab Pointer to the Table object
  85277. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  85278. **
  85279. */
  85280. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  85281. struct SrcList_item *pItem = pSrc->a;
  85282. Table *pTab;
  85283. assert( pItem && pSrc->nSrc==1 );
  85284. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  85285. sqlite3DeleteTable(pParse->db, pItem->pTab);
  85286. pItem->pTab = pTab;
  85287. if( pTab ){
  85288. pTab->nRef++;
  85289. }
  85290. if( sqlite3IndexedByLookup(pParse, pItem) ){
  85291. pTab = 0;
  85292. }
  85293. return pTab;
  85294. }
  85295. /*
  85296. ** Check to make sure the given table is writable. If it is not
  85297. ** writable, generate an error message and return 1. If it is
  85298. ** writable return 0;
  85299. */
  85300. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  85301. /* A table is not writable under the following circumstances:
  85302. **
  85303. ** 1) It is a virtual table and no implementation of the xUpdate method
  85304. ** has been provided, or
  85305. ** 2) It is a system table (i.e. sqlite_master), this call is not
  85306. ** part of a nested parse and writable_schema pragma has not
  85307. ** been specified.
  85308. **
  85309. ** In either case leave an error message in pParse and return non-zero.
  85310. */
  85311. if( ( IsVirtual(pTab)
  85312. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  85313. || ( (pTab->tabFlags & TF_Readonly)!=0
  85314. && (pParse->db->flags & SQLITE_WriteSchema)==0
  85315. && pParse->nested==0 )
  85316. ){
  85317. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  85318. return 1;
  85319. }
  85320. #ifndef SQLITE_OMIT_VIEW
  85321. if( !viewOk && pTab->pSelect ){
  85322. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  85323. return 1;
  85324. }
  85325. #endif
  85326. return 0;
  85327. }
  85328. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  85329. /*
  85330. ** Evaluate a view and store its result in an ephemeral table. The
  85331. ** pWhere argument is an optional WHERE clause that restricts the
  85332. ** set of rows in the view that are to be added to the ephemeral table.
  85333. */
  85334. SQLITE_PRIVATE void sqlite3MaterializeView(
  85335. Parse *pParse, /* Parsing context */
  85336. Table *pView, /* View definition */
  85337. Expr *pWhere, /* Optional WHERE clause to be added */
  85338. int iCur /* Cursor number for ephemerial table */
  85339. ){
  85340. SelectDest dest;
  85341. Select *pSel;
  85342. SrcList *pFrom;
  85343. sqlite3 *db = pParse->db;
  85344. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  85345. pWhere = sqlite3ExprDup(db, pWhere, 0);
  85346. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  85347. if( pFrom ){
  85348. assert( pFrom->nSrc==1 );
  85349. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  85350. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  85351. assert( pFrom->a[0].pOn==0 );
  85352. assert( pFrom->a[0].pUsing==0 );
  85353. }
  85354. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  85355. if( pSel ) pSel->selFlags |= SF_Materialize;
  85356. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  85357. sqlite3Select(pParse, pSel, &dest);
  85358. sqlite3SelectDelete(db, pSel);
  85359. }
  85360. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  85361. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  85362. /*
  85363. ** Generate an expression tree to implement the WHERE, ORDER BY,
  85364. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  85365. **
  85366. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  85367. ** \__________________________/
  85368. ** pLimitWhere (pInClause)
  85369. */
  85370. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  85371. Parse *pParse, /* The parser context */
  85372. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  85373. Expr *pWhere, /* The WHERE clause. May be null */
  85374. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  85375. Expr *pLimit, /* The LIMIT clause. May be null */
  85376. Expr *pOffset, /* The OFFSET clause. May be null */
  85377. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  85378. ){
  85379. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  85380. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  85381. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  85382. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  85383. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  85384. Select *pSelect = NULL; /* Complete SELECT tree */
  85385. /* Check that there isn't an ORDER BY without a LIMIT clause.
  85386. */
  85387. if( pOrderBy && (pLimit == 0) ) {
  85388. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  85389. goto limit_where_cleanup_2;
  85390. }
  85391. /* We only need to generate a select expression if there
  85392. ** is a limit/offset term to enforce.
  85393. */
  85394. if( pLimit == 0 ) {
  85395. /* if pLimit is null, pOffset will always be null as well. */
  85396. assert( pOffset == 0 );
  85397. return pWhere;
  85398. }
  85399. /* Generate a select expression tree to enforce the limit/offset
  85400. ** term for the DELETE or UPDATE statement. For example:
  85401. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  85402. ** becomes:
  85403. ** DELETE FROM table_a WHERE rowid IN (
  85404. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  85405. ** );
  85406. */
  85407. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  85408. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  85409. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  85410. if( pEList == 0 ) goto limit_where_cleanup_2;
  85411. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  85412. ** and the SELECT subtree. */
  85413. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  85414. if( pSelectSrc == 0 ) {
  85415. sqlite3ExprListDelete(pParse->db, pEList);
  85416. goto limit_where_cleanup_2;
  85417. }
  85418. /* generate the SELECT expression tree. */
  85419. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  85420. pOrderBy,0,pLimit,pOffset);
  85421. if( pSelect == 0 ) return 0;
  85422. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  85423. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  85424. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  85425. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  85426. if( pInClause == 0 ) goto limit_where_cleanup_1;
  85427. pInClause->x.pSelect = pSelect;
  85428. pInClause->flags |= EP_xIsSelect;
  85429. sqlite3ExprSetHeight(pParse, pInClause);
  85430. return pInClause;
  85431. /* something went wrong. clean up anything allocated. */
  85432. limit_where_cleanup_1:
  85433. sqlite3SelectDelete(pParse->db, pSelect);
  85434. return 0;
  85435. limit_where_cleanup_2:
  85436. sqlite3ExprDelete(pParse->db, pWhere);
  85437. sqlite3ExprListDelete(pParse->db, pOrderBy);
  85438. sqlite3ExprDelete(pParse->db, pLimit);
  85439. sqlite3ExprDelete(pParse->db, pOffset);
  85440. return 0;
  85441. }
  85442. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  85443. /*
  85444. ** Generate code for a DELETE FROM statement.
  85445. **
  85446. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  85447. ** \________/ \________________/
  85448. ** pTabList pWhere
  85449. */
  85450. SQLITE_PRIVATE void sqlite3DeleteFrom(
  85451. Parse *pParse, /* The parser context */
  85452. SrcList *pTabList, /* The table from which we should delete things */
  85453. Expr *pWhere /* The WHERE clause. May be null */
  85454. ){
  85455. Vdbe *v; /* The virtual database engine */
  85456. Table *pTab; /* The table from which records will be deleted */
  85457. const char *zDb; /* Name of database holding pTab */
  85458. int end, addr = 0; /* A couple addresses of generated code */
  85459. int i; /* Loop counter */
  85460. WhereInfo *pWInfo; /* Information about the WHERE clause */
  85461. Index *pIdx; /* For looping over indices of the table */
  85462. int iCur; /* VDBE Cursor number for pTab */
  85463. sqlite3 *db; /* Main database structure */
  85464. AuthContext sContext; /* Authorization context */
  85465. NameContext sNC; /* Name context to resolve expressions in */
  85466. int iDb; /* Database number */
  85467. int memCnt = -1; /* Memory cell used for change counting */
  85468. int rcauth; /* Value returned by authorization callback */
  85469. #ifndef SQLITE_OMIT_TRIGGER
  85470. int isView; /* True if attempting to delete from a view */
  85471. Trigger *pTrigger; /* List of table triggers, if required */
  85472. #endif
  85473. memset(&sContext, 0, sizeof(sContext));
  85474. db = pParse->db;
  85475. if( pParse->nErr || db->mallocFailed ){
  85476. goto delete_from_cleanup;
  85477. }
  85478. assert( pTabList->nSrc==1 );
  85479. /* Locate the table which we want to delete. This table has to be
  85480. ** put in an SrcList structure because some of the subroutines we
  85481. ** will be calling are designed to work with multiple tables and expect
  85482. ** an SrcList* parameter instead of just a Table* parameter.
  85483. */
  85484. pTab = sqlite3SrcListLookup(pParse, pTabList);
  85485. if( pTab==0 ) goto delete_from_cleanup;
  85486. /* Figure out if we have any triggers and if the table being
  85487. ** deleted from is a view
  85488. */
  85489. #ifndef SQLITE_OMIT_TRIGGER
  85490. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  85491. isView = pTab->pSelect!=0;
  85492. #else
  85493. # define pTrigger 0
  85494. # define isView 0
  85495. #endif
  85496. #ifdef SQLITE_OMIT_VIEW
  85497. # undef isView
  85498. # define isView 0
  85499. #endif
  85500. /* If pTab is really a view, make sure it has been initialized.
  85501. */
  85502. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  85503. goto delete_from_cleanup;
  85504. }
  85505. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  85506. goto delete_from_cleanup;
  85507. }
  85508. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85509. assert( iDb<db->nDb );
  85510. zDb = db->aDb[iDb].zName;
  85511. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  85512. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  85513. if( rcauth==SQLITE_DENY ){
  85514. goto delete_from_cleanup;
  85515. }
  85516. assert(!isView || pTrigger);
  85517. /* Assign cursor number to the table and all its indices.
  85518. */
  85519. assert( pTabList->nSrc==1 );
  85520. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  85521. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85522. pParse->nTab++;
  85523. }
  85524. /* Start the view context
  85525. */
  85526. if( isView ){
  85527. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  85528. }
  85529. /* Begin generating code.
  85530. */
  85531. v = sqlite3GetVdbe(pParse);
  85532. if( v==0 ){
  85533. goto delete_from_cleanup;
  85534. }
  85535. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  85536. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85537. /* If we are trying to delete from a view, realize that view into
  85538. ** a ephemeral table.
  85539. */
  85540. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  85541. if( isView ){
  85542. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  85543. }
  85544. #endif
  85545. /* Resolve the column names in the WHERE clause.
  85546. */
  85547. memset(&sNC, 0, sizeof(sNC));
  85548. sNC.pParse = pParse;
  85549. sNC.pSrcList = pTabList;
  85550. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  85551. goto delete_from_cleanup;
  85552. }
  85553. /* Initialize the counter of the number of rows deleted, if
  85554. ** we are counting rows.
  85555. */
  85556. if( db->flags & SQLITE_CountRows ){
  85557. memCnt = ++pParse->nMem;
  85558. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  85559. }
  85560. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  85561. /* Special case: A DELETE without a WHERE clause deletes everything.
  85562. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  85563. ** this optimization caused the row change count (the value returned by
  85564. ** API function sqlite3_count_changes) to be set incorrectly. */
  85565. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  85566. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  85567. ){
  85568. assert( !isView );
  85569. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  85570. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  85571. pTab->zName, P4_STATIC);
  85572. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85573. assert( pIdx->pSchema==pTab->pSchema );
  85574. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  85575. }
  85576. }else
  85577. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  85578. /* The usual case: There is a WHERE clause so we have to scan through
  85579. ** the table and pick which records to delete.
  85580. */
  85581. {
  85582. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  85583. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  85584. int regRowid; /* Actual register containing rowids */
  85585. /* Collect rowids of every row to be deleted.
  85586. */
  85587. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  85588. pWInfo = sqlite3WhereBegin(
  85589. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  85590. );
  85591. if( pWInfo==0 ) goto delete_from_cleanup;
  85592. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  85593. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  85594. if( db->flags & SQLITE_CountRows ){
  85595. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  85596. }
  85597. sqlite3WhereEnd(pWInfo);
  85598. /* Delete every item whose key was written to the list during the
  85599. ** database scan. We have to delete items after the scan is complete
  85600. ** because deleting an item can change the scan order. */
  85601. end = sqlite3VdbeMakeLabel(v);
  85602. /* Unless this is a view, open cursors for the table we are
  85603. ** deleting from and all its indices. If this is a view, then the
  85604. ** only effect this statement has is to fire the INSTEAD OF
  85605. ** triggers. */
  85606. if( !isView ){
  85607. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  85608. }
  85609. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  85610. /* Delete the row */
  85611. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85612. if( IsVirtual(pTab) ){
  85613. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  85614. sqlite3VtabMakeWritable(pParse, pTab);
  85615. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  85616. sqlite3VdbeChangeP5(v, OE_Abort);
  85617. sqlite3MayAbort(pParse);
  85618. }else
  85619. #endif
  85620. {
  85621. int count = (pParse->nested==0); /* True to count changes */
  85622. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  85623. }
  85624. /* End of the delete loop */
  85625. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  85626. sqlite3VdbeResolveLabel(v, end);
  85627. /* Close the cursors open on the table and its indexes. */
  85628. if( !isView && !IsVirtual(pTab) ){
  85629. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  85630. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  85631. }
  85632. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  85633. }
  85634. }
  85635. /* Update the sqlite_sequence table by storing the content of the
  85636. ** maximum rowid counter values recorded while inserting into
  85637. ** autoincrement tables.
  85638. */
  85639. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  85640. sqlite3AutoincrementEnd(pParse);
  85641. }
  85642. /* Return the number of rows that were deleted. If this routine is
  85643. ** generating code because of a call to sqlite3NestedParse(), do not
  85644. ** invoke the callback function.
  85645. */
  85646. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  85647. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  85648. sqlite3VdbeSetNumCols(v, 1);
  85649. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  85650. }
  85651. delete_from_cleanup:
  85652. sqlite3AuthContextPop(&sContext);
  85653. sqlite3SrcListDelete(db, pTabList);
  85654. sqlite3ExprDelete(db, pWhere);
  85655. return;
  85656. }
  85657. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  85658. ** thely may interfere with compilation of other functions in this file
  85659. ** (or in another file, if this file becomes part of the amalgamation). */
  85660. #ifdef isView
  85661. #undef isView
  85662. #endif
  85663. #ifdef pTrigger
  85664. #undef pTrigger
  85665. #endif
  85666. /*
  85667. ** This routine generates VDBE code that causes a single row of a
  85668. ** single table to be deleted.
  85669. **
  85670. ** The VDBE must be in a particular state when this routine is called.
  85671. ** These are the requirements:
  85672. **
  85673. ** 1. A read/write cursor pointing to pTab, the table containing the row
  85674. ** to be deleted, must be opened as cursor number $iCur.
  85675. **
  85676. ** 2. Read/write cursors for all indices of pTab must be open as
  85677. ** cursor number base+i for the i-th index.
  85678. **
  85679. ** 3. The record number of the row to be deleted must be stored in
  85680. ** memory cell iRowid.
  85681. **
  85682. ** This routine generates code to remove both the table record and all
  85683. ** index entries that point to that record.
  85684. */
  85685. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  85686. Parse *pParse, /* Parsing context */
  85687. Table *pTab, /* Table containing the row to be deleted */
  85688. int iCur, /* Cursor number for the table */
  85689. int iRowid, /* Memory cell that contains the rowid to delete */
  85690. int count, /* If non-zero, increment the row change counter */
  85691. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  85692. int onconf /* Default ON CONFLICT policy for triggers */
  85693. ){
  85694. Vdbe *v = pParse->pVdbe; /* Vdbe */
  85695. int iOld = 0; /* First register in OLD.* array */
  85696. int iLabel; /* Label resolved to end of generated code */
  85697. /* Vdbe is guaranteed to have been allocated by this stage. */
  85698. assert( v );
  85699. /* Seek cursor iCur to the row to delete. If this row no longer exists
  85700. ** (this can happen if a trigger program has already deleted it), do
  85701. ** not attempt to delete it or fire any DELETE triggers. */
  85702. iLabel = sqlite3VdbeMakeLabel(v);
  85703. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  85704. /* If there are any triggers to fire, allocate a range of registers to
  85705. ** use for the old.* references in the triggers. */
  85706. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  85707. u32 mask; /* Mask of OLD.* columns in use */
  85708. int iCol; /* Iterator used while populating OLD.* */
  85709. /* TODO: Could use temporary registers here. Also could attempt to
  85710. ** avoid copying the contents of the rowid register. */
  85711. mask = sqlite3TriggerColmask(
  85712. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  85713. );
  85714. mask |= sqlite3FkOldmask(pParse, pTab);
  85715. iOld = pParse->nMem+1;
  85716. pParse->nMem += (1 + pTab->nCol);
  85717. /* Populate the OLD.* pseudo-table register array. These values will be
  85718. ** used by any BEFORE and AFTER triggers that exist. */
  85719. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  85720. for(iCol=0; iCol<pTab->nCol; iCol++){
  85721. if( mask==0xffffffff || mask&(1<<iCol) ){
  85722. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  85723. }
  85724. }
  85725. /* Invoke BEFORE DELETE trigger programs. */
  85726. sqlite3CodeRowTrigger(pParse, pTrigger,
  85727. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  85728. );
  85729. /* Seek the cursor to the row to be deleted again. It may be that
  85730. ** the BEFORE triggers coded above have already removed the row
  85731. ** being deleted. Do not attempt to delete the row a second time, and
  85732. ** do not fire AFTER triggers. */
  85733. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  85734. /* Do FK processing. This call checks that any FK constraints that
  85735. ** refer to this table (i.e. constraints attached to other tables)
  85736. ** are not violated by deleting this row. */
  85737. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  85738. }
  85739. /* Delete the index and table entries. Skip this step if pTab is really
  85740. ** a view (in which case the only effect of the DELETE statement is to
  85741. ** fire the INSTEAD OF triggers). */
  85742. if( pTab->pSelect==0 ){
  85743. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  85744. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  85745. if( count ){
  85746. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  85747. }
  85748. }
  85749. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  85750. ** handle rows (possibly in other tables) that refer via a foreign key
  85751. ** to the row just deleted. */
  85752. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  85753. /* Invoke AFTER DELETE trigger programs. */
  85754. sqlite3CodeRowTrigger(pParse, pTrigger,
  85755. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  85756. );
  85757. /* Jump here if the row had already been deleted before any BEFORE
  85758. ** trigger programs were invoked. Or if a trigger program throws a
  85759. ** RAISE(IGNORE) exception. */
  85760. sqlite3VdbeResolveLabel(v, iLabel);
  85761. }
  85762. /*
  85763. ** This routine generates VDBE code that causes the deletion of all
  85764. ** index entries associated with a single row of a single table.
  85765. **
  85766. ** The VDBE must be in a particular state when this routine is called.
  85767. ** These are the requirements:
  85768. **
  85769. ** 1. A read/write cursor pointing to pTab, the table containing the row
  85770. ** to be deleted, must be opened as cursor number "iCur".
  85771. **
  85772. ** 2. Read/write cursors for all indices of pTab must be open as
  85773. ** cursor number iCur+i for the i-th index.
  85774. **
  85775. ** 3. The "iCur" cursor must be pointing to the row that is to be
  85776. ** deleted.
  85777. */
  85778. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  85779. Parse *pParse, /* Parsing and code generating context */
  85780. Table *pTab, /* Table containing the row to be deleted */
  85781. int iCur, /* Cursor number for the table */
  85782. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  85783. ){
  85784. int i;
  85785. Index *pIdx;
  85786. int r1;
  85787. int iPartIdxLabel;
  85788. Vdbe *v = pParse->pVdbe;
  85789. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  85790. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  85791. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  85792. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  85793. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  85794. }
  85795. }
  85796. /*
  85797. ** Generate code that will assemble an index key and put it in register
  85798. ** regOut. The key with be for index pIdx which is an index on pTab.
  85799. ** iCur is the index of a cursor open on the pTab table and pointing to
  85800. ** the entry that needs indexing.
  85801. **
  85802. ** Return a register number which is the first in a block of
  85803. ** registers that holds the elements of the index key. The
  85804. ** block of registers has already been deallocated by the time
  85805. ** this routine returns.
  85806. **
  85807. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  85808. ** to that label if pIdx is a partial index that should be skipped.
  85809. ** A partial index should be skipped if its WHERE clause evaluates
  85810. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  85811. ** will be set to zero which is an empty label that is ignored by
  85812. ** sqlite3VdbeResolveLabel().
  85813. */
  85814. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  85815. Parse *pParse, /* Parsing context */
  85816. Index *pIdx, /* The index for which to generate a key */
  85817. int iCur, /* Cursor number for the pIdx->pTable table */
  85818. int regOut, /* Write the new index key to this register */
  85819. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  85820. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  85821. ){
  85822. Vdbe *v = pParse->pVdbe;
  85823. int j;
  85824. Table *pTab = pIdx->pTable;
  85825. int regBase;
  85826. int nCol;
  85827. if( piPartIdxLabel ){
  85828. if( pIdx->pPartIdxWhere ){
  85829. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  85830. pParse->iPartIdxTab = iCur;
  85831. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  85832. SQLITE_JUMPIFNULL);
  85833. }else{
  85834. *piPartIdxLabel = 0;
  85835. }
  85836. }
  85837. nCol = pIdx->nColumn;
  85838. regBase = sqlite3GetTempRange(pParse, nCol+1);
  85839. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  85840. for(j=0; j<nCol; j++){
  85841. int idx = pIdx->aiColumn[j];
  85842. if( idx==pTab->iPKey ){
  85843. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  85844. }else{
  85845. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  85846. sqlite3ColumnDefault(v, pTab, idx, -1);
  85847. }
  85848. }
  85849. if( doMakeRec ){
  85850. const char *zAff;
  85851. if( pTab->pSelect
  85852. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  85853. ){
  85854. zAff = 0;
  85855. }else{
  85856. zAff = sqlite3IndexAffinityStr(v, pIdx);
  85857. }
  85858. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  85859. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  85860. }
  85861. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  85862. return regBase;
  85863. }
  85864. /************** End of delete.c **********************************************/
  85865. /************** Begin file func.c ********************************************/
  85866. /*
  85867. ** 2002 February 23
  85868. **
  85869. ** The author disclaims copyright to this source code. In place of
  85870. ** a legal notice, here is a blessing:
  85871. **
  85872. ** May you do good and not evil.
  85873. ** May you find forgiveness for yourself and forgive others.
  85874. ** May you share freely, never taking more than you give.
  85875. **
  85876. *************************************************************************
  85877. ** This file contains the C functions that implement various SQL
  85878. ** functions of SQLite.
  85879. **
  85880. ** There is only one exported symbol in this file - the function
  85881. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  85882. ** All other code has file scope.
  85883. */
  85884. /* #include <stdlib.h> */
  85885. /* #include <assert.h> */
  85886. /*
  85887. ** Return the collating function associated with a function.
  85888. */
  85889. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  85890. return context->pColl;
  85891. }
  85892. /*
  85893. ** Indicate that the accumulator load should be skipped on this
  85894. ** iteration of the aggregate loop.
  85895. */
  85896. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  85897. context->skipFlag = 1;
  85898. }
  85899. /*
  85900. ** Implementation of the non-aggregate min() and max() functions
  85901. */
  85902. static void minmaxFunc(
  85903. sqlite3_context *context,
  85904. int argc,
  85905. sqlite3_value **argv
  85906. ){
  85907. int i;
  85908. int mask; /* 0 for min() or 0xffffffff for max() */
  85909. int iBest;
  85910. CollSeq *pColl;
  85911. assert( argc>1 );
  85912. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  85913. pColl = sqlite3GetFuncCollSeq(context);
  85914. assert( pColl );
  85915. assert( mask==-1 || mask==0 );
  85916. iBest = 0;
  85917. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  85918. for(i=1; i<argc; i++){
  85919. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  85920. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  85921. testcase( mask==0 );
  85922. iBest = i;
  85923. }
  85924. }
  85925. sqlite3_result_value(context, argv[iBest]);
  85926. }
  85927. /*
  85928. ** Return the type of the argument.
  85929. */
  85930. static void typeofFunc(
  85931. sqlite3_context *context,
  85932. int NotUsed,
  85933. sqlite3_value **argv
  85934. ){
  85935. const char *z = 0;
  85936. UNUSED_PARAMETER(NotUsed);
  85937. switch( sqlite3_value_type(argv[0]) ){
  85938. case SQLITE_INTEGER: z = "integer"; break;
  85939. case SQLITE_TEXT: z = "text"; break;
  85940. case SQLITE_FLOAT: z = "real"; break;
  85941. case SQLITE_BLOB: z = "blob"; break;
  85942. default: z = "null"; break;
  85943. }
  85944. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  85945. }
  85946. /*
  85947. ** Implementation of the length() function
  85948. */
  85949. static void lengthFunc(
  85950. sqlite3_context *context,
  85951. int argc,
  85952. sqlite3_value **argv
  85953. ){
  85954. int len;
  85955. assert( argc==1 );
  85956. UNUSED_PARAMETER(argc);
  85957. switch( sqlite3_value_type(argv[0]) ){
  85958. case SQLITE_BLOB:
  85959. case SQLITE_INTEGER:
  85960. case SQLITE_FLOAT: {
  85961. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  85962. break;
  85963. }
  85964. case SQLITE_TEXT: {
  85965. const unsigned char *z = sqlite3_value_text(argv[0]);
  85966. if( z==0 ) return;
  85967. len = 0;
  85968. while( *z ){
  85969. len++;
  85970. SQLITE_SKIP_UTF8(z);
  85971. }
  85972. sqlite3_result_int(context, len);
  85973. break;
  85974. }
  85975. default: {
  85976. sqlite3_result_null(context);
  85977. break;
  85978. }
  85979. }
  85980. }
  85981. /*
  85982. ** Implementation of the abs() function.
  85983. **
  85984. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  85985. ** the numeric argument X.
  85986. */
  85987. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  85988. assert( argc==1 );
  85989. UNUSED_PARAMETER(argc);
  85990. switch( sqlite3_value_type(argv[0]) ){
  85991. case SQLITE_INTEGER: {
  85992. i64 iVal = sqlite3_value_int64(argv[0]);
  85993. if( iVal<0 ){
  85994. if( (iVal<<1)==0 ){
  85995. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  85996. ** abs(X) throws an integer overflow error since there is no
  85997. ** equivalent positive 64-bit two complement value. */
  85998. sqlite3_result_error(context, "integer overflow", -1);
  85999. return;
  86000. }
  86001. iVal = -iVal;
  86002. }
  86003. sqlite3_result_int64(context, iVal);
  86004. break;
  86005. }
  86006. case SQLITE_NULL: {
  86007. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  86008. sqlite3_result_null(context);
  86009. break;
  86010. }
  86011. default: {
  86012. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  86013. ** something that can be converted into a number, we have:
  86014. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  86015. ** cannot be converted to a numeric value.
  86016. */
  86017. double rVal = sqlite3_value_double(argv[0]);
  86018. if( rVal<0 ) rVal = -rVal;
  86019. sqlite3_result_double(context, rVal);
  86020. break;
  86021. }
  86022. }
  86023. }
  86024. /*
  86025. ** Implementation of the instr() function.
  86026. **
  86027. ** instr(haystack,needle) finds the first occurrence of needle
  86028. ** in haystack and returns the number of previous characters plus 1,
  86029. ** or 0 if needle does not occur within haystack.
  86030. **
  86031. ** If both haystack and needle are BLOBs, then the result is one more than
  86032. ** the number of bytes in haystack prior to the first occurrence of needle,
  86033. ** or 0 if needle never occurs in haystack.
  86034. */
  86035. static void instrFunc(
  86036. sqlite3_context *context,
  86037. int argc,
  86038. sqlite3_value **argv
  86039. ){
  86040. const unsigned char *zHaystack;
  86041. const unsigned char *zNeedle;
  86042. int nHaystack;
  86043. int nNeedle;
  86044. int typeHaystack, typeNeedle;
  86045. int N = 1;
  86046. int isText;
  86047. UNUSED_PARAMETER(argc);
  86048. typeHaystack = sqlite3_value_type(argv[0]);
  86049. typeNeedle = sqlite3_value_type(argv[1]);
  86050. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  86051. nHaystack = sqlite3_value_bytes(argv[0]);
  86052. nNeedle = sqlite3_value_bytes(argv[1]);
  86053. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  86054. zHaystack = sqlite3_value_blob(argv[0]);
  86055. zNeedle = sqlite3_value_blob(argv[1]);
  86056. isText = 0;
  86057. }else{
  86058. zHaystack = sqlite3_value_text(argv[0]);
  86059. zNeedle = sqlite3_value_text(argv[1]);
  86060. isText = 1;
  86061. }
  86062. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  86063. N++;
  86064. do{
  86065. nHaystack--;
  86066. zHaystack++;
  86067. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  86068. }
  86069. if( nNeedle>nHaystack ) N = 0;
  86070. sqlite3_result_int(context, N);
  86071. }
  86072. /*
  86073. ** Implementation of the substr() function.
  86074. **
  86075. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  86076. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  86077. ** of x. If x is text, then we actually count UTF-8 characters.
  86078. ** If x is a blob, then we count bytes.
  86079. **
  86080. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  86081. **
  86082. ** If p2 is negative, return the p2 characters preceding p1.
  86083. */
  86084. static void substrFunc(
  86085. sqlite3_context *context,
  86086. int argc,
  86087. sqlite3_value **argv
  86088. ){
  86089. const unsigned char *z;
  86090. const unsigned char *z2;
  86091. int len;
  86092. int p0type;
  86093. i64 p1, p2;
  86094. int negP2 = 0;
  86095. assert( argc==3 || argc==2 );
  86096. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  86097. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  86098. ){
  86099. return;
  86100. }
  86101. p0type = sqlite3_value_type(argv[0]);
  86102. p1 = sqlite3_value_int(argv[1]);
  86103. if( p0type==SQLITE_BLOB ){
  86104. len = sqlite3_value_bytes(argv[0]);
  86105. z = sqlite3_value_blob(argv[0]);
  86106. if( z==0 ) return;
  86107. assert( len==sqlite3_value_bytes(argv[0]) );
  86108. }else{
  86109. z = sqlite3_value_text(argv[0]);
  86110. if( z==0 ) return;
  86111. len = 0;
  86112. if( p1<0 ){
  86113. for(z2=z; *z2; len++){
  86114. SQLITE_SKIP_UTF8(z2);
  86115. }
  86116. }
  86117. }
  86118. if( argc==3 ){
  86119. p2 = sqlite3_value_int(argv[2]);
  86120. if( p2<0 ){
  86121. p2 = -p2;
  86122. negP2 = 1;
  86123. }
  86124. }else{
  86125. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  86126. }
  86127. if( p1<0 ){
  86128. p1 += len;
  86129. if( p1<0 ){
  86130. p2 += p1;
  86131. if( p2<0 ) p2 = 0;
  86132. p1 = 0;
  86133. }
  86134. }else if( p1>0 ){
  86135. p1--;
  86136. }else if( p2>0 ){
  86137. p2--;
  86138. }
  86139. if( negP2 ){
  86140. p1 -= p2;
  86141. if( p1<0 ){
  86142. p2 += p1;
  86143. p1 = 0;
  86144. }
  86145. }
  86146. assert( p1>=0 && p2>=0 );
  86147. if( p0type!=SQLITE_BLOB ){
  86148. while( *z && p1 ){
  86149. SQLITE_SKIP_UTF8(z);
  86150. p1--;
  86151. }
  86152. for(z2=z; *z2 && p2; p2--){
  86153. SQLITE_SKIP_UTF8(z2);
  86154. }
  86155. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  86156. }else{
  86157. if( p1+p2>len ){
  86158. p2 = len-p1;
  86159. if( p2<0 ) p2 = 0;
  86160. }
  86161. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  86162. }
  86163. }
  86164. /*
  86165. ** Implementation of the round() function
  86166. */
  86167. #ifndef SQLITE_OMIT_FLOATING_POINT
  86168. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86169. int n = 0;
  86170. double r;
  86171. char *zBuf;
  86172. assert( argc==1 || argc==2 );
  86173. if( argc==2 ){
  86174. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  86175. n = sqlite3_value_int(argv[1]);
  86176. if( n>30 ) n = 30;
  86177. if( n<0 ) n = 0;
  86178. }
  86179. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  86180. r = sqlite3_value_double(argv[0]);
  86181. /* If Y==0 and X will fit in a 64-bit int,
  86182. ** handle the rounding directly,
  86183. ** otherwise use printf.
  86184. */
  86185. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  86186. r = (double)((sqlite_int64)(r+0.5));
  86187. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  86188. r = -(double)((sqlite_int64)((-r)+0.5));
  86189. }else{
  86190. zBuf = sqlite3_mprintf("%.*f",n,r);
  86191. if( zBuf==0 ){
  86192. sqlite3_result_error_nomem(context);
  86193. return;
  86194. }
  86195. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  86196. sqlite3_free(zBuf);
  86197. }
  86198. sqlite3_result_double(context, r);
  86199. }
  86200. #endif
  86201. /*
  86202. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  86203. ** allocation fails, call sqlite3_result_error_nomem() to notify
  86204. ** the database handle that malloc() has failed and return NULL.
  86205. ** If nByte is larger than the maximum string or blob length, then
  86206. ** raise an SQLITE_TOOBIG exception and return NULL.
  86207. */
  86208. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  86209. char *z;
  86210. sqlite3 *db = sqlite3_context_db_handle(context);
  86211. assert( nByte>0 );
  86212. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86213. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  86214. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86215. sqlite3_result_error_toobig(context);
  86216. z = 0;
  86217. }else{
  86218. z = sqlite3Malloc((int)nByte);
  86219. if( !z ){
  86220. sqlite3_result_error_nomem(context);
  86221. }
  86222. }
  86223. return z;
  86224. }
  86225. /*
  86226. ** Implementation of the upper() and lower() SQL functions.
  86227. */
  86228. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86229. char *z1;
  86230. const char *z2;
  86231. int i, n;
  86232. UNUSED_PARAMETER(argc);
  86233. z2 = (char*)sqlite3_value_text(argv[0]);
  86234. n = sqlite3_value_bytes(argv[0]);
  86235. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  86236. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  86237. if( z2 ){
  86238. z1 = contextMalloc(context, ((i64)n)+1);
  86239. if( z1 ){
  86240. for(i=0; i<n; i++){
  86241. z1[i] = (char)sqlite3Toupper(z2[i]);
  86242. }
  86243. sqlite3_result_text(context, z1, n, sqlite3_free);
  86244. }
  86245. }
  86246. }
  86247. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86248. char *z1;
  86249. const char *z2;
  86250. int i, n;
  86251. UNUSED_PARAMETER(argc);
  86252. z2 = (char*)sqlite3_value_text(argv[0]);
  86253. n = sqlite3_value_bytes(argv[0]);
  86254. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  86255. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  86256. if( z2 ){
  86257. z1 = contextMalloc(context, ((i64)n)+1);
  86258. if( z1 ){
  86259. for(i=0; i<n; i++){
  86260. z1[i] = sqlite3Tolower(z2[i]);
  86261. }
  86262. sqlite3_result_text(context, z1, n, sqlite3_free);
  86263. }
  86264. }
  86265. }
  86266. /*
  86267. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  86268. ** as VDBE code so that unused argument values do not have to be computed.
  86269. ** However, we still need some kind of function implementation for this
  86270. ** routines in the function table. The noopFunc macro provides this.
  86271. ** noopFunc will never be called so it doesn't matter what the implementation
  86272. ** is. We might as well use the "version()" function as a substitute.
  86273. */
  86274. #define noopFunc versionFunc /* Substitute function - never called */
  86275. /*
  86276. ** Implementation of random(). Return a random integer.
  86277. */
  86278. static void randomFunc(
  86279. sqlite3_context *context,
  86280. int NotUsed,
  86281. sqlite3_value **NotUsed2
  86282. ){
  86283. sqlite_int64 r;
  86284. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86285. sqlite3_randomness(sizeof(r), &r);
  86286. if( r<0 ){
  86287. /* We need to prevent a random number of 0x8000000000000000
  86288. ** (or -9223372036854775808) since when you do abs() of that
  86289. ** number of you get the same value back again. To do this
  86290. ** in a way that is testable, mask the sign bit off of negative
  86291. ** values, resulting in a positive value. Then take the
  86292. ** 2s complement of that positive value. The end result can
  86293. ** therefore be no less than -9223372036854775807.
  86294. */
  86295. r = -(r & LARGEST_INT64);
  86296. }
  86297. sqlite3_result_int64(context, r);
  86298. }
  86299. /*
  86300. ** Implementation of randomblob(N). Return a random blob
  86301. ** that is N bytes long.
  86302. */
  86303. static void randomBlob(
  86304. sqlite3_context *context,
  86305. int argc,
  86306. sqlite3_value **argv
  86307. ){
  86308. int n;
  86309. unsigned char *p;
  86310. assert( argc==1 );
  86311. UNUSED_PARAMETER(argc);
  86312. n = sqlite3_value_int(argv[0]);
  86313. if( n<1 ){
  86314. n = 1;
  86315. }
  86316. p = contextMalloc(context, n);
  86317. if( p ){
  86318. sqlite3_randomness(n, p);
  86319. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  86320. }
  86321. }
  86322. /*
  86323. ** Implementation of the last_insert_rowid() SQL function. The return
  86324. ** value is the same as the sqlite3_last_insert_rowid() API function.
  86325. */
  86326. static void last_insert_rowid(
  86327. sqlite3_context *context,
  86328. int NotUsed,
  86329. sqlite3_value **NotUsed2
  86330. ){
  86331. sqlite3 *db = sqlite3_context_db_handle(context);
  86332. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86333. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  86334. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  86335. ** function. */
  86336. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  86337. }
  86338. /*
  86339. ** Implementation of the changes() SQL function.
  86340. **
  86341. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  86342. ** around the sqlite3_changes() C/C++ function and hence follows the same
  86343. ** rules for counting changes.
  86344. */
  86345. static void changes(
  86346. sqlite3_context *context,
  86347. int NotUsed,
  86348. sqlite3_value **NotUsed2
  86349. ){
  86350. sqlite3 *db = sqlite3_context_db_handle(context);
  86351. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86352. sqlite3_result_int(context, sqlite3_changes(db));
  86353. }
  86354. /*
  86355. ** Implementation of the total_changes() SQL function. The return value is
  86356. ** the same as the sqlite3_total_changes() API function.
  86357. */
  86358. static void total_changes(
  86359. sqlite3_context *context,
  86360. int NotUsed,
  86361. sqlite3_value **NotUsed2
  86362. ){
  86363. sqlite3 *db = sqlite3_context_db_handle(context);
  86364. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86365. /* IMP: R-52756-41993 This function is a wrapper around the
  86366. ** sqlite3_total_changes() C/C++ interface. */
  86367. sqlite3_result_int(context, sqlite3_total_changes(db));
  86368. }
  86369. /*
  86370. ** A structure defining how to do GLOB-style comparisons.
  86371. */
  86372. struct compareInfo {
  86373. u8 matchAll;
  86374. u8 matchOne;
  86375. u8 matchSet;
  86376. u8 noCase;
  86377. };
  86378. /*
  86379. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  86380. ** character is exactly one byte in size. Also, all characters are
  86381. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  86382. ** whereas only characters less than 0x80 do in ASCII.
  86383. */
  86384. #if defined(SQLITE_EBCDIC)
  86385. # define sqlite3Utf8Read(A) (*((*A)++))
  86386. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  86387. #else
  86388. # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  86389. #endif
  86390. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  86391. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  86392. ** case. Thus 'a' LIKE 'A' would be true. */
  86393. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  86394. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  86395. ** is case sensitive causing 'a' LIKE 'A' to be false */
  86396. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  86397. /*
  86398. ** Compare two UTF-8 strings for equality where the first string can
  86399. ** potentially be a "glob" expression. Return true (1) if they
  86400. ** are the same and false (0) if they are different.
  86401. **
  86402. ** Globbing rules:
  86403. **
  86404. ** '*' Matches any sequence of zero or more characters.
  86405. **
  86406. ** '?' Matches exactly one character.
  86407. **
  86408. ** [...] Matches one character from the enclosed list of
  86409. ** characters.
  86410. **
  86411. ** [^...] Matches one character not in the enclosed list.
  86412. **
  86413. ** With the [...] and [^...] matching, a ']' character can be included
  86414. ** in the list by making it the first character after '[' or '^'. A
  86415. ** range of characters can be specified using '-'. Example:
  86416. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  86417. ** it the last character in the list.
  86418. **
  86419. ** This routine is usually quick, but can be N**2 in the worst case.
  86420. **
  86421. ** Hints: to match '*' or '?', put them in "[]". Like this:
  86422. **
  86423. ** abc[*]xyz Matches "abc*xyz" only
  86424. */
  86425. static int patternCompare(
  86426. const u8 *zPattern, /* The glob pattern */
  86427. const u8 *zString, /* The string to compare against the glob */
  86428. const struct compareInfo *pInfo, /* Information about how to do the compare */
  86429. u32 esc /* The escape character */
  86430. ){
  86431. u32 c, c2;
  86432. int invert;
  86433. int seen;
  86434. u8 matchOne = pInfo->matchOne;
  86435. u8 matchAll = pInfo->matchAll;
  86436. u8 matchSet = pInfo->matchSet;
  86437. u8 noCase = pInfo->noCase;
  86438. int prevEscape = 0; /* True if the previous character was 'escape' */
  86439. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  86440. if( c==matchAll && !prevEscape ){
  86441. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  86442. || c == matchOne ){
  86443. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  86444. return 0;
  86445. }
  86446. }
  86447. if( c==0 ){
  86448. return 1;
  86449. }else if( c==esc ){
  86450. c = sqlite3Utf8Read(&zPattern);
  86451. if( c==0 ){
  86452. return 0;
  86453. }
  86454. }else if( c==matchSet ){
  86455. assert( esc==0 ); /* This is GLOB, not LIKE */
  86456. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  86457. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  86458. SQLITE_SKIP_UTF8(zString);
  86459. }
  86460. return *zString!=0;
  86461. }
  86462. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  86463. if( noCase ){
  86464. GlobUpperToLower(c2);
  86465. GlobUpperToLower(c);
  86466. while( c2 != 0 && c2 != c ){
  86467. c2 = sqlite3Utf8Read(&zString);
  86468. GlobUpperToLower(c2);
  86469. }
  86470. }else{
  86471. while( c2 != 0 && c2 != c ){
  86472. c2 = sqlite3Utf8Read(&zString);
  86473. }
  86474. }
  86475. if( c2==0 ) return 0;
  86476. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  86477. }
  86478. return 0;
  86479. }else if( c==matchOne && !prevEscape ){
  86480. if( sqlite3Utf8Read(&zString)==0 ){
  86481. return 0;
  86482. }
  86483. }else if( c==matchSet ){
  86484. u32 prior_c = 0;
  86485. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  86486. seen = 0;
  86487. invert = 0;
  86488. c = sqlite3Utf8Read(&zString);
  86489. if( c==0 ) return 0;
  86490. c2 = sqlite3Utf8Read(&zPattern);
  86491. if( c2=='^' ){
  86492. invert = 1;
  86493. c2 = sqlite3Utf8Read(&zPattern);
  86494. }
  86495. if( c2==']' ){
  86496. if( c==']' ) seen = 1;
  86497. c2 = sqlite3Utf8Read(&zPattern);
  86498. }
  86499. while( c2 && c2!=']' ){
  86500. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  86501. c2 = sqlite3Utf8Read(&zPattern);
  86502. if( c>=prior_c && c<=c2 ) seen = 1;
  86503. prior_c = 0;
  86504. }else{
  86505. if( c==c2 ){
  86506. seen = 1;
  86507. }
  86508. prior_c = c2;
  86509. }
  86510. c2 = sqlite3Utf8Read(&zPattern);
  86511. }
  86512. if( c2==0 || (seen ^ invert)==0 ){
  86513. return 0;
  86514. }
  86515. }else if( esc==c && !prevEscape ){
  86516. prevEscape = 1;
  86517. }else{
  86518. c2 = sqlite3Utf8Read(&zString);
  86519. if( noCase ){
  86520. GlobUpperToLower(c);
  86521. GlobUpperToLower(c2);
  86522. }
  86523. if( c!=c2 ){
  86524. return 0;
  86525. }
  86526. prevEscape = 0;
  86527. }
  86528. }
  86529. return *zString==0;
  86530. }
  86531. /*
  86532. ** The sqlite3_strglob() interface.
  86533. */
  86534. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  86535. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  86536. }
  86537. /*
  86538. ** Count the number of times that the LIKE operator (or GLOB which is
  86539. ** just a variation of LIKE) gets called. This is used for testing
  86540. ** only.
  86541. */
  86542. #ifdef SQLITE_TEST
  86543. SQLITE_API int sqlite3_like_count = 0;
  86544. #endif
  86545. /*
  86546. ** Implementation of the like() SQL function. This function implements
  86547. ** the build-in LIKE operator. The first argument to the function is the
  86548. ** pattern and the second argument is the string. So, the SQL statements:
  86549. **
  86550. ** A LIKE B
  86551. **
  86552. ** is implemented as like(B,A).
  86553. **
  86554. ** This same function (with a different compareInfo structure) computes
  86555. ** the GLOB operator.
  86556. */
  86557. static void likeFunc(
  86558. sqlite3_context *context,
  86559. int argc,
  86560. sqlite3_value **argv
  86561. ){
  86562. const unsigned char *zA, *zB;
  86563. u32 escape = 0;
  86564. int nPat;
  86565. sqlite3 *db = sqlite3_context_db_handle(context);
  86566. zB = sqlite3_value_text(argv[0]);
  86567. zA = sqlite3_value_text(argv[1]);
  86568. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  86569. ** of deep recursion and N*N behavior in patternCompare().
  86570. */
  86571. nPat = sqlite3_value_bytes(argv[0]);
  86572. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  86573. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  86574. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  86575. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  86576. return;
  86577. }
  86578. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  86579. if( argc==3 ){
  86580. /* The escape character string must consist of a single UTF-8 character.
  86581. ** Otherwise, return an error.
  86582. */
  86583. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  86584. if( zEsc==0 ) return;
  86585. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  86586. sqlite3_result_error(context,
  86587. "ESCAPE expression must be a single character", -1);
  86588. return;
  86589. }
  86590. escape = sqlite3Utf8Read(&zEsc);
  86591. }
  86592. if( zA && zB ){
  86593. struct compareInfo *pInfo = sqlite3_user_data(context);
  86594. #ifdef SQLITE_TEST
  86595. sqlite3_like_count++;
  86596. #endif
  86597. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  86598. }
  86599. }
  86600. /*
  86601. ** Implementation of the NULLIF(x,y) function. The result is the first
  86602. ** argument if the arguments are different. The result is NULL if the
  86603. ** arguments are equal to each other.
  86604. */
  86605. static void nullifFunc(
  86606. sqlite3_context *context,
  86607. int NotUsed,
  86608. sqlite3_value **argv
  86609. ){
  86610. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  86611. UNUSED_PARAMETER(NotUsed);
  86612. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  86613. sqlite3_result_value(context, argv[0]);
  86614. }
  86615. }
  86616. /*
  86617. ** Implementation of the sqlite_version() function. The result is the version
  86618. ** of the SQLite library that is running.
  86619. */
  86620. static void versionFunc(
  86621. sqlite3_context *context,
  86622. int NotUsed,
  86623. sqlite3_value **NotUsed2
  86624. ){
  86625. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86626. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  86627. ** sqlite3_libversion() C-interface. */
  86628. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  86629. }
  86630. /*
  86631. ** Implementation of the sqlite_source_id() function. The result is a string
  86632. ** that identifies the particular version of the source code used to build
  86633. ** SQLite.
  86634. */
  86635. static void sourceidFunc(
  86636. sqlite3_context *context,
  86637. int NotUsed,
  86638. sqlite3_value **NotUsed2
  86639. ){
  86640. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86641. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  86642. ** sqlite3_sourceid() C interface. */
  86643. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  86644. }
  86645. /*
  86646. ** Implementation of the sqlite_log() function. This is a wrapper around
  86647. ** sqlite3_log(). The return value is NULL. The function exists purely for
  86648. ** its side-effects.
  86649. */
  86650. static void errlogFunc(
  86651. sqlite3_context *context,
  86652. int argc,
  86653. sqlite3_value **argv
  86654. ){
  86655. UNUSED_PARAMETER(argc);
  86656. UNUSED_PARAMETER(context);
  86657. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  86658. }
  86659. /*
  86660. ** Implementation of the sqlite_compileoption_used() function.
  86661. ** The result is an integer that identifies if the compiler option
  86662. ** was used to build SQLite.
  86663. */
  86664. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  86665. static void compileoptionusedFunc(
  86666. sqlite3_context *context,
  86667. int argc,
  86668. sqlite3_value **argv
  86669. ){
  86670. const char *zOptName;
  86671. assert( argc==1 );
  86672. UNUSED_PARAMETER(argc);
  86673. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  86674. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  86675. ** function.
  86676. */
  86677. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  86678. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  86679. }
  86680. }
  86681. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  86682. /*
  86683. ** Implementation of the sqlite_compileoption_get() function.
  86684. ** The result is a string that identifies the compiler options
  86685. ** used to build SQLite.
  86686. */
  86687. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  86688. static void compileoptiongetFunc(
  86689. sqlite3_context *context,
  86690. int argc,
  86691. sqlite3_value **argv
  86692. ){
  86693. int n;
  86694. assert( argc==1 );
  86695. UNUSED_PARAMETER(argc);
  86696. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  86697. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  86698. */
  86699. n = sqlite3_value_int(argv[0]);
  86700. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  86701. }
  86702. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  86703. /* Array for converting from half-bytes (nybbles) into ASCII hex
  86704. ** digits. */
  86705. static const char hexdigits[] = {
  86706. '0', '1', '2', '3', '4', '5', '6', '7',
  86707. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  86708. };
  86709. /*
  86710. ** Implementation of the QUOTE() function. This function takes a single
  86711. ** argument. If the argument is numeric, the return value is the same as
  86712. ** the argument. If the argument is NULL, the return value is the string
  86713. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  86714. ** single-quote escapes.
  86715. */
  86716. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86717. assert( argc==1 );
  86718. UNUSED_PARAMETER(argc);
  86719. switch( sqlite3_value_type(argv[0]) ){
  86720. case SQLITE_FLOAT: {
  86721. double r1, r2;
  86722. char zBuf[50];
  86723. r1 = sqlite3_value_double(argv[0]);
  86724. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  86725. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  86726. if( r1!=r2 ){
  86727. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  86728. }
  86729. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  86730. break;
  86731. }
  86732. case SQLITE_INTEGER: {
  86733. sqlite3_result_value(context, argv[0]);
  86734. break;
  86735. }
  86736. case SQLITE_BLOB: {
  86737. char *zText = 0;
  86738. char const *zBlob = sqlite3_value_blob(argv[0]);
  86739. int nBlob = sqlite3_value_bytes(argv[0]);
  86740. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  86741. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  86742. if( zText ){
  86743. int i;
  86744. for(i=0; i<nBlob; i++){
  86745. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  86746. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  86747. }
  86748. zText[(nBlob*2)+2] = '\'';
  86749. zText[(nBlob*2)+3] = '\0';
  86750. zText[0] = 'X';
  86751. zText[1] = '\'';
  86752. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  86753. sqlite3_free(zText);
  86754. }
  86755. break;
  86756. }
  86757. case SQLITE_TEXT: {
  86758. int i,j;
  86759. u64 n;
  86760. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  86761. char *z;
  86762. if( zArg==0 ) return;
  86763. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  86764. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  86765. if( z ){
  86766. z[0] = '\'';
  86767. for(i=0, j=1; zArg[i]; i++){
  86768. z[j++] = zArg[i];
  86769. if( zArg[i]=='\'' ){
  86770. z[j++] = '\'';
  86771. }
  86772. }
  86773. z[j++] = '\'';
  86774. z[j] = 0;
  86775. sqlite3_result_text(context, z, j, sqlite3_free);
  86776. }
  86777. break;
  86778. }
  86779. default: {
  86780. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  86781. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  86782. break;
  86783. }
  86784. }
  86785. }
  86786. /*
  86787. ** The unicode() function. Return the integer unicode code-point value
  86788. ** for the first character of the input string.
  86789. */
  86790. static void unicodeFunc(
  86791. sqlite3_context *context,
  86792. int argc,
  86793. sqlite3_value **argv
  86794. ){
  86795. const unsigned char *z = sqlite3_value_text(argv[0]);
  86796. (void)argc;
  86797. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  86798. }
  86799. /*
  86800. ** The char() function takes zero or more arguments, each of which is
  86801. ** an integer. It constructs a string where each character of the string
  86802. ** is the unicode character for the corresponding integer argument.
  86803. */
  86804. static void charFunc(
  86805. sqlite3_context *context,
  86806. int argc,
  86807. sqlite3_value **argv
  86808. ){
  86809. unsigned char *z, *zOut;
  86810. int i;
  86811. zOut = z = sqlite3_malloc( argc*4 );
  86812. if( z==0 ){
  86813. sqlite3_result_error_nomem(context);
  86814. return;
  86815. }
  86816. for(i=0; i<argc; i++){
  86817. sqlite3_int64 x;
  86818. unsigned c;
  86819. x = sqlite3_value_int64(argv[i]);
  86820. if( x<0 || x>0x10ffff ) x = 0xfffd;
  86821. c = (unsigned)(x & 0x1fffff);
  86822. if( c<0x00080 ){
  86823. *zOut++ = (u8)(c&0xFF);
  86824. }else if( c<0x00800 ){
  86825. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  86826. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86827. }else if( c<0x10000 ){
  86828. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  86829. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  86830. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86831. }else{
  86832. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  86833. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  86834. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  86835. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86836. } \
  86837. }
  86838. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  86839. }
  86840. /*
  86841. ** The hex() function. Interpret the argument as a blob. Return
  86842. ** a hexadecimal rendering as text.
  86843. */
  86844. static void hexFunc(
  86845. sqlite3_context *context,
  86846. int argc,
  86847. sqlite3_value **argv
  86848. ){
  86849. int i, n;
  86850. const unsigned char *pBlob;
  86851. char *zHex, *z;
  86852. assert( argc==1 );
  86853. UNUSED_PARAMETER(argc);
  86854. pBlob = sqlite3_value_blob(argv[0]);
  86855. n = sqlite3_value_bytes(argv[0]);
  86856. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  86857. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  86858. if( zHex ){
  86859. for(i=0; i<n; i++, pBlob++){
  86860. unsigned char c = *pBlob;
  86861. *(z++) = hexdigits[(c>>4)&0xf];
  86862. *(z++) = hexdigits[c&0xf];
  86863. }
  86864. *z = 0;
  86865. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  86866. }
  86867. }
  86868. /*
  86869. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  86870. */
  86871. static void zeroblobFunc(
  86872. sqlite3_context *context,
  86873. int argc,
  86874. sqlite3_value **argv
  86875. ){
  86876. i64 n;
  86877. sqlite3 *db = sqlite3_context_db_handle(context);
  86878. assert( argc==1 );
  86879. UNUSED_PARAMETER(argc);
  86880. n = sqlite3_value_int64(argv[0]);
  86881. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86882. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  86883. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86884. sqlite3_result_error_toobig(context);
  86885. }else{
  86886. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  86887. }
  86888. }
  86889. /*
  86890. ** The replace() function. Three arguments are all strings: call
  86891. ** them A, B, and C. The result is also a string which is derived
  86892. ** from A by replacing every occurrence of B with C. The match
  86893. ** must be exact. Collating sequences are not used.
  86894. */
  86895. static void replaceFunc(
  86896. sqlite3_context *context,
  86897. int argc,
  86898. sqlite3_value **argv
  86899. ){
  86900. const unsigned char *zStr; /* The input string A */
  86901. const unsigned char *zPattern; /* The pattern string B */
  86902. const unsigned char *zRep; /* The replacement string C */
  86903. unsigned char *zOut; /* The output */
  86904. int nStr; /* Size of zStr */
  86905. int nPattern; /* Size of zPattern */
  86906. int nRep; /* Size of zRep */
  86907. i64 nOut; /* Maximum size of zOut */
  86908. int loopLimit; /* Last zStr[] that might match zPattern[] */
  86909. int i, j; /* Loop counters */
  86910. assert( argc==3 );
  86911. UNUSED_PARAMETER(argc);
  86912. zStr = sqlite3_value_text(argv[0]);
  86913. if( zStr==0 ) return;
  86914. nStr = sqlite3_value_bytes(argv[0]);
  86915. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  86916. zPattern = sqlite3_value_text(argv[1]);
  86917. if( zPattern==0 ){
  86918. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  86919. || sqlite3_context_db_handle(context)->mallocFailed );
  86920. return;
  86921. }
  86922. if( zPattern[0]==0 ){
  86923. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  86924. sqlite3_result_value(context, argv[0]);
  86925. return;
  86926. }
  86927. nPattern = sqlite3_value_bytes(argv[1]);
  86928. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  86929. zRep = sqlite3_value_text(argv[2]);
  86930. if( zRep==0 ) return;
  86931. nRep = sqlite3_value_bytes(argv[2]);
  86932. assert( zRep==sqlite3_value_text(argv[2]) );
  86933. nOut = nStr + 1;
  86934. assert( nOut<SQLITE_MAX_LENGTH );
  86935. zOut = contextMalloc(context, (i64)nOut);
  86936. if( zOut==0 ){
  86937. return;
  86938. }
  86939. loopLimit = nStr - nPattern;
  86940. for(i=j=0; i<=loopLimit; i++){
  86941. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  86942. zOut[j++] = zStr[i];
  86943. }else{
  86944. u8 *zOld;
  86945. sqlite3 *db = sqlite3_context_db_handle(context);
  86946. nOut += nRep - nPattern;
  86947. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86948. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86949. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86950. sqlite3_result_error_toobig(context);
  86951. sqlite3_free(zOut);
  86952. return;
  86953. }
  86954. zOld = zOut;
  86955. zOut = sqlite3_realloc(zOut, (int)nOut);
  86956. if( zOut==0 ){
  86957. sqlite3_result_error_nomem(context);
  86958. sqlite3_free(zOld);
  86959. return;
  86960. }
  86961. memcpy(&zOut[j], zRep, nRep);
  86962. j += nRep;
  86963. i += nPattern-1;
  86964. }
  86965. }
  86966. assert( j+nStr-i+1==nOut );
  86967. memcpy(&zOut[j], &zStr[i], nStr-i);
  86968. j += nStr - i;
  86969. assert( j<=nOut );
  86970. zOut[j] = 0;
  86971. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  86972. }
  86973. /*
  86974. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  86975. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  86976. */
  86977. static void trimFunc(
  86978. sqlite3_context *context,
  86979. int argc,
  86980. sqlite3_value **argv
  86981. ){
  86982. const unsigned char *zIn; /* Input string */
  86983. const unsigned char *zCharSet; /* Set of characters to trim */
  86984. int nIn; /* Number of bytes in input */
  86985. int flags; /* 1: trimleft 2: trimright 3: trim */
  86986. int i; /* Loop counter */
  86987. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  86988. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  86989. int nChar; /* Number of characters in zCharSet */
  86990. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  86991. return;
  86992. }
  86993. zIn = sqlite3_value_text(argv[0]);
  86994. if( zIn==0 ) return;
  86995. nIn = sqlite3_value_bytes(argv[0]);
  86996. assert( zIn==sqlite3_value_text(argv[0]) );
  86997. if( argc==1 ){
  86998. static const unsigned char lenOne[] = { 1 };
  86999. static unsigned char * const azOne[] = { (u8*)" " };
  87000. nChar = 1;
  87001. aLen = (u8*)lenOne;
  87002. azChar = (unsigned char **)azOne;
  87003. zCharSet = 0;
  87004. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  87005. return;
  87006. }else{
  87007. const unsigned char *z;
  87008. for(z=zCharSet, nChar=0; *z; nChar++){
  87009. SQLITE_SKIP_UTF8(z);
  87010. }
  87011. if( nChar>0 ){
  87012. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  87013. if( azChar==0 ){
  87014. return;
  87015. }
  87016. aLen = (unsigned char*)&azChar[nChar];
  87017. for(z=zCharSet, nChar=0; *z; nChar++){
  87018. azChar[nChar] = (unsigned char *)z;
  87019. SQLITE_SKIP_UTF8(z);
  87020. aLen[nChar] = (u8)(z - azChar[nChar]);
  87021. }
  87022. }
  87023. }
  87024. if( nChar>0 ){
  87025. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  87026. if( flags & 1 ){
  87027. while( nIn>0 ){
  87028. int len = 0;
  87029. for(i=0; i<nChar; i++){
  87030. len = aLen[i];
  87031. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  87032. }
  87033. if( i>=nChar ) break;
  87034. zIn += len;
  87035. nIn -= len;
  87036. }
  87037. }
  87038. if( flags & 2 ){
  87039. while( nIn>0 ){
  87040. int len = 0;
  87041. for(i=0; i<nChar; i++){
  87042. len = aLen[i];
  87043. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  87044. }
  87045. if( i>=nChar ) break;
  87046. nIn -= len;
  87047. }
  87048. }
  87049. if( zCharSet ){
  87050. sqlite3_free(azChar);
  87051. }
  87052. }
  87053. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  87054. }
  87055. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  87056. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  87057. ** when SQLite is built.
  87058. */
  87059. #ifdef SQLITE_SOUNDEX
  87060. /*
  87061. ** Compute the soundex encoding of a word.
  87062. **
  87063. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  87064. ** soundex encoding of the string X.
  87065. */
  87066. static void soundexFunc(
  87067. sqlite3_context *context,
  87068. int argc,
  87069. sqlite3_value **argv
  87070. ){
  87071. char zResult[8];
  87072. const u8 *zIn;
  87073. int i, j;
  87074. static const unsigned char iCode[] = {
  87075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87079. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  87080. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  87081. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  87082. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  87083. };
  87084. assert( argc==1 );
  87085. zIn = (u8*)sqlite3_value_text(argv[0]);
  87086. if( zIn==0 ) zIn = (u8*)"";
  87087. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  87088. if( zIn[i] ){
  87089. u8 prevcode = iCode[zIn[i]&0x7f];
  87090. zResult[0] = sqlite3Toupper(zIn[i]);
  87091. for(j=1; j<4 && zIn[i]; i++){
  87092. int code = iCode[zIn[i]&0x7f];
  87093. if( code>0 ){
  87094. if( code!=prevcode ){
  87095. prevcode = code;
  87096. zResult[j++] = code + '0';
  87097. }
  87098. }else{
  87099. prevcode = 0;
  87100. }
  87101. }
  87102. while( j<4 ){
  87103. zResult[j++] = '0';
  87104. }
  87105. zResult[j] = 0;
  87106. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  87107. }else{
  87108. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  87109. ** is NULL or contains no ASCII alphabetic characters. */
  87110. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  87111. }
  87112. }
  87113. #endif /* SQLITE_SOUNDEX */
  87114. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  87115. /*
  87116. ** A function that loads a shared-library extension then returns NULL.
  87117. */
  87118. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  87119. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  87120. const char *zProc;
  87121. sqlite3 *db = sqlite3_context_db_handle(context);
  87122. char *zErrMsg = 0;
  87123. if( argc==2 ){
  87124. zProc = (const char *)sqlite3_value_text(argv[1]);
  87125. }else{
  87126. zProc = 0;
  87127. }
  87128. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  87129. sqlite3_result_error(context, zErrMsg, -1);
  87130. sqlite3_free(zErrMsg);
  87131. }
  87132. }
  87133. #endif
  87134. /*
  87135. ** An instance of the following structure holds the context of a
  87136. ** sum() or avg() aggregate computation.
  87137. */
  87138. typedef struct SumCtx SumCtx;
  87139. struct SumCtx {
  87140. double rSum; /* Floating point sum */
  87141. i64 iSum; /* Integer sum */
  87142. i64 cnt; /* Number of elements summed */
  87143. u8 overflow; /* True if integer overflow seen */
  87144. u8 approx; /* True if non-integer value was input to the sum */
  87145. };
  87146. /*
  87147. ** Routines used to compute the sum, average, and total.
  87148. **
  87149. ** The SUM() function follows the (broken) SQL standard which means
  87150. ** that it returns NULL if it sums over no inputs. TOTAL returns
  87151. ** 0.0 in that case. In addition, TOTAL always returns a float where
  87152. ** SUM might return an integer if it never encounters a floating point
  87153. ** value. TOTAL never fails, but SUM might through an exception if
  87154. ** it overflows an integer.
  87155. */
  87156. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  87157. SumCtx *p;
  87158. int type;
  87159. assert( argc==1 );
  87160. UNUSED_PARAMETER(argc);
  87161. p = sqlite3_aggregate_context(context, sizeof(*p));
  87162. type = sqlite3_value_numeric_type(argv[0]);
  87163. if( p && type!=SQLITE_NULL ){
  87164. p->cnt++;
  87165. if( type==SQLITE_INTEGER ){
  87166. i64 v = sqlite3_value_int64(argv[0]);
  87167. p->rSum += v;
  87168. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  87169. p->overflow = 1;
  87170. }
  87171. }else{
  87172. p->rSum += sqlite3_value_double(argv[0]);
  87173. p->approx = 1;
  87174. }
  87175. }
  87176. }
  87177. static void sumFinalize(sqlite3_context *context){
  87178. SumCtx *p;
  87179. p = sqlite3_aggregate_context(context, 0);
  87180. if( p && p->cnt>0 ){
  87181. if( p->overflow ){
  87182. sqlite3_result_error(context,"integer overflow",-1);
  87183. }else if( p->approx ){
  87184. sqlite3_result_double(context, p->rSum);
  87185. }else{
  87186. sqlite3_result_int64(context, p->iSum);
  87187. }
  87188. }
  87189. }
  87190. static void avgFinalize(sqlite3_context *context){
  87191. SumCtx *p;
  87192. p = sqlite3_aggregate_context(context, 0);
  87193. if( p && p->cnt>0 ){
  87194. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  87195. }
  87196. }
  87197. static void totalFinalize(sqlite3_context *context){
  87198. SumCtx *p;
  87199. p = sqlite3_aggregate_context(context, 0);
  87200. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  87201. sqlite3_result_double(context, p ? p->rSum : (double)0);
  87202. }
  87203. /*
  87204. ** The following structure keeps track of state information for the
  87205. ** count() aggregate function.
  87206. */
  87207. typedef struct CountCtx CountCtx;
  87208. struct CountCtx {
  87209. i64 n;
  87210. };
  87211. /*
  87212. ** Routines to implement the count() aggregate function.
  87213. */
  87214. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  87215. CountCtx *p;
  87216. p = sqlite3_aggregate_context(context, sizeof(*p));
  87217. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  87218. p->n++;
  87219. }
  87220. #ifndef SQLITE_OMIT_DEPRECATED
  87221. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  87222. ** sure it still operates correctly, verify that its count agrees with our
  87223. ** internal count when using count(*) and when the total count can be
  87224. ** expressed as a 32-bit integer. */
  87225. assert( argc==1 || p==0 || p->n>0x7fffffff
  87226. || p->n==sqlite3_aggregate_count(context) );
  87227. #endif
  87228. }
  87229. static void countFinalize(sqlite3_context *context){
  87230. CountCtx *p;
  87231. p = sqlite3_aggregate_context(context, 0);
  87232. sqlite3_result_int64(context, p ? p->n : 0);
  87233. }
  87234. /*
  87235. ** Routines to implement min() and max() aggregate functions.
  87236. */
  87237. static void minmaxStep(
  87238. sqlite3_context *context,
  87239. int NotUsed,
  87240. sqlite3_value **argv
  87241. ){
  87242. Mem *pArg = (Mem *)argv[0];
  87243. Mem *pBest;
  87244. UNUSED_PARAMETER(NotUsed);
  87245. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  87246. if( !pBest ) return;
  87247. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  87248. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  87249. }else if( pBest->flags ){
  87250. int max;
  87251. int cmp;
  87252. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  87253. /* This step function is used for both the min() and max() aggregates,
  87254. ** the only difference between the two being that the sense of the
  87255. ** comparison is inverted. For the max() aggregate, the
  87256. ** sqlite3_user_data() function returns (void *)-1. For min() it
  87257. ** returns (void *)db, where db is the sqlite3* database pointer.
  87258. ** Therefore the next statement sets variable 'max' to 1 for the max()
  87259. ** aggregate, or 0 for min().
  87260. */
  87261. max = sqlite3_user_data(context)!=0;
  87262. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  87263. if( (max && cmp<0) || (!max && cmp>0) ){
  87264. sqlite3VdbeMemCopy(pBest, pArg);
  87265. }else{
  87266. sqlite3SkipAccumulatorLoad(context);
  87267. }
  87268. }else{
  87269. sqlite3VdbeMemCopy(pBest, pArg);
  87270. }
  87271. }
  87272. static void minMaxFinalize(sqlite3_context *context){
  87273. sqlite3_value *pRes;
  87274. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  87275. if( pRes ){
  87276. if( pRes->flags ){
  87277. sqlite3_result_value(context, pRes);
  87278. }
  87279. sqlite3VdbeMemRelease(pRes);
  87280. }
  87281. }
  87282. /*
  87283. ** group_concat(EXPR, ?SEPARATOR?)
  87284. */
  87285. static void groupConcatStep(
  87286. sqlite3_context *context,
  87287. int argc,
  87288. sqlite3_value **argv
  87289. ){
  87290. const char *zVal;
  87291. StrAccum *pAccum;
  87292. const char *zSep;
  87293. int nVal, nSep;
  87294. assert( argc==1 || argc==2 );
  87295. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  87296. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  87297. if( pAccum ){
  87298. sqlite3 *db = sqlite3_context_db_handle(context);
  87299. int firstTerm = pAccum->useMalloc==0;
  87300. pAccum->useMalloc = 2;
  87301. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  87302. if( !firstTerm ){
  87303. if( argc==2 ){
  87304. zSep = (char*)sqlite3_value_text(argv[1]);
  87305. nSep = sqlite3_value_bytes(argv[1]);
  87306. }else{
  87307. zSep = ",";
  87308. nSep = 1;
  87309. }
  87310. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  87311. }
  87312. zVal = (char*)sqlite3_value_text(argv[0]);
  87313. nVal = sqlite3_value_bytes(argv[0]);
  87314. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  87315. }
  87316. }
  87317. static void groupConcatFinalize(sqlite3_context *context){
  87318. StrAccum *pAccum;
  87319. pAccum = sqlite3_aggregate_context(context, 0);
  87320. if( pAccum ){
  87321. if( pAccum->accError==STRACCUM_TOOBIG ){
  87322. sqlite3_result_error_toobig(context);
  87323. }else if( pAccum->accError==STRACCUM_NOMEM ){
  87324. sqlite3_result_error_nomem(context);
  87325. }else{
  87326. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  87327. sqlite3_free);
  87328. }
  87329. }
  87330. }
  87331. /*
  87332. ** This routine does per-connection function registration. Most
  87333. ** of the built-in functions above are part of the global function set.
  87334. ** This routine only deals with those that are not global.
  87335. */
  87336. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  87337. int rc = sqlite3_overload_function(db, "MATCH", 2);
  87338. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  87339. if( rc==SQLITE_NOMEM ){
  87340. db->mallocFailed = 1;
  87341. }
  87342. }
  87343. /*
  87344. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  87345. */
  87346. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  87347. FuncDef *pDef;
  87348. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  87349. 2, SQLITE_UTF8, 0);
  87350. if( ALWAYS(pDef) ){
  87351. pDef->funcFlags |= flagVal;
  87352. }
  87353. }
  87354. /*
  87355. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  87356. ** parameter determines whether or not the LIKE operator is case
  87357. ** sensitive. GLOB is always case sensitive.
  87358. */
  87359. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  87360. struct compareInfo *pInfo;
  87361. if( caseSensitive ){
  87362. pInfo = (struct compareInfo*)&likeInfoAlt;
  87363. }else{
  87364. pInfo = (struct compareInfo*)&likeInfoNorm;
  87365. }
  87366. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  87367. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  87368. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  87369. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  87370. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  87371. setLikeOptFlag(db, "like",
  87372. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  87373. }
  87374. /*
  87375. ** pExpr points to an expression which implements a function. If
  87376. ** it is appropriate to apply the LIKE optimization to that function
  87377. ** then set aWc[0] through aWc[2] to the wildcard characters and
  87378. ** return TRUE. If the function is not a LIKE-style function then
  87379. ** return FALSE.
  87380. */
  87381. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  87382. FuncDef *pDef;
  87383. if( pExpr->op!=TK_FUNCTION
  87384. || !pExpr->x.pList
  87385. || pExpr->x.pList->nExpr!=2
  87386. ){
  87387. return 0;
  87388. }
  87389. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87390. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  87391. sqlite3Strlen30(pExpr->u.zToken),
  87392. 2, SQLITE_UTF8, 0);
  87393. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  87394. return 0;
  87395. }
  87396. /* The memcpy() statement assumes that the wildcard characters are
  87397. ** the first three statements in the compareInfo structure. The
  87398. ** asserts() that follow verify that assumption
  87399. */
  87400. memcpy(aWc, pDef->pUserData, 3);
  87401. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  87402. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  87403. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  87404. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  87405. return 1;
  87406. }
  87407. /*
  87408. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  87409. ** to the global function hash table. This occurs at start-time (as
  87410. ** a consequence of calling sqlite3_initialize()).
  87411. **
  87412. ** After this routine runs
  87413. */
  87414. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  87415. /*
  87416. ** The following array holds FuncDef structures for all of the functions
  87417. ** defined in this file.
  87418. **
  87419. ** The array cannot be constant since changes are made to the
  87420. ** FuncDef.pHash elements at start-time. The elements of this array
  87421. ** are read-only after initialization is complete.
  87422. */
  87423. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  87424. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  87425. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  87426. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  87427. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  87428. FUNCTION(trim, 1, 3, 0, trimFunc ),
  87429. FUNCTION(trim, 2, 3, 0, trimFunc ),
  87430. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  87431. FUNCTION(min, 0, 0, 1, 0 ),
  87432. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  87433. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  87434. FUNCTION(max, 0, 1, 1, 0 ),
  87435. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  87436. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  87437. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  87438. FUNCTION(instr, 2, 0, 0, instrFunc ),
  87439. FUNCTION(substr, 2, 0, 0, substrFunc ),
  87440. FUNCTION(substr, 3, 0, 0, substrFunc ),
  87441. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  87442. FUNCTION(char, -1, 0, 0, charFunc ),
  87443. FUNCTION(abs, 1, 0, 0, absFunc ),
  87444. #ifndef SQLITE_OMIT_FLOATING_POINT
  87445. FUNCTION(round, 1, 0, 0, roundFunc ),
  87446. FUNCTION(round, 2, 0, 0, roundFunc ),
  87447. #endif
  87448. FUNCTION(upper, 1, 0, 0, upperFunc ),
  87449. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  87450. FUNCTION(coalesce, 1, 0, 0, 0 ),
  87451. FUNCTION(coalesce, 0, 0, 0, 0 ),
  87452. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  87453. FUNCTION(hex, 1, 0, 0, hexFunc ),
  87454. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  87455. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  87456. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  87457. FUNCTION(random, 0, 0, 0, randomFunc ),
  87458. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  87459. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  87460. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  87461. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  87462. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  87463. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  87464. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  87465. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  87466. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  87467. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  87468. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  87469. FUNCTION(changes, 0, 0, 0, changes ),
  87470. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  87471. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  87472. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  87473. #ifdef SQLITE_SOUNDEX
  87474. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  87475. #endif
  87476. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  87477. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  87478. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  87479. #endif
  87480. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  87481. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  87482. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  87483. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  87484. {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  87485. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  87486. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  87487. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  87488. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87489. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  87490. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87491. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87492. #else
  87493. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  87494. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  87495. #endif
  87496. };
  87497. int i;
  87498. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  87499. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  87500. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  87501. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  87502. }
  87503. sqlite3RegisterDateTimeFunctions();
  87504. #ifndef SQLITE_OMIT_ALTERTABLE
  87505. sqlite3AlterFunctions();
  87506. #endif
  87507. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  87508. sqlite3AnalyzeFunctions();
  87509. #endif
  87510. }
  87511. /************** End of func.c ************************************************/
  87512. /************** Begin file fkey.c ********************************************/
  87513. /*
  87514. **
  87515. ** The author disclaims copyright to this source code. In place of
  87516. ** a legal notice, here is a blessing:
  87517. **
  87518. ** May you do good and not evil.
  87519. ** May you find forgiveness for yourself and forgive others.
  87520. ** May you share freely, never taking more than you give.
  87521. **
  87522. *************************************************************************
  87523. ** This file contains code used by the compiler to add foreign key
  87524. ** support to compiled SQL statements.
  87525. */
  87526. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87527. #ifndef SQLITE_OMIT_TRIGGER
  87528. /*
  87529. ** Deferred and Immediate FKs
  87530. ** --------------------------
  87531. **
  87532. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  87533. ** If an immediate foreign key constraint is violated,
  87534. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  87535. ** statement transaction rolled back. If a
  87536. ** deferred foreign key constraint is violated, no action is taken
  87537. ** immediately. However if the application attempts to commit the
  87538. ** transaction before fixing the constraint violation, the attempt fails.
  87539. **
  87540. ** Deferred constraints are implemented using a simple counter associated
  87541. ** with the database handle. The counter is set to zero each time a
  87542. ** database transaction is opened. Each time a statement is executed
  87543. ** that causes a foreign key violation, the counter is incremented. Each
  87544. ** time a statement is executed that removes an existing violation from
  87545. ** the database, the counter is decremented. When the transaction is
  87546. ** committed, the commit fails if the current value of the counter is
  87547. ** greater than zero. This scheme has two big drawbacks:
  87548. **
  87549. ** * When a commit fails due to a deferred foreign key constraint,
  87550. ** there is no way to tell which foreign constraint is not satisfied,
  87551. ** or which row it is not satisfied for.
  87552. **
  87553. ** * If the database contains foreign key violations when the
  87554. ** transaction is opened, this may cause the mechanism to malfunction.
  87555. **
  87556. ** Despite these problems, this approach is adopted as it seems simpler
  87557. ** than the alternatives.
  87558. **
  87559. ** INSERT operations:
  87560. **
  87561. ** I.1) For each FK for which the table is the child table, search
  87562. ** the parent table for a match. If none is found increment the
  87563. ** constraint counter.
  87564. **
  87565. ** I.2) For each FK for which the table is the parent table,
  87566. ** search the child table for rows that correspond to the new
  87567. ** row in the parent table. Decrement the counter for each row
  87568. ** found (as the constraint is now satisfied).
  87569. **
  87570. ** DELETE operations:
  87571. **
  87572. ** D.1) For each FK for which the table is the child table,
  87573. ** search the parent table for a row that corresponds to the
  87574. ** deleted row in the child table. If such a row is not found,
  87575. ** decrement the counter.
  87576. **
  87577. ** D.2) For each FK for which the table is the parent table, search
  87578. ** the child table for rows that correspond to the deleted row
  87579. ** in the parent table. For each found increment the counter.
  87580. **
  87581. ** UPDATE operations:
  87582. **
  87583. ** An UPDATE command requires that all 4 steps above are taken, but only
  87584. ** for FK constraints for which the affected columns are actually
  87585. ** modified (values must be compared at runtime).
  87586. **
  87587. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  87588. ** This simplifies the implementation a bit.
  87589. **
  87590. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  87591. ** resolution is considered to delete rows before the new row is inserted.
  87592. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  87593. ** is thrown, even if the FK constraint would be satisfied after the new
  87594. ** row is inserted.
  87595. **
  87596. ** Immediate constraints are usually handled similarly. The only difference
  87597. ** is that the counter used is stored as part of each individual statement
  87598. ** object (struct Vdbe). If, after the statement has run, its immediate
  87599. ** constraint counter is greater than zero,
  87600. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  87601. ** and the statement transaction is rolled back. An exception is an INSERT
  87602. ** statement that inserts a single row only (no triggers). In this case,
  87603. ** instead of using a counter, an exception is thrown immediately if the
  87604. ** INSERT violates a foreign key constraint. This is necessary as such
  87605. ** an INSERT does not open a statement transaction.
  87606. **
  87607. ** TODO: How should dropping a table be handled? How should renaming a
  87608. ** table be handled?
  87609. **
  87610. **
  87611. ** Query API Notes
  87612. ** ---------------
  87613. **
  87614. ** Before coding an UPDATE or DELETE row operation, the code-generator
  87615. ** for those two operations needs to know whether or not the operation
  87616. ** requires any FK processing and, if so, which columns of the original
  87617. ** row are required by the FK processing VDBE code (i.e. if FKs were
  87618. ** implemented using triggers, which of the old.* columns would be
  87619. ** accessed). No information is required by the code-generator before
  87620. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  87621. ** generation code to query for this information are:
  87622. **
  87623. ** sqlite3FkRequired() - Test to see if FK processing is required.
  87624. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  87625. **
  87626. **
  87627. ** Externally accessible module functions
  87628. ** --------------------------------------
  87629. **
  87630. ** sqlite3FkCheck() - Check for foreign key violations.
  87631. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  87632. ** sqlite3FkDelete() - Delete an FKey structure.
  87633. */
  87634. /*
  87635. ** VDBE Calling Convention
  87636. ** -----------------------
  87637. **
  87638. ** Example:
  87639. **
  87640. ** For the following INSERT statement:
  87641. **
  87642. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  87643. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  87644. **
  87645. ** Register (x): 2 (type integer)
  87646. ** Register (x+1): 1 (type integer)
  87647. ** Register (x+2): NULL (type NULL)
  87648. ** Register (x+3): 3.1 (type real)
  87649. */
  87650. /*
  87651. ** A foreign key constraint requires that the key columns in the parent
  87652. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  87653. ** Given that pParent is the parent table for foreign key constraint pFKey,
  87654. ** search the schema for a unique index on the parent key columns.
  87655. **
  87656. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  87657. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  87658. ** is set to point to the unique index.
  87659. **
  87660. ** If the parent key consists of a single column (the foreign key constraint
  87661. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  87662. ** Otherwise, it is set to point to an allocated array of size N, where
  87663. ** N is the number of columns in the parent key. The first element of the
  87664. ** array is the index of the child table column that is mapped by the FK
  87665. ** constraint to the parent table column stored in the left-most column
  87666. ** of index *ppIdx. The second element of the array is the index of the
  87667. ** child table column that corresponds to the second left-most column of
  87668. ** *ppIdx, and so on.
  87669. **
  87670. ** If the required index cannot be found, either because:
  87671. **
  87672. ** 1) The named parent key columns do not exist, or
  87673. **
  87674. ** 2) The named parent key columns do exist, but are not subject to a
  87675. ** UNIQUE or PRIMARY KEY constraint, or
  87676. **
  87677. ** 3) No parent key columns were provided explicitly as part of the
  87678. ** foreign key definition, and the parent table does not have a
  87679. ** PRIMARY KEY, or
  87680. **
  87681. ** 4) No parent key columns were provided explicitly as part of the
  87682. ** foreign key definition, and the PRIMARY KEY of the parent table
  87683. ** consists of a a different number of columns to the child key in
  87684. ** the child table.
  87685. **
  87686. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  87687. ** into pParse. If an OOM error occurs, non-zero is returned and the
  87688. ** pParse->db->mallocFailed flag is set.
  87689. */
  87690. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  87691. Parse *pParse, /* Parse context to store any error in */
  87692. Table *pParent, /* Parent table of FK constraint pFKey */
  87693. FKey *pFKey, /* Foreign key to find index for */
  87694. Index **ppIdx, /* OUT: Unique index on parent table */
  87695. int **paiCol /* OUT: Map of index columns in pFKey */
  87696. ){
  87697. Index *pIdx = 0; /* Value to return via *ppIdx */
  87698. int *aiCol = 0; /* Value to return via *paiCol */
  87699. int nCol = pFKey->nCol; /* Number of columns in parent key */
  87700. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  87701. /* The caller is responsible for zeroing output parameters. */
  87702. assert( ppIdx && *ppIdx==0 );
  87703. assert( !paiCol || *paiCol==0 );
  87704. assert( pParse );
  87705. /* If this is a non-composite (single column) foreign key, check if it
  87706. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  87707. ** and *paiCol set to zero and return early.
  87708. **
  87709. ** Otherwise, for a composite foreign key (more than one column), allocate
  87710. ** space for the aiCol array (returned via output parameter *paiCol).
  87711. ** Non-composite foreign keys do not require the aiCol array.
  87712. */
  87713. if( nCol==1 ){
  87714. /* The FK maps to the IPK if any of the following are true:
  87715. **
  87716. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  87717. ** mapped to the primary key of table pParent, or
  87718. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  87719. ** PRIMARY KEY.
  87720. */
  87721. if( pParent->iPKey>=0 ){
  87722. if( !zKey ) return 0;
  87723. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  87724. }
  87725. }else if( paiCol ){
  87726. assert( nCol>1 );
  87727. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  87728. if( !aiCol ) return 1;
  87729. *paiCol = aiCol;
  87730. }
  87731. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  87732. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  87733. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  87734. ** of columns. If each indexed column corresponds to a foreign key
  87735. ** column of pFKey, then this index is a winner. */
  87736. if( zKey==0 ){
  87737. /* If zKey is NULL, then this foreign key is implicitly mapped to
  87738. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  87739. ** identified by the test (Index.autoIndex==2). */
  87740. if( pIdx->autoIndex==2 ){
  87741. if( aiCol ){
  87742. int i;
  87743. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  87744. }
  87745. break;
  87746. }
  87747. }else{
  87748. /* If zKey is non-NULL, then this foreign key was declared to
  87749. ** map to an explicit list of columns in table pParent. Check if this
  87750. ** index matches those columns. Also, check that the index uses
  87751. ** the default collation sequences for each column. */
  87752. int i, j;
  87753. for(i=0; i<nCol; i++){
  87754. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  87755. char *zDfltColl; /* Def. collation for column */
  87756. char *zIdxCol; /* Name of indexed column */
  87757. /* If the index uses a collation sequence that is different from
  87758. ** the default collation sequence for the column, this index is
  87759. ** unusable. Bail out early in this case. */
  87760. zDfltColl = pParent->aCol[iCol].zColl;
  87761. if( !zDfltColl ){
  87762. zDfltColl = "BINARY";
  87763. }
  87764. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  87765. zIdxCol = pParent->aCol[iCol].zName;
  87766. for(j=0; j<nCol; j++){
  87767. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  87768. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  87769. break;
  87770. }
  87771. }
  87772. if( j==nCol ) break;
  87773. }
  87774. if( i==nCol ) break; /* pIdx is usable */
  87775. }
  87776. }
  87777. }
  87778. if( !pIdx ){
  87779. if( !pParse->disableTriggers ){
  87780. sqlite3ErrorMsg(pParse,
  87781. "foreign key mismatch - \"%w\" referencing \"%w\"",
  87782. pFKey->pFrom->zName, pFKey->zTo);
  87783. }
  87784. sqlite3DbFree(pParse->db, aiCol);
  87785. return 1;
  87786. }
  87787. *ppIdx = pIdx;
  87788. return 0;
  87789. }
  87790. /*
  87791. ** This function is called when a row is inserted into or deleted from the
  87792. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  87793. ** on the child table of pFKey, this function is invoked twice for each row
  87794. ** affected - once to "delete" the old row, and then again to "insert" the
  87795. ** new row.
  87796. **
  87797. ** Each time it is called, this function generates VDBE code to locate the
  87798. ** row in the parent table that corresponds to the row being inserted into
  87799. ** or deleted from the child table. If the parent row can be found, no
  87800. ** special action is taken. Otherwise, if the parent row can *not* be
  87801. ** found in the parent table:
  87802. **
  87803. ** Operation | FK type | Action taken
  87804. ** --------------------------------------------------------------------------
  87805. ** INSERT immediate Increment the "immediate constraint counter".
  87806. **
  87807. ** DELETE immediate Decrement the "immediate constraint counter".
  87808. **
  87809. ** INSERT deferred Increment the "deferred constraint counter".
  87810. **
  87811. ** DELETE deferred Decrement the "deferred constraint counter".
  87812. **
  87813. ** These operations are identified in the comment at the top of this file
  87814. ** (fkey.c) as "I.1" and "D.1".
  87815. */
  87816. static void fkLookupParent(
  87817. Parse *pParse, /* Parse context */
  87818. int iDb, /* Index of database housing pTab */
  87819. Table *pTab, /* Parent table of FK pFKey */
  87820. Index *pIdx, /* Unique index on parent key columns in pTab */
  87821. FKey *pFKey, /* Foreign key constraint */
  87822. int *aiCol, /* Map from parent key columns to child table columns */
  87823. int regData, /* Address of array containing child table row */
  87824. int nIncr, /* Increment constraint counter by this */
  87825. int isIgnore /* If true, pretend pTab contains all NULL values */
  87826. ){
  87827. int i; /* Iterator variable */
  87828. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  87829. int iCur = pParse->nTab - 1; /* Cursor number to use */
  87830. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  87831. /* If nIncr is less than zero, then check at runtime if there are any
  87832. ** outstanding constraints to resolve. If there are not, there is no need
  87833. ** to check if deleting this row resolves any outstanding violations.
  87834. **
  87835. ** Check if any of the key columns in the child table row are NULL. If
  87836. ** any are, then the constraint is considered satisfied. No need to
  87837. ** search for a matching row in the parent table. */
  87838. if( nIncr<0 ){
  87839. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  87840. }
  87841. for(i=0; i<pFKey->nCol; i++){
  87842. int iReg = aiCol[i] + regData + 1;
  87843. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  87844. }
  87845. if( isIgnore==0 ){
  87846. if( pIdx==0 ){
  87847. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  87848. ** column of the parent table (table pTab). */
  87849. int iMustBeInt; /* Address of MustBeInt instruction */
  87850. int regTemp = sqlite3GetTempReg(pParse);
  87851. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  87852. ** apply the affinity of the parent key). If this fails, then there
  87853. ** is no matching parent key. Before using MustBeInt, make a copy of
  87854. ** the value. Otherwise, the value inserted into the child key column
  87855. ** will have INTEGER affinity applied to it, which may not be correct. */
  87856. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  87857. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  87858. /* If the parent table is the same as the child table, and we are about
  87859. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  87860. ** then check if the row being inserted matches itself. If so, do not
  87861. ** increment the constraint-counter. */
  87862. if( pTab==pFKey->pFrom && nIncr==1 ){
  87863. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  87864. }
  87865. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  87866. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  87867. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  87868. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  87869. sqlite3VdbeJumpHere(v, iMustBeInt);
  87870. sqlite3ReleaseTempReg(pParse, regTemp);
  87871. }else{
  87872. int nCol = pFKey->nCol;
  87873. int regTemp = sqlite3GetTempRange(pParse, nCol);
  87874. int regRec = sqlite3GetTempReg(pParse);
  87875. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  87876. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  87877. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  87878. for(i=0; i<nCol; i++){
  87879. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  87880. }
  87881. /* If the parent table is the same as the child table, and we are about
  87882. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  87883. ** then check if the row being inserted matches itself. If so, do not
  87884. ** increment the constraint-counter.
  87885. **
  87886. ** If any of the parent-key values are NULL, then the row cannot match
  87887. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  87888. ** of the parent-key values are NULL (at this point it is known that
  87889. ** none of the child key values are).
  87890. */
  87891. if( pTab==pFKey->pFrom && nIncr==1 ){
  87892. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  87893. for(i=0; i<nCol; i++){
  87894. int iChild = aiCol[i]+1+regData;
  87895. int iParent = pIdx->aiColumn[i]+1+regData;
  87896. assert( aiCol[i]!=pTab->iPKey );
  87897. if( pIdx->aiColumn[i]==pTab->iPKey ){
  87898. /* The parent key is a composite key that includes the IPK column */
  87899. iParent = regData;
  87900. }
  87901. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  87902. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  87903. }
  87904. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  87905. }
  87906. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  87907. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  87908. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  87909. sqlite3ReleaseTempReg(pParse, regRec);
  87910. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  87911. }
  87912. }
  87913. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  87914. && !pParse->pToplevel
  87915. && !pParse->isMultiWrite
  87916. ){
  87917. /* Special case: If this is an INSERT statement that will insert exactly
  87918. ** one row into the table, raise a constraint immediately instead of
  87919. ** incrementing a counter. This is necessary as the VM code is being
  87920. ** generated for will not open a statement transaction. */
  87921. assert( nIncr==1 );
  87922. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  87923. OE_Abort, "foreign key constraint failed", P4_STATIC
  87924. );
  87925. }else{
  87926. if( nIncr>0 && pFKey->isDeferred==0 ){
  87927. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  87928. }
  87929. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  87930. }
  87931. sqlite3VdbeResolveLabel(v, iOk);
  87932. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  87933. }
  87934. /*
  87935. ** This function is called to generate code executed when a row is deleted
  87936. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  87937. ** deferred, when a row is inserted into the same table. When generating
  87938. ** code for an SQL UPDATE operation, this function may be called twice -
  87939. ** once to "delete" the old row and once to "insert" the new row.
  87940. **
  87941. ** The code generated by this function scans through the rows in the child
  87942. ** table that correspond to the parent table row being deleted or inserted.
  87943. ** For each child row found, one of the following actions is taken:
  87944. **
  87945. ** Operation | FK type | Action taken
  87946. ** --------------------------------------------------------------------------
  87947. ** DELETE immediate Increment the "immediate constraint counter".
  87948. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  87949. ** throw a "foreign key constraint failed" exception.
  87950. **
  87951. ** INSERT immediate Decrement the "immediate constraint counter".
  87952. **
  87953. ** DELETE deferred Increment the "deferred constraint counter".
  87954. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  87955. ** throw a "foreign key constraint failed" exception.
  87956. **
  87957. ** INSERT deferred Decrement the "deferred constraint counter".
  87958. **
  87959. ** These operations are identified in the comment at the top of this file
  87960. ** (fkey.c) as "I.2" and "D.2".
  87961. */
  87962. static void fkScanChildren(
  87963. Parse *pParse, /* Parse context */
  87964. SrcList *pSrc, /* SrcList containing the table to scan */
  87965. Table *pTab,
  87966. Index *pIdx, /* Foreign key index */
  87967. FKey *pFKey, /* Foreign key relationship */
  87968. int *aiCol, /* Map from pIdx cols to child table cols */
  87969. int regData, /* Referenced table data starts here */
  87970. int nIncr /* Amount to increment deferred counter by */
  87971. ){
  87972. sqlite3 *db = pParse->db; /* Database handle */
  87973. int i; /* Iterator variable */
  87974. Expr *pWhere = 0; /* WHERE clause to scan with */
  87975. NameContext sNameContext; /* Context used to resolve WHERE clause */
  87976. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  87977. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  87978. Vdbe *v = sqlite3GetVdbe(pParse);
  87979. assert( !pIdx || pIdx->pTable==pTab );
  87980. if( nIncr<0 ){
  87981. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  87982. }
  87983. /* Create an Expr object representing an SQL expression like:
  87984. **
  87985. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  87986. **
  87987. ** The collation sequence used for the comparison should be that of
  87988. ** the parent key columns. The affinity of the parent key column should
  87989. ** be applied to each child key value before the comparison takes place.
  87990. */
  87991. for(i=0; i<pFKey->nCol; i++){
  87992. Expr *pLeft; /* Value from parent table row */
  87993. Expr *pRight; /* Column ref to child table */
  87994. Expr *pEq; /* Expression (pLeft = pRight) */
  87995. int iCol; /* Index of column in child table */
  87996. const char *zCol; /* Name of column in child table */
  87997. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  87998. if( pLeft ){
  87999. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  88000. ** expression to the parent key column defaults. */
  88001. if( pIdx ){
  88002. Column *pCol;
  88003. const char *zColl;
  88004. iCol = pIdx->aiColumn[i];
  88005. pCol = &pTab->aCol[iCol];
  88006. if( pTab->iPKey==iCol ) iCol = -1;
  88007. pLeft->iTable = regData+iCol+1;
  88008. pLeft->affinity = pCol->affinity;
  88009. zColl = pCol->zColl;
  88010. if( zColl==0 ) zColl = db->pDfltColl->zName;
  88011. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  88012. }else{
  88013. pLeft->iTable = regData;
  88014. pLeft->affinity = SQLITE_AFF_INTEGER;
  88015. }
  88016. }
  88017. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  88018. assert( iCol>=0 );
  88019. zCol = pFKey->pFrom->aCol[iCol].zName;
  88020. pRight = sqlite3Expr(db, TK_ID, zCol);
  88021. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  88022. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88023. }
  88024. /* If the child table is the same as the parent table, and this scan
  88025. ** is taking place as part of a DELETE operation (operation D.2), omit the
  88026. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  88027. ** clause, where $rowid is the rowid of the row being deleted. */
  88028. if( pTab==pFKey->pFrom && nIncr>0 ){
  88029. Expr *pEq; /* Expression (pLeft = pRight) */
  88030. Expr *pLeft; /* Value from parent table row */
  88031. Expr *pRight; /* Column ref to child table */
  88032. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  88033. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  88034. if( pLeft && pRight ){
  88035. pLeft->iTable = regData;
  88036. pLeft->affinity = SQLITE_AFF_INTEGER;
  88037. pRight->iTable = pSrc->a[0].iCursor;
  88038. pRight->iColumn = -1;
  88039. }
  88040. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  88041. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88042. }
  88043. /* Resolve the references in the WHERE clause. */
  88044. memset(&sNameContext, 0, sizeof(NameContext));
  88045. sNameContext.pSrcList = pSrc;
  88046. sNameContext.pParse = pParse;
  88047. sqlite3ResolveExprNames(&sNameContext, pWhere);
  88048. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  88049. ** clause. If the constraint is not deferred, throw an exception for
  88050. ** each row found. Otherwise, for deferred constraints, increment the
  88051. ** deferred constraint counter by nIncr for each row selected. */
  88052. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  88053. if( nIncr>0 && pFKey->isDeferred==0 ){
  88054. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  88055. }
  88056. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  88057. if( pWInfo ){
  88058. sqlite3WhereEnd(pWInfo);
  88059. }
  88060. /* Clean up the WHERE clause constructed above. */
  88061. sqlite3ExprDelete(db, pWhere);
  88062. if( iFkIfZero ){
  88063. sqlite3VdbeJumpHere(v, iFkIfZero);
  88064. }
  88065. }
  88066. /*
  88067. ** This function returns a pointer to the head of a linked list of FK
  88068. ** constraints for which table pTab is the parent table. For example,
  88069. ** given the following schema:
  88070. **
  88071. ** CREATE TABLE t1(a PRIMARY KEY);
  88072. ** CREATE TABLE t2(b REFERENCES t1(a);
  88073. **
  88074. ** Calling this function with table "t1" as an argument returns a pointer
  88075. ** to the FKey structure representing the foreign key constraint on table
  88076. ** "t2". Calling this function with "t2" as the argument would return a
  88077. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  88078. ** table).
  88079. */
  88080. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  88081. int nName = sqlite3Strlen30(pTab->zName);
  88082. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  88083. }
  88084. /*
  88085. ** The second argument is a Trigger structure allocated by the
  88086. ** fkActionTrigger() routine. This function deletes the Trigger structure
  88087. ** and all of its sub-components.
  88088. **
  88089. ** The Trigger structure or any of its sub-components may be allocated from
  88090. ** the lookaside buffer belonging to database handle dbMem.
  88091. */
  88092. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  88093. if( p ){
  88094. TriggerStep *pStep = p->step_list;
  88095. sqlite3ExprDelete(dbMem, pStep->pWhere);
  88096. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  88097. sqlite3SelectDelete(dbMem, pStep->pSelect);
  88098. sqlite3ExprDelete(dbMem, p->pWhen);
  88099. sqlite3DbFree(dbMem, p);
  88100. }
  88101. }
  88102. /*
  88103. ** This function is called to generate code that runs when table pTab is
  88104. ** being dropped from the database. The SrcList passed as the second argument
  88105. ** to this function contains a single entry guaranteed to resolve to
  88106. ** table pTab.
  88107. **
  88108. ** Normally, no code is required. However, if either
  88109. **
  88110. ** (a) The table is the parent table of a FK constraint, or
  88111. ** (b) The table is the child table of a deferred FK constraint and it is
  88112. ** determined at runtime that there are outstanding deferred FK
  88113. ** constraint violations in the database,
  88114. **
  88115. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  88116. ** the table from the database. Triggers are disabled while running this
  88117. ** DELETE, but foreign key actions are not.
  88118. */
  88119. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  88120. sqlite3 *db = pParse->db;
  88121. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  88122. int iSkip = 0;
  88123. Vdbe *v = sqlite3GetVdbe(pParse);
  88124. assert( v ); /* VDBE has already been allocated */
  88125. if( sqlite3FkReferences(pTab)==0 ){
  88126. /* Search for a deferred foreign key constraint for which this table
  88127. ** is the child table. If one cannot be found, return without
  88128. ** generating any VDBE code. If one can be found, then jump over
  88129. ** the entire DELETE if there are no outstanding deferred constraints
  88130. ** when this statement is run. */
  88131. FKey *p;
  88132. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88133. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  88134. }
  88135. if( !p ) return;
  88136. iSkip = sqlite3VdbeMakeLabel(v);
  88137. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  88138. }
  88139. pParse->disableTriggers = 1;
  88140. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  88141. pParse->disableTriggers = 0;
  88142. /* If the DELETE has generated immediate foreign key constraint
  88143. ** violations, halt the VDBE and return an error at this point, before
  88144. ** any modifications to the schema are made. This is because statement
  88145. ** transactions are not able to rollback schema changes.
  88146. **
  88147. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  88148. ** the statement transaction will not be rolled back even if FK
  88149. ** constraints are violated.
  88150. */
  88151. if( (db->flags & SQLITE_DeferFKs)==0 ){
  88152. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  88153. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  88154. OE_Abort, "foreign key constraint failed", P4_STATIC
  88155. );
  88156. }
  88157. if( iSkip ){
  88158. sqlite3VdbeResolveLabel(v, iSkip);
  88159. }
  88160. }
  88161. }
  88162. /*
  88163. ** The second argument points to an FKey object representing a foreign key
  88164. ** for which pTab is the child table. An UPDATE statement against pTab
  88165. ** is currently being processed. For each column of the table that is
  88166. ** actually updated, the corresponding element in the aChange[] array
  88167. ** is zero or greater (if a column is unmodified the corresponding element
  88168. ** is set to -1). If the rowid column is modified by the UPDATE statement
  88169. ** the bChngRowid argument is non-zero.
  88170. **
  88171. ** This function returns true if any of the columns that are part of the
  88172. ** child key for FK constraint *p are modified.
  88173. */
  88174. static int fkChildIsModified(
  88175. Table *pTab, /* Table being updated */
  88176. FKey *p, /* Foreign key for which pTab is the child */
  88177. int *aChange, /* Array indicating modified columns */
  88178. int bChngRowid /* True if rowid is modified by this update */
  88179. ){
  88180. int i;
  88181. for(i=0; i<p->nCol; i++){
  88182. int iChildKey = p->aCol[i].iFrom;
  88183. if( aChange[iChildKey]>=0 ) return 1;
  88184. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  88185. }
  88186. return 0;
  88187. }
  88188. /*
  88189. ** The second argument points to an FKey object representing a foreign key
  88190. ** for which pTab is the parent table. An UPDATE statement against pTab
  88191. ** is currently being processed. For each column of the table that is
  88192. ** actually updated, the corresponding element in the aChange[] array
  88193. ** is zero or greater (if a column is unmodified the corresponding element
  88194. ** is set to -1). If the rowid column is modified by the UPDATE statement
  88195. ** the bChngRowid argument is non-zero.
  88196. **
  88197. ** This function returns true if any of the columns that are part of the
  88198. ** parent key for FK constraint *p are modified.
  88199. */
  88200. static int fkParentIsModified(
  88201. Table *pTab,
  88202. FKey *p,
  88203. int *aChange,
  88204. int bChngRowid
  88205. ){
  88206. int i;
  88207. for(i=0; i<p->nCol; i++){
  88208. char *zKey = p->aCol[i].zCol;
  88209. int iKey;
  88210. for(iKey=0; iKey<pTab->nCol; iKey++){
  88211. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  88212. Column *pCol = &pTab->aCol[iKey];
  88213. if( zKey ){
  88214. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  88215. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  88216. return 1;
  88217. }
  88218. }
  88219. }
  88220. }
  88221. return 0;
  88222. }
  88223. /*
  88224. ** This function is called when inserting, deleting or updating a row of
  88225. ** table pTab to generate VDBE code to perform foreign key constraint
  88226. ** processing for the operation.
  88227. **
  88228. ** For a DELETE operation, parameter regOld is passed the index of the
  88229. ** first register in an array of (pTab->nCol+1) registers containing the
  88230. ** rowid of the row being deleted, followed by each of the column values
  88231. ** of the row being deleted, from left to right. Parameter regNew is passed
  88232. ** zero in this case.
  88233. **
  88234. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  88235. ** first register of an array of (pTab->nCol+1) registers containing the new
  88236. ** row data.
  88237. **
  88238. ** For an UPDATE operation, this function is called twice. Once before
  88239. ** the original record is deleted from the table using the calling convention
  88240. ** described for DELETE. Then again after the original record is deleted
  88241. ** but before the new record is inserted using the INSERT convention.
  88242. */
  88243. SQLITE_PRIVATE void sqlite3FkCheck(
  88244. Parse *pParse, /* Parse context */
  88245. Table *pTab, /* Row is being deleted from this table */
  88246. int regOld, /* Previous row data is stored here */
  88247. int regNew, /* New row data is stored here */
  88248. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  88249. int bChngRowid /* True if rowid is UPDATEd */
  88250. ){
  88251. sqlite3 *db = pParse->db; /* Database handle */
  88252. FKey *pFKey; /* Used to iterate through FKs */
  88253. int iDb; /* Index of database containing pTab */
  88254. const char *zDb; /* Name of database containing pTab */
  88255. int isIgnoreErrors = pParse->disableTriggers;
  88256. /* Exactly one of regOld and regNew should be non-zero. */
  88257. assert( (regOld==0)!=(regNew==0) );
  88258. /* If foreign-keys are disabled, this function is a no-op. */
  88259. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  88260. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88261. zDb = db->aDb[iDb].zName;
  88262. /* Loop through all the foreign key constraints for which pTab is the
  88263. ** child table (the table that the foreign key definition is part of). */
  88264. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  88265. Table *pTo; /* Parent table of foreign key pFKey */
  88266. Index *pIdx = 0; /* Index on key columns in pTo */
  88267. int *aiFree = 0;
  88268. int *aiCol;
  88269. int iCol;
  88270. int i;
  88271. int isIgnore = 0;
  88272. if( aChange
  88273. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  88274. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  88275. ){
  88276. continue;
  88277. }
  88278. /* Find the parent table of this foreign key. Also find a unique index
  88279. ** on the parent key columns in the parent table. If either of these
  88280. ** schema items cannot be located, set an error in pParse and return
  88281. ** early. */
  88282. if( pParse->disableTriggers ){
  88283. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  88284. }else{
  88285. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  88286. }
  88287. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  88288. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  88289. if( !isIgnoreErrors || db->mallocFailed ) return;
  88290. if( pTo==0 ){
  88291. /* If isIgnoreErrors is true, then a table is being dropped. In this
  88292. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  88293. ** before actually dropping it in order to check FK constraints.
  88294. ** If the parent table of an FK constraint on the current table is
  88295. ** missing, behave as if it is empty. i.e. decrement the relevant
  88296. ** FK counter for each row of the current table with non-NULL keys.
  88297. */
  88298. Vdbe *v = sqlite3GetVdbe(pParse);
  88299. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  88300. for(i=0; i<pFKey->nCol; i++){
  88301. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  88302. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  88303. }
  88304. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  88305. }
  88306. continue;
  88307. }
  88308. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  88309. if( aiFree ){
  88310. aiCol = aiFree;
  88311. }else{
  88312. iCol = pFKey->aCol[0].iFrom;
  88313. aiCol = &iCol;
  88314. }
  88315. for(i=0; i<pFKey->nCol; i++){
  88316. if( aiCol[i]==pTab->iPKey ){
  88317. aiCol[i] = -1;
  88318. }
  88319. #ifndef SQLITE_OMIT_AUTHORIZATION
  88320. /* Request permission to read the parent key columns. If the
  88321. ** authorization callback returns SQLITE_IGNORE, behave as if any
  88322. ** values read from the parent table are NULL. */
  88323. if( db->xAuth ){
  88324. int rcauth;
  88325. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  88326. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  88327. isIgnore = (rcauth==SQLITE_IGNORE);
  88328. }
  88329. #endif
  88330. }
  88331. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  88332. ** a cursor to use to search the unique index on the parent key columns
  88333. ** in the parent table. */
  88334. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  88335. pParse->nTab++;
  88336. if( regOld!=0 ){
  88337. /* A row is being removed from the child table. Search for the parent.
  88338. ** If the parent does not exist, removing the child row resolves an
  88339. ** outstanding foreign key constraint violation. */
  88340. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  88341. }
  88342. if( regNew!=0 ){
  88343. /* A row is being added to the child table. If a parent row cannot
  88344. ** be found, adding the child row has violated the FK constraint. */
  88345. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  88346. }
  88347. sqlite3DbFree(db, aiFree);
  88348. }
  88349. /* Loop through all the foreign key constraints that refer to this table */
  88350. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  88351. Index *pIdx = 0; /* Foreign key index for pFKey */
  88352. SrcList *pSrc;
  88353. int *aiCol = 0;
  88354. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  88355. continue;
  88356. }
  88357. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  88358. && !pParse->pToplevel && !pParse->isMultiWrite
  88359. ){
  88360. assert( regOld==0 && regNew!=0 );
  88361. /* Inserting a single row into a parent table cannot cause an immediate
  88362. ** foreign key violation. So do nothing in this case. */
  88363. continue;
  88364. }
  88365. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  88366. if( !isIgnoreErrors || db->mallocFailed ) return;
  88367. continue;
  88368. }
  88369. assert( aiCol || pFKey->nCol==1 );
  88370. /* Create a SrcList structure containing a single table (the table
  88371. ** the foreign key that refers to this table is attached to). This
  88372. ** is required for the sqlite3WhereXXX() interface. */
  88373. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  88374. if( pSrc ){
  88375. struct SrcList_item *pItem = pSrc->a;
  88376. pItem->pTab = pFKey->pFrom;
  88377. pItem->zName = pFKey->pFrom->zName;
  88378. pItem->pTab->nRef++;
  88379. pItem->iCursor = pParse->nTab++;
  88380. if( regNew!=0 ){
  88381. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  88382. }
  88383. if( regOld!=0 ){
  88384. /* If there is a RESTRICT action configured for the current operation
  88385. ** on the parent table of this FK, then throw an exception
  88386. ** immediately if the FK constraint is violated, even if this is a
  88387. ** deferred trigger. That's what RESTRICT means. To defer checking
  88388. ** the constraint, the FK should specify NO ACTION (represented
  88389. ** using OE_None). NO ACTION is the default. */
  88390. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  88391. }
  88392. pItem->zName = 0;
  88393. sqlite3SrcListDelete(db, pSrc);
  88394. }
  88395. sqlite3DbFree(db, aiCol);
  88396. }
  88397. }
  88398. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  88399. /*
  88400. ** This function is called before generating code to update or delete a
  88401. ** row contained in table pTab.
  88402. */
  88403. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  88404. Parse *pParse, /* Parse context */
  88405. Table *pTab /* Table being modified */
  88406. ){
  88407. u32 mask = 0;
  88408. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88409. FKey *p;
  88410. int i;
  88411. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88412. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  88413. }
  88414. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  88415. Index *pIdx = 0;
  88416. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  88417. if( pIdx ){
  88418. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  88419. }
  88420. }
  88421. }
  88422. return mask;
  88423. }
  88424. /*
  88425. ** This function is called before generating code to update or delete a
  88426. ** row contained in table pTab. If the operation is a DELETE, then
  88427. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  88428. ** to an array of size N, where N is the number of columns in table pTab.
  88429. ** If the i'th column is not modified by the UPDATE, then the corresponding
  88430. ** entry in the aChange[] array is set to -1. If the column is modified,
  88431. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  88432. ** UPDATE statement modifies the rowid fields of the table.
  88433. **
  88434. ** If any foreign key processing will be required, this function returns
  88435. ** true. If there is no foreign key related processing, this function
  88436. ** returns false.
  88437. */
  88438. SQLITE_PRIVATE int sqlite3FkRequired(
  88439. Parse *pParse, /* Parse context */
  88440. Table *pTab, /* Table being modified */
  88441. int *aChange, /* Non-NULL for UPDATE operations */
  88442. int chngRowid /* True for UPDATE that affects rowid */
  88443. ){
  88444. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88445. if( !aChange ){
  88446. /* A DELETE operation. Foreign key processing is required if the
  88447. ** table in question is either the child or parent table for any
  88448. ** foreign key constraint. */
  88449. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  88450. }else{
  88451. /* This is an UPDATE. Foreign key processing is only required if the
  88452. ** operation modifies one or more child or parent key columns. */
  88453. FKey *p;
  88454. /* Check if any child key columns are being modified. */
  88455. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88456. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  88457. }
  88458. /* Check if any parent key columns are being modified. */
  88459. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  88460. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  88461. }
  88462. }
  88463. }
  88464. return 0;
  88465. }
  88466. /*
  88467. ** This function is called when an UPDATE or DELETE operation is being
  88468. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  88469. ** If the current operation is an UPDATE, then the pChanges parameter is
  88470. ** passed a pointer to the list of columns being modified. If it is a
  88471. ** DELETE, pChanges is passed a NULL pointer.
  88472. **
  88473. ** It returns a pointer to a Trigger structure containing a trigger
  88474. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  88475. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  88476. ** returned (these actions require no special handling by the triggers
  88477. ** sub-system, code for them is created by fkScanChildren()).
  88478. **
  88479. ** For example, if pFKey is the foreign key and pTab is table "p" in
  88480. ** the following schema:
  88481. **
  88482. ** CREATE TABLE p(pk PRIMARY KEY);
  88483. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  88484. **
  88485. ** then the returned trigger structure is equivalent to:
  88486. **
  88487. ** CREATE TRIGGER ... DELETE ON p BEGIN
  88488. ** DELETE FROM c WHERE ck = old.pk;
  88489. ** END;
  88490. **
  88491. ** The returned pointer is cached as part of the foreign key object. It
  88492. ** is eventually freed along with the rest of the foreign key object by
  88493. ** sqlite3FkDelete().
  88494. */
  88495. static Trigger *fkActionTrigger(
  88496. Parse *pParse, /* Parse context */
  88497. Table *pTab, /* Table being updated or deleted from */
  88498. FKey *pFKey, /* Foreign key to get action for */
  88499. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  88500. ){
  88501. sqlite3 *db = pParse->db; /* Database handle */
  88502. int action; /* One of OE_None, OE_Cascade etc. */
  88503. Trigger *pTrigger; /* Trigger definition to return */
  88504. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  88505. action = pFKey->aAction[iAction];
  88506. pTrigger = pFKey->apTrigger[iAction];
  88507. if( action!=OE_None && !pTrigger ){
  88508. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  88509. char const *zFrom; /* Name of child table */
  88510. int nFrom; /* Length in bytes of zFrom */
  88511. Index *pIdx = 0; /* Parent key index for this FK */
  88512. int *aiCol = 0; /* child table cols -> parent key cols */
  88513. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  88514. Expr *pWhere = 0; /* WHERE clause of trigger step */
  88515. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  88516. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  88517. int i; /* Iterator variable */
  88518. Expr *pWhen = 0; /* WHEN clause for the trigger */
  88519. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  88520. assert( aiCol || pFKey->nCol==1 );
  88521. for(i=0; i<pFKey->nCol; i++){
  88522. Token tOld = { "old", 3 }; /* Literal "old" token */
  88523. Token tNew = { "new", 3 }; /* Literal "new" token */
  88524. Token tFromCol; /* Name of column in child table */
  88525. Token tToCol; /* Name of column in parent table */
  88526. int iFromCol; /* Idx of column in child table */
  88527. Expr *pEq; /* tFromCol = OLD.tToCol */
  88528. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  88529. assert( iFromCol>=0 );
  88530. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  88531. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  88532. tToCol.n = sqlite3Strlen30(tToCol.z);
  88533. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  88534. /* Create the expression "OLD.zToCol = zFromCol". It is important
  88535. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  88536. ** that the affinity and collation sequence associated with the
  88537. ** parent table are used for the comparison. */
  88538. pEq = sqlite3PExpr(pParse, TK_EQ,
  88539. sqlite3PExpr(pParse, TK_DOT,
  88540. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  88541. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  88542. , 0),
  88543. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  88544. , 0);
  88545. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88546. /* For ON UPDATE, construct the next term of the WHEN clause.
  88547. ** The final WHEN clause will be like this:
  88548. **
  88549. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  88550. */
  88551. if( pChanges ){
  88552. pEq = sqlite3PExpr(pParse, TK_IS,
  88553. sqlite3PExpr(pParse, TK_DOT,
  88554. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  88555. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  88556. 0),
  88557. sqlite3PExpr(pParse, TK_DOT,
  88558. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  88559. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  88560. 0),
  88561. 0);
  88562. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  88563. }
  88564. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  88565. Expr *pNew;
  88566. if( action==OE_Cascade ){
  88567. pNew = sqlite3PExpr(pParse, TK_DOT,
  88568. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  88569. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  88570. , 0);
  88571. }else if( action==OE_SetDflt ){
  88572. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  88573. if( pDflt ){
  88574. pNew = sqlite3ExprDup(db, pDflt, 0);
  88575. }else{
  88576. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  88577. }
  88578. }else{
  88579. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  88580. }
  88581. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  88582. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  88583. }
  88584. }
  88585. sqlite3DbFree(db, aiCol);
  88586. zFrom = pFKey->pFrom->zName;
  88587. nFrom = sqlite3Strlen30(zFrom);
  88588. if( action==OE_Restrict ){
  88589. Token tFrom;
  88590. Expr *pRaise;
  88591. tFrom.z = zFrom;
  88592. tFrom.n = nFrom;
  88593. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  88594. if( pRaise ){
  88595. pRaise->affinity = OE_Abort;
  88596. }
  88597. pSelect = sqlite3SelectNew(pParse,
  88598. sqlite3ExprListAppend(pParse, 0, pRaise),
  88599. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  88600. pWhere,
  88601. 0, 0, 0, 0, 0, 0
  88602. );
  88603. pWhere = 0;
  88604. }
  88605. /* Disable lookaside memory allocation */
  88606. enableLookaside = db->lookaside.bEnabled;
  88607. db->lookaside.bEnabled = 0;
  88608. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  88609. sizeof(Trigger) + /* struct Trigger */
  88610. sizeof(TriggerStep) + /* Single step in trigger program */
  88611. nFrom + 1 /* Space for pStep->target.z */
  88612. );
  88613. if( pTrigger ){
  88614. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  88615. pStep->target.z = (char *)&pStep[1];
  88616. pStep->target.n = nFrom;
  88617. memcpy((char *)pStep->target.z, zFrom, nFrom);
  88618. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  88619. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  88620. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  88621. if( pWhen ){
  88622. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  88623. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  88624. }
  88625. }
  88626. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  88627. db->lookaside.bEnabled = enableLookaside;
  88628. sqlite3ExprDelete(db, pWhere);
  88629. sqlite3ExprDelete(db, pWhen);
  88630. sqlite3ExprListDelete(db, pList);
  88631. sqlite3SelectDelete(db, pSelect);
  88632. if( db->mallocFailed==1 ){
  88633. fkTriggerDelete(db, pTrigger);
  88634. return 0;
  88635. }
  88636. assert( pStep!=0 );
  88637. switch( action ){
  88638. case OE_Restrict:
  88639. pStep->op = TK_SELECT;
  88640. break;
  88641. case OE_Cascade:
  88642. if( !pChanges ){
  88643. pStep->op = TK_DELETE;
  88644. break;
  88645. }
  88646. default:
  88647. pStep->op = TK_UPDATE;
  88648. }
  88649. pStep->pTrig = pTrigger;
  88650. pTrigger->pSchema = pTab->pSchema;
  88651. pTrigger->pTabSchema = pTab->pSchema;
  88652. pFKey->apTrigger[iAction] = pTrigger;
  88653. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  88654. }
  88655. return pTrigger;
  88656. }
  88657. /*
  88658. ** This function is called when deleting or updating a row to implement
  88659. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  88660. */
  88661. SQLITE_PRIVATE void sqlite3FkActions(
  88662. Parse *pParse, /* Parse context */
  88663. Table *pTab, /* Table being updated or deleted from */
  88664. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  88665. int regOld, /* Address of array containing old row */
  88666. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  88667. int bChngRowid /* True if rowid is UPDATEd */
  88668. ){
  88669. /* If foreign-key support is enabled, iterate through all FKs that
  88670. ** refer to table pTab. If there is an action associated with the FK
  88671. ** for this operation (either update or delete), invoke the associated
  88672. ** trigger sub-program. */
  88673. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88674. FKey *pFKey; /* Iterator variable */
  88675. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  88676. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  88677. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  88678. if( pAct ){
  88679. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  88680. }
  88681. }
  88682. }
  88683. }
  88684. }
  88685. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  88686. /*
  88687. ** Free all memory associated with foreign key definitions attached to
  88688. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  88689. ** hash table.
  88690. */
  88691. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  88692. FKey *pFKey; /* Iterator variable */
  88693. FKey *pNext; /* Copy of pFKey->pNextFrom */
  88694. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  88695. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  88696. /* Remove the FK from the fkeyHash hash table. */
  88697. if( !db || db->pnBytesFreed==0 ){
  88698. if( pFKey->pPrevTo ){
  88699. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  88700. }else{
  88701. void *p = (void *)pFKey->pNextTo;
  88702. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  88703. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  88704. }
  88705. if( pFKey->pNextTo ){
  88706. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  88707. }
  88708. }
  88709. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  88710. ** classified as either immediate or deferred.
  88711. */
  88712. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  88713. /* Delete any triggers created to implement actions for this FK. */
  88714. #ifndef SQLITE_OMIT_TRIGGER
  88715. fkTriggerDelete(db, pFKey->apTrigger[0]);
  88716. fkTriggerDelete(db, pFKey->apTrigger[1]);
  88717. #endif
  88718. pNext = pFKey->pNextFrom;
  88719. sqlite3DbFree(db, pFKey);
  88720. }
  88721. }
  88722. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  88723. /************** End of fkey.c ************************************************/
  88724. /************** Begin file insert.c ******************************************/
  88725. /*
  88726. ** 2001 September 15
  88727. **
  88728. ** The author disclaims copyright to this source code. In place of
  88729. ** a legal notice, here is a blessing:
  88730. **
  88731. ** May you do good and not evil.
  88732. ** May you find forgiveness for yourself and forgive others.
  88733. ** May you share freely, never taking more than you give.
  88734. **
  88735. *************************************************************************
  88736. ** This file contains C code routines that are called by the parser
  88737. ** to handle INSERT statements in SQLite.
  88738. */
  88739. /*
  88740. ** Generate code that will open a table for reading.
  88741. */
  88742. SQLITE_PRIVATE void sqlite3OpenTable(
  88743. Parse *p, /* Generate code into this VDBE */
  88744. int iCur, /* The cursor number of the table */
  88745. int iDb, /* The database index in sqlite3.aDb[] */
  88746. Table *pTab, /* The table to be opened */
  88747. int opcode /* OP_OpenRead or OP_OpenWrite */
  88748. ){
  88749. Vdbe *v;
  88750. assert( !IsVirtual(pTab) );
  88751. v = sqlite3GetVdbe(p);
  88752. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  88753. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  88754. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  88755. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  88756. VdbeComment((v, "%s", pTab->zName));
  88757. }
  88758. /*
  88759. ** Return a pointer to the column affinity string associated with index
  88760. ** pIdx. A column affinity string has one character for each column in
  88761. ** the table, according to the affinity of the column:
  88762. **
  88763. ** Character Column affinity
  88764. ** ------------------------------
  88765. ** 'a' TEXT
  88766. ** 'b' NONE
  88767. ** 'c' NUMERIC
  88768. ** 'd' INTEGER
  88769. ** 'e' REAL
  88770. **
  88771. ** An extra 'd' is appended to the end of the string to cover the
  88772. ** rowid that appears as the last column in every index.
  88773. **
  88774. ** Memory for the buffer containing the column index affinity string
  88775. ** is managed along with the rest of the Index structure. It will be
  88776. ** released when sqlite3DeleteIndex() is called.
  88777. */
  88778. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  88779. if( !pIdx->zColAff ){
  88780. /* The first time a column affinity string for a particular index is
  88781. ** required, it is allocated and populated here. It is then stored as
  88782. ** a member of the Index structure for subsequent use.
  88783. **
  88784. ** The column affinity string will eventually be deleted by
  88785. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  88786. ** up.
  88787. */
  88788. int n;
  88789. Table *pTab = pIdx->pTable;
  88790. sqlite3 *db = sqlite3VdbeDb(v);
  88791. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  88792. if( !pIdx->zColAff ){
  88793. db->mallocFailed = 1;
  88794. return 0;
  88795. }
  88796. for(n=0; n<pIdx->nColumn; n++){
  88797. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  88798. }
  88799. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  88800. pIdx->zColAff[n] = 0;
  88801. }
  88802. return pIdx->zColAff;
  88803. }
  88804. /*
  88805. ** Set P4 of the most recently inserted opcode to a column affinity
  88806. ** string for table pTab. A column affinity string has one character
  88807. ** for each column indexed by the index, according to the affinity of the
  88808. ** column:
  88809. **
  88810. ** Character Column affinity
  88811. ** ------------------------------
  88812. ** 'a' TEXT
  88813. ** 'b' NONE
  88814. ** 'c' NUMERIC
  88815. ** 'd' INTEGER
  88816. ** 'e' REAL
  88817. */
  88818. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  88819. /* The first time a column affinity string for a particular table
  88820. ** is required, it is allocated and populated here. It is then
  88821. ** stored as a member of the Table structure for subsequent use.
  88822. **
  88823. ** The column affinity string will eventually be deleted by
  88824. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  88825. */
  88826. if( !pTab->zColAff ){
  88827. char *zColAff;
  88828. int i;
  88829. sqlite3 *db = sqlite3VdbeDb(v);
  88830. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  88831. if( !zColAff ){
  88832. db->mallocFailed = 1;
  88833. return;
  88834. }
  88835. for(i=0; i<pTab->nCol; i++){
  88836. zColAff[i] = pTab->aCol[i].affinity;
  88837. }
  88838. zColAff[pTab->nCol] = '\0';
  88839. pTab->zColAff = zColAff;
  88840. }
  88841. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  88842. }
  88843. /*
  88844. ** Return non-zero if the table pTab in database iDb or any of its indices
  88845. ** have been opened at any point in the VDBE program beginning at location
  88846. ** iStartAddr throught the end of the program. This is used to see if
  88847. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  88848. ** run without using temporary table for the results of the SELECT.
  88849. */
  88850. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  88851. Vdbe *v = sqlite3GetVdbe(p);
  88852. int i;
  88853. int iEnd = sqlite3VdbeCurrentAddr(v);
  88854. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88855. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  88856. #endif
  88857. for(i=iStartAddr; i<iEnd; i++){
  88858. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  88859. assert( pOp!=0 );
  88860. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  88861. Index *pIndex;
  88862. int tnum = pOp->p2;
  88863. if( tnum==pTab->tnum ){
  88864. return 1;
  88865. }
  88866. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  88867. if( tnum==pIndex->tnum ){
  88868. return 1;
  88869. }
  88870. }
  88871. }
  88872. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88873. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  88874. assert( pOp->p4.pVtab!=0 );
  88875. assert( pOp->p4type==P4_VTAB );
  88876. return 1;
  88877. }
  88878. #endif
  88879. }
  88880. return 0;
  88881. }
  88882. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88883. /*
  88884. ** Locate or create an AutoincInfo structure associated with table pTab
  88885. ** which is in database iDb. Return the register number for the register
  88886. ** that holds the maximum rowid.
  88887. **
  88888. ** There is at most one AutoincInfo structure per table even if the
  88889. ** same table is autoincremented multiple times due to inserts within
  88890. ** triggers. A new AutoincInfo structure is created if this is the
  88891. ** first use of table pTab. On 2nd and subsequent uses, the original
  88892. ** AutoincInfo structure is used.
  88893. **
  88894. ** Three memory locations are allocated:
  88895. **
  88896. ** (1) Register to hold the name of the pTab table.
  88897. ** (2) Register to hold the maximum ROWID of pTab.
  88898. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  88899. **
  88900. ** The 2nd register is the one that is returned. That is all the
  88901. ** insert routine needs to know about.
  88902. */
  88903. static int autoIncBegin(
  88904. Parse *pParse, /* Parsing context */
  88905. int iDb, /* Index of the database holding pTab */
  88906. Table *pTab /* The table we are writing to */
  88907. ){
  88908. int memId = 0; /* Register holding maximum rowid */
  88909. if( pTab->tabFlags & TF_Autoincrement ){
  88910. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88911. AutoincInfo *pInfo;
  88912. pInfo = pToplevel->pAinc;
  88913. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  88914. if( pInfo==0 ){
  88915. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  88916. if( pInfo==0 ) return 0;
  88917. pInfo->pNext = pToplevel->pAinc;
  88918. pToplevel->pAinc = pInfo;
  88919. pInfo->pTab = pTab;
  88920. pInfo->iDb = iDb;
  88921. pToplevel->nMem++; /* Register to hold name of table */
  88922. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  88923. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  88924. }
  88925. memId = pInfo->regCtr;
  88926. }
  88927. return memId;
  88928. }
  88929. /*
  88930. ** This routine generates code that will initialize all of the
  88931. ** register used by the autoincrement tracker.
  88932. */
  88933. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  88934. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  88935. sqlite3 *db = pParse->db; /* The database connection */
  88936. Db *pDb; /* Database only autoinc table */
  88937. int memId; /* Register holding max rowid */
  88938. int addr; /* A VDBE address */
  88939. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  88940. /* This routine is never called during trigger-generation. It is
  88941. ** only called from the top-level */
  88942. assert( pParse->pTriggerTab==0 );
  88943. assert( pParse==sqlite3ParseToplevel(pParse) );
  88944. assert( v ); /* We failed long ago if this is not so */
  88945. for(p = pParse->pAinc; p; p = p->pNext){
  88946. pDb = &db->aDb[p->iDb];
  88947. memId = p->regCtr;
  88948. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  88949. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  88950. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  88951. addr = sqlite3VdbeCurrentAddr(v);
  88952. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  88953. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  88954. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  88955. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  88956. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  88957. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  88958. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  88959. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  88960. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  88961. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  88962. sqlite3VdbeAddOp0(v, OP_Close);
  88963. }
  88964. }
  88965. /*
  88966. ** Update the maximum rowid for an autoincrement calculation.
  88967. **
  88968. ** This routine should be called when the top of the stack holds a
  88969. ** new rowid that is about to be inserted. If that new rowid is
  88970. ** larger than the maximum rowid in the memId memory cell, then the
  88971. ** memory cell is updated. The stack is unchanged.
  88972. */
  88973. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  88974. if( memId>0 ){
  88975. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  88976. }
  88977. }
  88978. /*
  88979. ** This routine generates the code needed to write autoincrement
  88980. ** maximum rowid values back into the sqlite_sequence register.
  88981. ** Every statement that might do an INSERT into an autoincrement
  88982. ** table (either directly or through triggers) needs to call this
  88983. ** routine just before the "exit" code.
  88984. */
  88985. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  88986. AutoincInfo *p;
  88987. Vdbe *v = pParse->pVdbe;
  88988. sqlite3 *db = pParse->db;
  88989. assert( v );
  88990. for(p = pParse->pAinc; p; p = p->pNext){
  88991. Db *pDb = &db->aDb[p->iDb];
  88992. int j1, j2, j3, j4, j5;
  88993. int iRec;
  88994. int memId = p->regCtr;
  88995. iRec = sqlite3GetTempReg(pParse);
  88996. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  88997. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  88998. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  88999. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  89000. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  89001. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  89002. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  89003. sqlite3VdbeJumpHere(v, j2);
  89004. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  89005. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  89006. sqlite3VdbeJumpHere(v, j4);
  89007. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  89008. sqlite3VdbeJumpHere(v, j1);
  89009. sqlite3VdbeJumpHere(v, j5);
  89010. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  89011. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  89012. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  89013. sqlite3VdbeAddOp0(v, OP_Close);
  89014. sqlite3ReleaseTempReg(pParse, iRec);
  89015. }
  89016. }
  89017. #else
  89018. /*
  89019. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  89020. ** above are all no-ops
  89021. */
  89022. # define autoIncBegin(A,B,C) (0)
  89023. # define autoIncStep(A,B,C)
  89024. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  89025. /*
  89026. ** Generate code for a co-routine that will evaluate a subquery one
  89027. ** row at a time.
  89028. **
  89029. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  89030. ** Information about the location of co-routine and the registers it will use
  89031. ** is returned by filling in the pDest object.
  89032. **
  89033. ** Registers are allocated as follows:
  89034. **
  89035. ** pDest->iSDParm The register holding the next entry-point of the
  89036. ** co-routine. Run the co-routine to its next breakpoint
  89037. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  89038. **
  89039. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  89040. ** co-routine. This register is 0 if the previous Yield
  89041. ** generated a new result row, or 1 if the subquery
  89042. ** has completed. If the Yield is called again
  89043. ** after this register becomes 1, then the VDBE will
  89044. ** halt with an SQLITE_INTERNAL error.
  89045. **
  89046. ** pDest->iSdst First result register.
  89047. **
  89048. ** pDest->nSdst Number of result registers.
  89049. **
  89050. ** This routine handles all of the register allocation and fills in the
  89051. ** pDest structure appropriately.
  89052. **
  89053. ** Here is a schematic of the generated code assuming that X is the
  89054. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  89055. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  89056. ** registers that hold the result set, reg[pDest->iSdst] through
  89057. ** reg[pDest->iSdst+pDest->nSdst-1]:
  89058. **
  89059. ** X <- A
  89060. ** EOF <- 0
  89061. ** goto B
  89062. ** A: setup for the SELECT
  89063. ** loop rows in the SELECT
  89064. ** load results into registers R..S
  89065. ** yield X
  89066. ** end loop
  89067. ** cleanup after the SELECT
  89068. ** EOF <- 1
  89069. ** yield X
  89070. ** halt-error
  89071. ** B:
  89072. **
  89073. ** To use this subroutine, the caller generates code as follows:
  89074. **
  89075. ** [ Co-routine generated by this subroutine, shown above ]
  89076. ** S: yield X
  89077. ** if EOF goto E
  89078. ** if skip this row, goto C
  89079. ** if terminate loop, goto E
  89080. ** deal with this row
  89081. ** C: goto S
  89082. ** E:
  89083. */
  89084. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  89085. int regYield; /* Register holding co-routine entry-point */
  89086. int regEof; /* Register holding co-routine completion flag */
  89087. int addrTop; /* Top of the co-routine */
  89088. int j1; /* Jump instruction */
  89089. int rc; /* Result code */
  89090. Vdbe *v; /* VDBE under construction */
  89091. regYield = ++pParse->nMem;
  89092. regEof = ++pParse->nMem;
  89093. v = sqlite3GetVdbe(pParse);
  89094. addrTop = sqlite3VdbeCurrentAddr(v);
  89095. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  89096. VdbeComment((v, "Co-routine entry point"));
  89097. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  89098. VdbeComment((v, "Co-routine completion flag"));
  89099. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  89100. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  89101. rc = sqlite3Select(pParse, pSelect, pDest);
  89102. assert( pParse->nErr==0 || rc );
  89103. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  89104. if( rc ) return rc;
  89105. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  89106. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  89107. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  89108. VdbeComment((v, "End of coroutine"));
  89109. sqlite3VdbeJumpHere(v, j1); /* label B: */
  89110. return rc;
  89111. }
  89112. /* Forward declaration */
  89113. static int xferOptimization(
  89114. Parse *pParse, /* Parser context */
  89115. Table *pDest, /* The table we are inserting into */
  89116. Select *pSelect, /* A SELECT statement to use as the data source */
  89117. int onError, /* How to handle constraint errors */
  89118. int iDbDest /* The database of pDest */
  89119. );
  89120. /*
  89121. ** This routine is call to handle SQL of the following forms:
  89122. **
  89123. ** insert into TABLE (IDLIST) values(EXPRLIST)
  89124. ** insert into TABLE (IDLIST) select
  89125. **
  89126. ** The IDLIST following the table name is always optional. If omitted,
  89127. ** then a list of all columns for the table is substituted. The IDLIST
  89128. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  89129. **
  89130. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  89131. ** statement above, and pSelect is NULL. For the second form, pList is
  89132. ** NULL and pSelect is a pointer to the select statement used to generate
  89133. ** data for the insert.
  89134. **
  89135. ** The code generated follows one of four templates. For a simple
  89136. ** select with data coming from a VALUES clause, the code executes
  89137. ** once straight down through. Pseudo-code follows (we call this
  89138. ** the "1st template"):
  89139. **
  89140. ** open write cursor to <table> and its indices
  89141. ** puts VALUES clause expressions onto the stack
  89142. ** write the resulting record into <table>
  89143. ** cleanup
  89144. **
  89145. ** The three remaining templates assume the statement is of the form
  89146. **
  89147. ** INSERT INTO <table> SELECT ...
  89148. **
  89149. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  89150. ** in other words if the SELECT pulls all columns from a single table
  89151. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  89152. ** if <table2> and <table1> are distinct tables but have identical
  89153. ** schemas, including all the same indices, then a special optimization
  89154. ** is invoked that copies raw records from <table2> over to <table1>.
  89155. ** See the xferOptimization() function for the implementation of this
  89156. ** template. This is the 2nd template.
  89157. **
  89158. ** open a write cursor to <table>
  89159. ** open read cursor on <table2>
  89160. ** transfer all records in <table2> over to <table>
  89161. ** close cursors
  89162. ** foreach index on <table>
  89163. ** open a write cursor on the <table> index
  89164. ** open a read cursor on the corresponding <table2> index
  89165. ** transfer all records from the read to the write cursors
  89166. ** close cursors
  89167. ** end foreach
  89168. **
  89169. ** The 3rd template is for when the second template does not apply
  89170. ** and the SELECT clause does not read from <table> at any time.
  89171. ** The generated code follows this template:
  89172. **
  89173. ** EOF <- 0
  89174. ** X <- A
  89175. ** goto B
  89176. ** A: setup for the SELECT
  89177. ** loop over the rows in the SELECT
  89178. ** load values into registers R..R+n
  89179. ** yield X
  89180. ** end loop
  89181. ** cleanup after the SELECT
  89182. ** EOF <- 1
  89183. ** yield X
  89184. ** goto A
  89185. ** B: open write cursor to <table> and its indices
  89186. ** C: yield X
  89187. ** if EOF goto D
  89188. ** insert the select result into <table> from R..R+n
  89189. ** goto C
  89190. ** D: cleanup
  89191. **
  89192. ** The 4th template is used if the insert statement takes its
  89193. ** values from a SELECT but the data is being inserted into a table
  89194. ** that is also read as part of the SELECT. In the third form,
  89195. ** we have to use a intermediate table to store the results of
  89196. ** the select. The template is like this:
  89197. **
  89198. ** EOF <- 0
  89199. ** X <- A
  89200. ** goto B
  89201. ** A: setup for the SELECT
  89202. ** loop over the tables in the SELECT
  89203. ** load value into register R..R+n
  89204. ** yield X
  89205. ** end loop
  89206. ** cleanup after the SELECT
  89207. ** EOF <- 1
  89208. ** yield X
  89209. ** halt-error
  89210. ** B: open temp table
  89211. ** L: yield X
  89212. ** if EOF goto M
  89213. ** insert row from R..R+n into temp table
  89214. ** goto L
  89215. ** M: open write cursor to <table> and its indices
  89216. ** rewind temp table
  89217. ** C: loop over rows of intermediate table
  89218. ** transfer values form intermediate table into <table>
  89219. ** end loop
  89220. ** D: cleanup
  89221. */
  89222. SQLITE_PRIVATE void sqlite3Insert(
  89223. Parse *pParse, /* Parser context */
  89224. SrcList *pTabList, /* Name of table into which we are inserting */
  89225. ExprList *pList, /* List of values to be inserted */
  89226. Select *pSelect, /* A SELECT statement to use as the data source */
  89227. IdList *pColumn, /* Column names corresponding to IDLIST. */
  89228. int onError /* How to handle constraint errors */
  89229. ){
  89230. sqlite3 *db; /* The main database structure */
  89231. Table *pTab; /* The table to insert into. aka TABLE */
  89232. char *zTab; /* Name of the table into which we are inserting */
  89233. const char *zDb; /* Name of the database holding this table */
  89234. int i, j, idx; /* Loop counters */
  89235. Vdbe *v; /* Generate code into this virtual machine */
  89236. Index *pIdx; /* For looping over indices of the table */
  89237. int nColumn; /* Number of columns in the data */
  89238. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  89239. int baseCur = 0; /* VDBE Cursor number for pTab */
  89240. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  89241. int endOfLoop; /* Label for the end of the insertion loop */
  89242. int useTempTable = 0; /* Store SELECT results in intermediate table */
  89243. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  89244. int addrInsTop = 0; /* Jump to label "D" */
  89245. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  89246. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  89247. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  89248. int iDb; /* Index of database holding TABLE */
  89249. Db *pDb; /* The database containing table being inserted into */
  89250. int appendFlag = 0; /* True if the insert is likely to be an append */
  89251. /* Register allocations */
  89252. int regFromSelect = 0;/* Base register for data coming from SELECT */
  89253. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  89254. int regRowCount = 0; /* Memory cell used for the row counter */
  89255. int regIns; /* Block of regs holding rowid+data being inserted */
  89256. int regRowid; /* registers holding insert rowid */
  89257. int regData; /* register holding first column to insert */
  89258. int regEof = 0; /* Register recording end of SELECT data */
  89259. int *aRegIdx = 0; /* One register allocated to each index */
  89260. #ifndef SQLITE_OMIT_TRIGGER
  89261. int isView; /* True if attempting to insert into a view */
  89262. Trigger *pTrigger; /* List of triggers on pTab, if required */
  89263. int tmask; /* Mask of trigger times */
  89264. #endif
  89265. db = pParse->db;
  89266. memset(&dest, 0, sizeof(dest));
  89267. if( pParse->nErr || db->mallocFailed ){
  89268. goto insert_cleanup;
  89269. }
  89270. /* Locate the table into which we will be inserting new information.
  89271. */
  89272. assert( pTabList->nSrc==1 );
  89273. zTab = pTabList->a[0].zName;
  89274. if( NEVER(zTab==0) ) goto insert_cleanup;
  89275. pTab = sqlite3SrcListLookup(pParse, pTabList);
  89276. if( pTab==0 ){
  89277. goto insert_cleanup;
  89278. }
  89279. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89280. assert( iDb<db->nDb );
  89281. pDb = &db->aDb[iDb];
  89282. zDb = pDb->zName;
  89283. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  89284. goto insert_cleanup;
  89285. }
  89286. /* Figure out if we have any triggers and if the table being
  89287. ** inserted into is a view
  89288. */
  89289. #ifndef SQLITE_OMIT_TRIGGER
  89290. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  89291. isView = pTab->pSelect!=0;
  89292. #else
  89293. # define pTrigger 0
  89294. # define tmask 0
  89295. # define isView 0
  89296. #endif
  89297. #ifdef SQLITE_OMIT_VIEW
  89298. # undef isView
  89299. # define isView 0
  89300. #endif
  89301. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  89302. /* If pTab is really a view, make sure it has been initialized.
  89303. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  89304. ** module table).
  89305. */
  89306. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  89307. goto insert_cleanup;
  89308. }
  89309. /* Ensure that:
  89310. * (a) the table is not read-only,
  89311. * (b) that if it is a view then ON INSERT triggers exist
  89312. */
  89313. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  89314. goto insert_cleanup;
  89315. }
  89316. /* Allocate a VDBE
  89317. */
  89318. v = sqlite3GetVdbe(pParse);
  89319. if( v==0 ) goto insert_cleanup;
  89320. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  89321. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  89322. #ifndef SQLITE_OMIT_XFER_OPT
  89323. /* If the statement is of the form
  89324. **
  89325. ** INSERT INTO <table1> SELECT * FROM <table2>;
  89326. **
  89327. ** Then special optimizations can be applied that make the transfer
  89328. ** very fast and which reduce fragmentation of indices.
  89329. **
  89330. ** This is the 2nd template.
  89331. */
  89332. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  89333. assert( !pTrigger );
  89334. assert( pList==0 );
  89335. goto insert_end;
  89336. }
  89337. #endif /* SQLITE_OMIT_XFER_OPT */
  89338. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  89339. ** sqlite_sequence table and store it in memory cell regAutoinc.
  89340. */
  89341. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  89342. /* Figure out how many columns of data are supplied. If the data
  89343. ** is coming from a SELECT statement, then generate a co-routine that
  89344. ** produces a single row of the SELECT on each invocation. The
  89345. ** co-routine is the common header to the 3rd and 4th templates.
  89346. */
  89347. if( pSelect ){
  89348. /* Data is coming from a SELECT. Generate a co-routine to run that
  89349. ** SELECT. */
  89350. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  89351. if( rc ) goto insert_cleanup;
  89352. regEof = dest.iSDParm + 1;
  89353. regFromSelect = dest.iSdst;
  89354. assert( pSelect->pEList );
  89355. nColumn = pSelect->pEList->nExpr;
  89356. assert( dest.nSdst==nColumn );
  89357. /* Set useTempTable to TRUE if the result of the SELECT statement
  89358. ** should be written into a temporary table (template 4). Set to
  89359. ** FALSE if each* row of the SELECT can be written directly into
  89360. ** the destination table (template 3).
  89361. **
  89362. ** A temp table must be used if the table being updated is also one
  89363. ** of the tables being read by the SELECT statement. Also use a
  89364. ** temp table in the case of row triggers.
  89365. */
  89366. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  89367. useTempTable = 1;
  89368. }
  89369. if( useTempTable ){
  89370. /* Invoke the coroutine to extract information from the SELECT
  89371. ** and add it to a transient table srcTab. The code generated
  89372. ** here is from the 4th template:
  89373. **
  89374. ** B: open temp table
  89375. ** L: yield X
  89376. ** if EOF goto M
  89377. ** insert row from R..R+n into temp table
  89378. ** goto L
  89379. ** M: ...
  89380. */
  89381. int regRec; /* Register to hold packed record */
  89382. int regTempRowid; /* Register to hold temp table ROWID */
  89383. int addrTop; /* Label "L" */
  89384. int addrIf; /* Address of jump to M */
  89385. srcTab = pParse->nTab++;
  89386. regRec = sqlite3GetTempReg(pParse);
  89387. regTempRowid = sqlite3GetTempReg(pParse);
  89388. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  89389. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  89390. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  89391. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  89392. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  89393. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  89394. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  89395. sqlite3VdbeJumpHere(v, addrIf);
  89396. sqlite3ReleaseTempReg(pParse, regRec);
  89397. sqlite3ReleaseTempReg(pParse, regTempRowid);
  89398. }
  89399. }else{
  89400. /* This is the case if the data for the INSERT is coming from a VALUES
  89401. ** clause
  89402. */
  89403. NameContext sNC;
  89404. memset(&sNC, 0, sizeof(sNC));
  89405. sNC.pParse = pParse;
  89406. srcTab = -1;
  89407. assert( useTempTable==0 );
  89408. nColumn = pList ? pList->nExpr : 0;
  89409. for(i=0; i<nColumn; i++){
  89410. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  89411. goto insert_cleanup;
  89412. }
  89413. }
  89414. }
  89415. /* Make sure the number of columns in the source data matches the number
  89416. ** of columns to be inserted into the table.
  89417. */
  89418. if( IsVirtual(pTab) ){
  89419. for(i=0; i<pTab->nCol; i++){
  89420. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  89421. }
  89422. }
  89423. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  89424. sqlite3ErrorMsg(pParse,
  89425. "table %S has %d columns but %d values were supplied",
  89426. pTabList, 0, pTab->nCol-nHidden, nColumn);
  89427. goto insert_cleanup;
  89428. }
  89429. if( pColumn!=0 && nColumn!=pColumn->nId ){
  89430. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  89431. goto insert_cleanup;
  89432. }
  89433. /* If the INSERT statement included an IDLIST term, then make sure
  89434. ** all elements of the IDLIST really are columns of the table and
  89435. ** remember the column indices.
  89436. **
  89437. ** If the table has an INTEGER PRIMARY KEY column and that column
  89438. ** is named in the IDLIST, then record in the keyColumn variable
  89439. ** the index into IDLIST of the primary key column. keyColumn is
  89440. ** the index of the primary key as it appears in IDLIST, not as
  89441. ** is appears in the original table. (The index of the primary
  89442. ** key in the original table is pTab->iPKey.)
  89443. */
  89444. if( pColumn ){
  89445. for(i=0; i<pColumn->nId; i++){
  89446. pColumn->a[i].idx = -1;
  89447. }
  89448. for(i=0; i<pColumn->nId; i++){
  89449. for(j=0; j<pTab->nCol; j++){
  89450. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  89451. pColumn->a[i].idx = j;
  89452. if( j==pTab->iPKey ){
  89453. keyColumn = i;
  89454. }
  89455. break;
  89456. }
  89457. }
  89458. if( j>=pTab->nCol ){
  89459. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  89460. keyColumn = i;
  89461. }else{
  89462. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  89463. pTabList, 0, pColumn->a[i].zName);
  89464. pParse->checkSchema = 1;
  89465. goto insert_cleanup;
  89466. }
  89467. }
  89468. }
  89469. }
  89470. /* If there is no IDLIST term but the table has an integer primary
  89471. ** key, the set the keyColumn variable to the primary key column index
  89472. ** in the original table definition.
  89473. */
  89474. if( pColumn==0 && nColumn>0 ){
  89475. keyColumn = pTab->iPKey;
  89476. }
  89477. /* Initialize the count of rows to be inserted
  89478. */
  89479. if( db->flags & SQLITE_CountRows ){
  89480. regRowCount = ++pParse->nMem;
  89481. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  89482. }
  89483. /* If this is not a view, open the table and and all indices */
  89484. if( !isView ){
  89485. int nIdx;
  89486. baseCur = pParse->nTab;
  89487. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  89488. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  89489. if( aRegIdx==0 ){
  89490. goto insert_cleanup;
  89491. }
  89492. for(i=0; i<nIdx; i++){
  89493. aRegIdx[i] = ++pParse->nMem;
  89494. }
  89495. }
  89496. /* This is the top of the main insertion loop */
  89497. if( useTempTable ){
  89498. /* This block codes the top of loop only. The complete loop is the
  89499. ** following pseudocode (template 4):
  89500. **
  89501. ** rewind temp table
  89502. ** C: loop over rows of intermediate table
  89503. ** transfer values form intermediate table into <table>
  89504. ** end loop
  89505. ** D: ...
  89506. */
  89507. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  89508. addrCont = sqlite3VdbeCurrentAddr(v);
  89509. }else if( pSelect ){
  89510. /* This block codes the top of loop only. The complete loop is the
  89511. ** following pseudocode (template 3):
  89512. **
  89513. ** C: yield X
  89514. ** if EOF goto D
  89515. ** insert the select result into <table> from R..R+n
  89516. ** goto C
  89517. ** D: ...
  89518. */
  89519. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  89520. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  89521. }
  89522. /* Allocate registers for holding the rowid of the new row,
  89523. ** the content of the new row, and the assemblied row record.
  89524. */
  89525. regRowid = regIns = pParse->nMem+1;
  89526. pParse->nMem += pTab->nCol + 1;
  89527. if( IsVirtual(pTab) ){
  89528. regRowid++;
  89529. pParse->nMem++;
  89530. }
  89531. regData = regRowid+1;
  89532. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  89533. */
  89534. endOfLoop = sqlite3VdbeMakeLabel(v);
  89535. if( tmask & TRIGGER_BEFORE ){
  89536. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  89537. /* build the NEW.* reference row. Note that if there is an INTEGER
  89538. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  89539. ** translated into a unique ID for the row. But on a BEFORE trigger,
  89540. ** we do not know what the unique ID will be (because the insert has
  89541. ** not happened yet) so we substitute a rowid of -1
  89542. */
  89543. if( keyColumn<0 ){
  89544. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  89545. }else{
  89546. int j1;
  89547. if( useTempTable ){
  89548. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  89549. }else{
  89550. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  89551. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  89552. }
  89553. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  89554. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  89555. sqlite3VdbeJumpHere(v, j1);
  89556. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  89557. }
  89558. /* Cannot have triggers on a virtual table. If it were possible,
  89559. ** this block would have to account for hidden column.
  89560. */
  89561. assert( !IsVirtual(pTab) );
  89562. /* Create the new column data
  89563. */
  89564. for(i=0; i<pTab->nCol; i++){
  89565. if( pColumn==0 ){
  89566. j = i;
  89567. }else{
  89568. for(j=0; j<pColumn->nId; j++){
  89569. if( pColumn->a[j].idx==i ) break;
  89570. }
  89571. }
  89572. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  89573. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  89574. }else if( useTempTable ){
  89575. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  89576. }else{
  89577. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  89578. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  89579. }
  89580. }
  89581. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  89582. ** do not attempt any conversions before assembling the record.
  89583. ** If this is a real table, attempt conversions as required by the
  89584. ** table column affinities.
  89585. */
  89586. if( !isView ){
  89587. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  89588. sqlite3TableAffinityStr(v, pTab);
  89589. }
  89590. /* Fire BEFORE or INSTEAD OF triggers */
  89591. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  89592. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  89593. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  89594. }
  89595. /* Push the record number for the new entry onto the stack. The
  89596. ** record number is a randomly generate integer created by NewRowid
  89597. ** except when the table has an INTEGER PRIMARY KEY column, in which
  89598. ** case the record number is the same as that column.
  89599. */
  89600. if( !isView ){
  89601. if( IsVirtual(pTab) ){
  89602. /* The row that the VUpdate opcode will delete: none */
  89603. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  89604. }
  89605. if( keyColumn>=0 ){
  89606. if( useTempTable ){
  89607. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  89608. }else if( pSelect ){
  89609. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  89610. }else{
  89611. VdbeOp *pOp;
  89612. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  89613. pOp = sqlite3VdbeGetOp(v, -1);
  89614. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  89615. appendFlag = 1;
  89616. pOp->opcode = OP_NewRowid;
  89617. pOp->p1 = baseCur;
  89618. pOp->p2 = regRowid;
  89619. pOp->p3 = regAutoinc;
  89620. }
  89621. }
  89622. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  89623. ** to generate a unique primary key value.
  89624. */
  89625. if( !appendFlag ){
  89626. int j1;
  89627. if( !IsVirtual(pTab) ){
  89628. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  89629. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  89630. sqlite3VdbeJumpHere(v, j1);
  89631. }else{
  89632. j1 = sqlite3VdbeCurrentAddr(v);
  89633. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  89634. }
  89635. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  89636. }
  89637. }else if( IsVirtual(pTab) ){
  89638. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  89639. }else{
  89640. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  89641. appendFlag = 1;
  89642. }
  89643. autoIncStep(pParse, regAutoinc, regRowid);
  89644. /* Push onto the stack, data for all columns of the new entry, beginning
  89645. ** with the first column.
  89646. */
  89647. nHidden = 0;
  89648. for(i=0; i<pTab->nCol; i++){
  89649. int iRegStore = regRowid+1+i;
  89650. if( i==pTab->iPKey ){
  89651. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  89652. ** Whenever this column is read, the record number will be substituted
  89653. ** in its place. So will fill this column with a NULL to avoid
  89654. ** taking up data space with information that will never be used. */
  89655. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  89656. continue;
  89657. }
  89658. if( pColumn==0 ){
  89659. if( IsHiddenColumn(&pTab->aCol[i]) ){
  89660. assert( IsVirtual(pTab) );
  89661. j = -1;
  89662. nHidden++;
  89663. }else{
  89664. j = i - nHidden;
  89665. }
  89666. }else{
  89667. for(j=0; j<pColumn->nId; j++){
  89668. if( pColumn->a[j].idx==i ) break;
  89669. }
  89670. }
  89671. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  89672. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  89673. }else if( useTempTable ){
  89674. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  89675. }else if( pSelect ){
  89676. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  89677. }else{
  89678. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  89679. }
  89680. }
  89681. /* Generate code to check constraints and generate index keys and
  89682. ** do the insertion.
  89683. */
  89684. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89685. if( IsVirtual(pTab) ){
  89686. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  89687. sqlite3VtabMakeWritable(pParse, pTab);
  89688. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  89689. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  89690. sqlite3MayAbort(pParse);
  89691. }else
  89692. #endif
  89693. {
  89694. int isReplace; /* Set to true if constraints may cause a replace */
  89695. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  89696. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  89697. );
  89698. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  89699. sqlite3CompleteInsertion(
  89700. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  89701. );
  89702. }
  89703. }
  89704. /* Update the count of rows that are inserted
  89705. */
  89706. if( (db->flags & SQLITE_CountRows)!=0 ){
  89707. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  89708. }
  89709. if( pTrigger ){
  89710. /* Code AFTER triggers */
  89711. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  89712. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  89713. }
  89714. /* The bottom of the main insertion loop, if the data source
  89715. ** is a SELECT statement.
  89716. */
  89717. sqlite3VdbeResolveLabel(v, endOfLoop);
  89718. if( useTempTable ){
  89719. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  89720. sqlite3VdbeJumpHere(v, addrInsTop);
  89721. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  89722. }else if( pSelect ){
  89723. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  89724. sqlite3VdbeJumpHere(v, addrInsTop);
  89725. }
  89726. if( !IsVirtual(pTab) && !isView ){
  89727. /* Close all tables opened */
  89728. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  89729. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  89730. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  89731. }
  89732. }
  89733. insert_end:
  89734. /* Update the sqlite_sequence table by storing the content of the
  89735. ** maximum rowid counter values recorded while inserting into
  89736. ** autoincrement tables.
  89737. */
  89738. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  89739. sqlite3AutoincrementEnd(pParse);
  89740. }
  89741. /*
  89742. ** Return the number of rows inserted. If this routine is
  89743. ** generating code because of a call to sqlite3NestedParse(), do not
  89744. ** invoke the callback function.
  89745. */
  89746. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  89747. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  89748. sqlite3VdbeSetNumCols(v, 1);
  89749. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  89750. }
  89751. insert_cleanup:
  89752. sqlite3SrcListDelete(db, pTabList);
  89753. sqlite3ExprListDelete(db, pList);
  89754. sqlite3SelectDelete(db, pSelect);
  89755. sqlite3IdListDelete(db, pColumn);
  89756. sqlite3DbFree(db, aRegIdx);
  89757. }
  89758. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  89759. ** thely may interfere with compilation of other functions in this file
  89760. ** (or in another file, if this file becomes part of the amalgamation). */
  89761. #ifdef isView
  89762. #undef isView
  89763. #endif
  89764. #ifdef pTrigger
  89765. #undef pTrigger
  89766. #endif
  89767. #ifdef tmask
  89768. #undef tmask
  89769. #endif
  89770. /*
  89771. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  89772. **
  89773. ** The input is a range of consecutive registers as follows:
  89774. **
  89775. ** 1. The rowid of the row after the update.
  89776. **
  89777. ** 2. The data in the first column of the entry after the update.
  89778. **
  89779. ** i. Data from middle columns...
  89780. **
  89781. ** N. The data in the last column of the entry after the update.
  89782. **
  89783. ** The regRowid parameter is the index of the register containing (1).
  89784. **
  89785. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  89786. ** the address of a register containing the rowid before the update takes
  89787. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  89788. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  89789. ** indicates that the rowid was explicitly specified as part of the
  89790. ** INSERT statement. If rowidChng is false, it means that the rowid is
  89791. ** computed automatically in an insert or that the rowid value is not
  89792. ** modified by an update.
  89793. **
  89794. ** The code generated by this routine store new index entries into
  89795. ** registers identified by aRegIdx[]. No index entry is created for
  89796. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  89797. ** the same as the order of indices on the linked list of indices
  89798. ** attached to the table.
  89799. **
  89800. ** This routine also generates code to check constraints. NOT NULL,
  89801. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  89802. ** then the appropriate action is performed. There are five possible
  89803. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  89804. **
  89805. ** Constraint type Action What Happens
  89806. ** --------------- ---------- ----------------------------------------
  89807. ** any ROLLBACK The current transaction is rolled back and
  89808. ** sqlite3_exec() returns immediately with a
  89809. ** return code of SQLITE_CONSTRAINT.
  89810. **
  89811. ** any ABORT Back out changes from the current command
  89812. ** only (do not do a complete rollback) then
  89813. ** cause sqlite3_exec() to return immediately
  89814. ** with SQLITE_CONSTRAINT.
  89815. **
  89816. ** any FAIL Sqlite3_exec() returns immediately with a
  89817. ** return code of SQLITE_CONSTRAINT. The
  89818. ** transaction is not rolled back and any
  89819. ** prior changes are retained.
  89820. **
  89821. ** any IGNORE The record number and data is popped from
  89822. ** the stack and there is an immediate jump
  89823. ** to label ignoreDest.
  89824. **
  89825. ** NOT NULL REPLACE The NULL value is replace by the default
  89826. ** value for that column. If the default value
  89827. ** is NULL, the action is the same as ABORT.
  89828. **
  89829. ** UNIQUE REPLACE The other row that conflicts with the row
  89830. ** being inserted is removed.
  89831. **
  89832. ** CHECK REPLACE Illegal. The results in an exception.
  89833. **
  89834. ** Which action to take is determined by the overrideError parameter.
  89835. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  89836. ** is used. Or if pParse->onError==OE_Default then the onError value
  89837. ** for the constraint is used.
  89838. **
  89839. ** The calling routine must open a read/write cursor for pTab with
  89840. ** cursor number "baseCur". All indices of pTab must also have open
  89841. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  89842. ** Except, if there is no possibility of a REPLACE action then
  89843. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  89844. */
  89845. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  89846. Parse *pParse, /* The parser context */
  89847. Table *pTab, /* the table into which we are inserting */
  89848. int baseCur, /* Index of a read/write cursor pointing at pTab */
  89849. int regRowid, /* Index of the range of input registers */
  89850. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  89851. int rowidChng, /* True if the rowid might collide with existing entry */
  89852. int isUpdate, /* True for UPDATE, False for INSERT */
  89853. int overrideError, /* Override onError to this if not OE_Default */
  89854. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  89855. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  89856. ){
  89857. int i; /* loop counter */
  89858. Vdbe *v; /* VDBE under constrution */
  89859. int nCol; /* Number of columns */
  89860. int onError; /* Conflict resolution strategy */
  89861. int j1; /* Addresss of jump instruction */
  89862. int j2 = 0, j3; /* Addresses of jump instructions */
  89863. int regData; /* Register containing first data column */
  89864. int iCur; /* Table cursor number */
  89865. Index *pIdx; /* Pointer to one of the indices */
  89866. sqlite3 *db; /* Database connection */
  89867. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  89868. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  89869. db = pParse->db;
  89870. v = sqlite3GetVdbe(pParse);
  89871. assert( v!=0 );
  89872. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  89873. nCol = pTab->nCol;
  89874. regData = regRowid + 1;
  89875. /* Test all NOT NULL constraints.
  89876. */
  89877. for(i=0; i<nCol; i++){
  89878. if( i==pTab->iPKey ){
  89879. continue;
  89880. }
  89881. onError = pTab->aCol[i].notNull;
  89882. if( onError==OE_None ) continue;
  89883. if( overrideError!=OE_Default ){
  89884. onError = overrideError;
  89885. }else if( onError==OE_Default ){
  89886. onError = OE_Abort;
  89887. }
  89888. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  89889. onError = OE_Abort;
  89890. }
  89891. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  89892. || onError==OE_Ignore || onError==OE_Replace );
  89893. switch( onError ){
  89894. case OE_Abort:
  89895. sqlite3MayAbort(pParse);
  89896. case OE_Rollback:
  89897. case OE_Fail: {
  89898. char *zMsg;
  89899. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  89900. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  89901. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  89902. pTab->zName, pTab->aCol[i].zName);
  89903. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  89904. break;
  89905. }
  89906. case OE_Ignore: {
  89907. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  89908. break;
  89909. }
  89910. default: {
  89911. assert( onError==OE_Replace );
  89912. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  89913. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  89914. sqlite3VdbeJumpHere(v, j1);
  89915. break;
  89916. }
  89917. }
  89918. }
  89919. /* Test all CHECK constraints
  89920. */
  89921. #ifndef SQLITE_OMIT_CHECK
  89922. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  89923. ExprList *pCheck = pTab->pCheck;
  89924. pParse->ckBase = regData;
  89925. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  89926. for(i=0; i<pCheck->nExpr; i++){
  89927. int allOk = sqlite3VdbeMakeLabel(v);
  89928. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  89929. if( onError==OE_Ignore ){
  89930. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  89931. }else{
  89932. char *zConsName = pCheck->a[i].zName;
  89933. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  89934. if( zConsName ){
  89935. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  89936. }else{
  89937. zConsName = 0;
  89938. }
  89939. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  89940. onError, zConsName, P4_DYNAMIC);
  89941. }
  89942. sqlite3VdbeResolveLabel(v, allOk);
  89943. }
  89944. }
  89945. #endif /* !defined(SQLITE_OMIT_CHECK) */
  89946. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  89947. ** of the new record does not previously exist. Except, if this
  89948. ** is an UPDATE and the primary key is not changing, that is OK.
  89949. */
  89950. if( rowidChng ){
  89951. onError = pTab->keyConf;
  89952. if( overrideError!=OE_Default ){
  89953. onError = overrideError;
  89954. }else if( onError==OE_Default ){
  89955. onError = OE_Abort;
  89956. }
  89957. if( isUpdate ){
  89958. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  89959. }
  89960. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  89961. switch( onError ){
  89962. default: {
  89963. onError = OE_Abort;
  89964. /* Fall thru into the next case */
  89965. }
  89966. case OE_Rollback:
  89967. case OE_Abort:
  89968. case OE_Fail: {
  89969. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  89970. onError, "PRIMARY KEY must be unique", P4_STATIC);
  89971. break;
  89972. }
  89973. case OE_Replace: {
  89974. /* If there are DELETE triggers on this table and the
  89975. ** recursive-triggers flag is set, call GenerateRowDelete() to
  89976. ** remove the conflicting row from the table. This will fire
  89977. ** the triggers and remove both the table and index b-tree entries.
  89978. **
  89979. ** Otherwise, if there are no triggers or the recursive-triggers
  89980. ** flag is not set, but the table has one or more indexes, call
  89981. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  89982. ** only. The table b-tree entry will be replaced by the new entry
  89983. ** when it is inserted.
  89984. **
  89985. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  89986. ** also invoke MultiWrite() to indicate that this VDBE may require
  89987. ** statement rollback (if the statement is aborted after the delete
  89988. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  89989. ** but being more selective here allows statements like:
  89990. **
  89991. ** REPLACE INTO t(rowid) VALUES($newrowid)
  89992. **
  89993. ** to run without a statement journal if there are no indexes on the
  89994. ** table.
  89995. */
  89996. Trigger *pTrigger = 0;
  89997. if( db->flags&SQLITE_RecTriggers ){
  89998. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  89999. }
  90000. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  90001. sqlite3MultiWrite(pParse);
  90002. sqlite3GenerateRowDelete(
  90003. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  90004. );
  90005. }else if( pTab->pIndex ){
  90006. sqlite3MultiWrite(pParse);
  90007. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  90008. }
  90009. seenReplace = 1;
  90010. break;
  90011. }
  90012. case OE_Ignore: {
  90013. assert( seenReplace==0 );
  90014. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  90015. break;
  90016. }
  90017. }
  90018. sqlite3VdbeJumpHere(v, j3);
  90019. if( isUpdate ){
  90020. sqlite3VdbeJumpHere(v, j2);
  90021. }
  90022. }
  90023. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  90024. ** index and making sure that duplicate entries do not already exist.
  90025. ** Add the new records to the indices as we go.
  90026. */
  90027. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  90028. int regIdx;
  90029. int regR;
  90030. int addrSkipRow = 0;
  90031. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  90032. if( pIdx->pPartIdxWhere ){
  90033. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
  90034. addrSkipRow = sqlite3VdbeMakeLabel(v);
  90035. pParse->ckBase = regData;
  90036. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
  90037. SQLITE_JUMPIFNULL);
  90038. pParse->ckBase = 0;
  90039. }
  90040. /* Create a key for accessing the index entry */
  90041. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  90042. for(i=0; i<pIdx->nColumn; i++){
  90043. int idx = pIdx->aiColumn[i];
  90044. if( idx==pTab->iPKey ){
  90045. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  90046. }else{
  90047. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  90048. }
  90049. }
  90050. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  90051. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  90052. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  90053. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  90054. /* Find out what action to take in case there is an indexing conflict */
  90055. onError = pIdx->onError;
  90056. if( onError==OE_None ){
  90057. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  90058. sqlite3VdbeResolveLabel(v, addrSkipRow);
  90059. continue; /* pIdx is not a UNIQUE index */
  90060. }
  90061. if( overrideError!=OE_Default ){
  90062. onError = overrideError;
  90063. }else if( onError==OE_Default ){
  90064. onError = OE_Abort;
  90065. }
  90066. if( seenReplace ){
  90067. if( onError==OE_Ignore ) onError = OE_Replace;
  90068. else if( onError==OE_Fail ) onError = OE_Abort;
  90069. }
  90070. /* Check to see if the new index entry will be unique */
  90071. regR = sqlite3GetTempReg(pParse);
  90072. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  90073. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  90074. regR, SQLITE_INT_TO_PTR(regIdx),
  90075. P4_INT32);
  90076. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  90077. /* Generate code that executes if the new index entry is not unique */
  90078. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  90079. || onError==OE_Ignore || onError==OE_Replace );
  90080. switch( onError ){
  90081. case OE_Rollback:
  90082. case OE_Abort:
  90083. case OE_Fail: {
  90084. int j;
  90085. StrAccum errMsg;
  90086. const char *zSep;
  90087. char *zErr;
  90088. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  90089. errMsg.db = db;
  90090. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  90091. for(j=0; j<pIdx->nColumn; j++){
  90092. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  90093. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  90094. zSep = ", ";
  90095. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  90096. }
  90097. sqlite3StrAccumAppend(&errMsg,
  90098. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  90099. zErr = sqlite3StrAccumFinish(&errMsg);
  90100. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  90101. onError, zErr, 0);
  90102. sqlite3DbFree(errMsg.db, zErr);
  90103. break;
  90104. }
  90105. case OE_Ignore: {
  90106. assert( seenReplace==0 );
  90107. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  90108. break;
  90109. }
  90110. default: {
  90111. Trigger *pTrigger = 0;
  90112. assert( onError==OE_Replace );
  90113. sqlite3MultiWrite(pParse);
  90114. if( db->flags&SQLITE_RecTriggers ){
  90115. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  90116. }
  90117. sqlite3GenerateRowDelete(
  90118. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  90119. );
  90120. seenReplace = 1;
  90121. break;
  90122. }
  90123. }
  90124. sqlite3VdbeJumpHere(v, j3);
  90125. sqlite3VdbeResolveLabel(v, addrSkipRow);
  90126. sqlite3ReleaseTempReg(pParse, regR);
  90127. }
  90128. if( pbMayReplace ){
  90129. *pbMayReplace = seenReplace;
  90130. }
  90131. }
  90132. /*
  90133. ** This routine generates code to finish the INSERT or UPDATE operation
  90134. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  90135. ** A consecutive range of registers starting at regRowid contains the
  90136. ** rowid and the content to be inserted.
  90137. **
  90138. ** The arguments to this routine should be the same as the first six
  90139. ** arguments to sqlite3GenerateConstraintChecks.
  90140. */
  90141. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  90142. Parse *pParse, /* The parser context */
  90143. Table *pTab, /* the table into which we are inserting */
  90144. int baseCur, /* Index of a read/write cursor pointing at pTab */
  90145. int regRowid, /* Range of content */
  90146. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  90147. int isUpdate, /* True for UPDATE, False for INSERT */
  90148. int appendBias, /* True if this is likely to be an append */
  90149. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  90150. ){
  90151. int i;
  90152. Vdbe *v;
  90153. Index *pIdx;
  90154. u8 pik_flags;
  90155. int regData;
  90156. int regRec;
  90157. v = sqlite3GetVdbe(pParse);
  90158. assert( v!=0 );
  90159. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  90160. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  90161. if( aRegIdx[i]==0 ) continue;
  90162. if( pIdx->pPartIdxWhere ){
  90163. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  90164. }
  90165. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  90166. if( useSeekResult ){
  90167. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  90168. }
  90169. }
  90170. regData = regRowid + 1;
  90171. regRec = sqlite3GetTempReg(pParse);
  90172. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  90173. sqlite3TableAffinityStr(v, pTab);
  90174. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  90175. if( pParse->nested ){
  90176. pik_flags = 0;
  90177. }else{
  90178. pik_flags = OPFLAG_NCHANGE;
  90179. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  90180. }
  90181. if( appendBias ){
  90182. pik_flags |= OPFLAG_APPEND;
  90183. }
  90184. if( useSeekResult ){
  90185. pik_flags |= OPFLAG_USESEEKRESULT;
  90186. }
  90187. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  90188. if( !pParse->nested ){
  90189. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  90190. }
  90191. sqlite3VdbeChangeP5(v, pik_flags);
  90192. }
  90193. /*
  90194. ** Generate code that will open cursors for a table and for all
  90195. ** indices of that table. The "baseCur" parameter is the cursor number used
  90196. ** for the table. Indices are opened on subsequent cursors.
  90197. **
  90198. ** Return the number of indices on the table.
  90199. */
  90200. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  90201. Parse *pParse, /* Parsing context */
  90202. Table *pTab, /* Table to be opened */
  90203. int baseCur, /* Cursor number assigned to the table */
  90204. int op /* OP_OpenRead or OP_OpenWrite */
  90205. ){
  90206. int i;
  90207. int iDb;
  90208. Index *pIdx;
  90209. Vdbe *v;
  90210. if( IsVirtual(pTab) ) return 0;
  90211. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90212. v = sqlite3GetVdbe(pParse);
  90213. assert( v!=0 );
  90214. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  90215. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  90216. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  90217. assert( pIdx->pSchema==pTab->pSchema );
  90218. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  90219. (char*)pKey, P4_KEYINFO_HANDOFF);
  90220. VdbeComment((v, "%s", pIdx->zName));
  90221. }
  90222. if( pParse->nTab<baseCur+i ){
  90223. pParse->nTab = baseCur+i;
  90224. }
  90225. return i-1;
  90226. }
  90227. #ifdef SQLITE_TEST
  90228. /*
  90229. ** The following global variable is incremented whenever the
  90230. ** transfer optimization is used. This is used for testing
  90231. ** purposes only - to make sure the transfer optimization really
  90232. ** is happening when it is suppose to.
  90233. */
  90234. SQLITE_API int sqlite3_xferopt_count;
  90235. #endif /* SQLITE_TEST */
  90236. #ifndef SQLITE_OMIT_XFER_OPT
  90237. /*
  90238. ** Check to collation names to see if they are compatible.
  90239. */
  90240. static int xferCompatibleCollation(const char *z1, const char *z2){
  90241. if( z1==0 ){
  90242. return z2==0;
  90243. }
  90244. if( z2==0 ){
  90245. return 0;
  90246. }
  90247. return sqlite3StrICmp(z1, z2)==0;
  90248. }
  90249. /*
  90250. ** Check to see if index pSrc is compatible as a source of data
  90251. ** for index pDest in an insert transfer optimization. The rules
  90252. ** for a compatible index:
  90253. **
  90254. ** * The index is over the same set of columns
  90255. ** * The same DESC and ASC markings occurs on all columns
  90256. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  90257. ** * The same collating sequence on each column
  90258. ** * The index has the exact same WHERE clause
  90259. */
  90260. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  90261. int i;
  90262. assert( pDest && pSrc );
  90263. assert( pDest->pTable!=pSrc->pTable );
  90264. if( pDest->nColumn!=pSrc->nColumn ){
  90265. return 0; /* Different number of columns */
  90266. }
  90267. if( pDest->onError!=pSrc->onError ){
  90268. return 0; /* Different conflict resolution strategies */
  90269. }
  90270. for(i=0; i<pSrc->nColumn; i++){
  90271. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  90272. return 0; /* Different columns indexed */
  90273. }
  90274. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  90275. return 0; /* Different sort orders */
  90276. }
  90277. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  90278. return 0; /* Different collating sequences */
  90279. }
  90280. }
  90281. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  90282. return 0; /* Different WHERE clauses */
  90283. }
  90284. /* If no test above fails then the indices must be compatible */
  90285. return 1;
  90286. }
  90287. /*
  90288. ** Attempt the transfer optimization on INSERTs of the form
  90289. **
  90290. ** INSERT INTO tab1 SELECT * FROM tab2;
  90291. **
  90292. ** The xfer optimization transfers raw records from tab2 over to tab1.
  90293. ** Columns are not decoded and reassemblied, which greatly improves
  90294. ** performance. Raw index records are transferred in the same way.
  90295. **
  90296. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  90297. ** There are lots of rules for determining compatibility - see comments
  90298. ** embedded in the code for details.
  90299. **
  90300. ** This routine returns TRUE if the optimization is guaranteed to be used.
  90301. ** Sometimes the xfer optimization will only work if the destination table
  90302. ** is empty - a factor that can only be determined at run-time. In that
  90303. ** case, this routine generates code for the xfer optimization but also
  90304. ** does a test to see if the destination table is empty and jumps over the
  90305. ** xfer optimization code if the test fails. In that case, this routine
  90306. ** returns FALSE so that the caller will know to go ahead and generate
  90307. ** an unoptimized transfer. This routine also returns FALSE if there
  90308. ** is no chance that the xfer optimization can be applied.
  90309. **
  90310. ** This optimization is particularly useful at making VACUUM run faster.
  90311. */
  90312. static int xferOptimization(
  90313. Parse *pParse, /* Parser context */
  90314. Table *pDest, /* The table we are inserting into */
  90315. Select *pSelect, /* A SELECT statement to use as the data source */
  90316. int onError, /* How to handle constraint errors */
  90317. int iDbDest /* The database of pDest */
  90318. ){
  90319. ExprList *pEList; /* The result set of the SELECT */
  90320. Table *pSrc; /* The table in the FROM clause of SELECT */
  90321. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  90322. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  90323. int i; /* Loop counter */
  90324. int iDbSrc; /* The database of pSrc */
  90325. int iSrc, iDest; /* Cursors from source and destination */
  90326. int addr1, addr2; /* Loop addresses */
  90327. int emptyDestTest; /* Address of test for empty pDest */
  90328. int emptySrcTest; /* Address of test for empty pSrc */
  90329. Vdbe *v; /* The VDBE we are building */
  90330. KeyInfo *pKey; /* Key information for an index */
  90331. int regAutoinc; /* Memory register used by AUTOINC */
  90332. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  90333. int regData, regRowid; /* Registers holding data and rowid */
  90334. if( pSelect==0 ){
  90335. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  90336. }
  90337. if( sqlite3TriggerList(pParse, pDest) ){
  90338. return 0; /* tab1 must not have triggers */
  90339. }
  90340. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90341. if( pDest->tabFlags & TF_Virtual ){
  90342. return 0; /* tab1 must not be a virtual table */
  90343. }
  90344. #endif
  90345. if( onError==OE_Default ){
  90346. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  90347. if( onError==OE_Default ) onError = OE_Abort;
  90348. }
  90349. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  90350. if( pSelect->pSrc->nSrc!=1 ){
  90351. return 0; /* FROM clause must have exactly one term */
  90352. }
  90353. if( pSelect->pSrc->a[0].pSelect ){
  90354. return 0; /* FROM clause cannot contain a subquery */
  90355. }
  90356. if( pSelect->pWhere ){
  90357. return 0; /* SELECT may not have a WHERE clause */
  90358. }
  90359. if( pSelect->pOrderBy ){
  90360. return 0; /* SELECT may not have an ORDER BY clause */
  90361. }
  90362. /* Do not need to test for a HAVING clause. If HAVING is present but
  90363. ** there is no ORDER BY, we will get an error. */
  90364. if( pSelect->pGroupBy ){
  90365. return 0; /* SELECT may not have a GROUP BY clause */
  90366. }
  90367. if( pSelect->pLimit ){
  90368. return 0; /* SELECT may not have a LIMIT clause */
  90369. }
  90370. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  90371. if( pSelect->pPrior ){
  90372. return 0; /* SELECT may not be a compound query */
  90373. }
  90374. if( pSelect->selFlags & SF_Distinct ){
  90375. return 0; /* SELECT may not be DISTINCT */
  90376. }
  90377. pEList = pSelect->pEList;
  90378. assert( pEList!=0 );
  90379. if( pEList->nExpr!=1 ){
  90380. return 0; /* The result set must have exactly one column */
  90381. }
  90382. assert( pEList->a[0].pExpr );
  90383. if( pEList->a[0].pExpr->op!=TK_ALL ){
  90384. return 0; /* The result set must be the special operator "*" */
  90385. }
  90386. /* At this point we have established that the statement is of the
  90387. ** correct syntactic form to participate in this optimization. Now
  90388. ** we have to check the semantics.
  90389. */
  90390. pItem = pSelect->pSrc->a;
  90391. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  90392. if( pSrc==0 ){
  90393. return 0; /* FROM clause does not contain a real table */
  90394. }
  90395. if( pSrc==pDest ){
  90396. return 0; /* tab1 and tab2 may not be the same table */
  90397. }
  90398. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90399. if( pSrc->tabFlags & TF_Virtual ){
  90400. return 0; /* tab2 must not be a virtual table */
  90401. }
  90402. #endif
  90403. if( pSrc->pSelect ){
  90404. return 0; /* tab2 may not be a view */
  90405. }
  90406. if( pDest->nCol!=pSrc->nCol ){
  90407. return 0; /* Number of columns must be the same in tab1 and tab2 */
  90408. }
  90409. if( pDest->iPKey!=pSrc->iPKey ){
  90410. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  90411. }
  90412. for(i=0; i<pDest->nCol; i++){
  90413. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  90414. return 0; /* Affinity must be the same on all columns */
  90415. }
  90416. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  90417. return 0; /* Collating sequence must be the same on all columns */
  90418. }
  90419. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  90420. return 0; /* tab2 must be NOT NULL if tab1 is */
  90421. }
  90422. }
  90423. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  90424. if( pDestIdx->onError!=OE_None ){
  90425. destHasUniqueIdx = 1;
  90426. }
  90427. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  90428. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  90429. }
  90430. if( pSrcIdx==0 ){
  90431. return 0; /* pDestIdx has no corresponding index in pSrc */
  90432. }
  90433. }
  90434. #ifndef SQLITE_OMIT_CHECK
  90435. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  90436. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  90437. }
  90438. #endif
  90439. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90440. /* Disallow the transfer optimization if the destination table constains
  90441. ** any foreign key constraints. This is more restrictive than necessary.
  90442. ** But the main beneficiary of the transfer optimization is the VACUUM
  90443. ** command, and the VACUUM command disables foreign key constraints. So
  90444. ** the extra complication to make this rule less restrictive is probably
  90445. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  90446. */
  90447. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  90448. return 0;
  90449. }
  90450. #endif
  90451. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  90452. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  90453. }
  90454. /* If we get this far, it means that the xfer optimization is at
  90455. ** least a possibility, though it might only work if the destination
  90456. ** table (tab1) is initially empty.
  90457. */
  90458. #ifdef SQLITE_TEST
  90459. sqlite3_xferopt_count++;
  90460. #endif
  90461. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  90462. v = sqlite3GetVdbe(pParse);
  90463. sqlite3CodeVerifySchema(pParse, iDbSrc);
  90464. iSrc = pParse->nTab++;
  90465. iDest = pParse->nTab++;
  90466. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  90467. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  90468. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  90469. || destHasUniqueIdx /* (2) */
  90470. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  90471. ){
  90472. /* In some circumstances, we are able to run the xfer optimization
  90473. ** only if the destination table is initially empty. This code makes
  90474. ** that determination. Conditions under which the destination must
  90475. ** be empty:
  90476. **
  90477. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  90478. ** (If the destination is not initially empty, the rowid fields
  90479. ** of index entries might need to change.)
  90480. **
  90481. ** (2) The destination has a unique index. (The xfer optimization
  90482. ** is unable to test uniqueness.)
  90483. **
  90484. ** (3) onError is something other than OE_Abort and OE_Rollback.
  90485. */
  90486. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  90487. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  90488. sqlite3VdbeJumpHere(v, addr1);
  90489. }else{
  90490. emptyDestTest = 0;
  90491. }
  90492. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  90493. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  90494. regData = sqlite3GetTempReg(pParse);
  90495. regRowid = sqlite3GetTempReg(pParse);
  90496. if( pDest->iPKey>=0 ){
  90497. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  90498. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  90499. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  90500. onError, "PRIMARY KEY must be unique", P4_STATIC);
  90501. sqlite3VdbeJumpHere(v, addr2);
  90502. autoIncStep(pParse, regAutoinc, regRowid);
  90503. }else if( pDest->pIndex==0 ){
  90504. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  90505. }else{
  90506. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  90507. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  90508. }
  90509. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  90510. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  90511. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  90512. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  90513. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  90514. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  90515. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  90516. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  90517. }
  90518. assert( pSrcIdx );
  90519. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  90520. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90521. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  90522. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  90523. (char*)pKey, P4_KEYINFO_HANDOFF);
  90524. VdbeComment((v, "%s", pSrcIdx->zName));
  90525. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  90526. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  90527. (char*)pKey, P4_KEYINFO_HANDOFF);
  90528. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  90529. VdbeComment((v, "%s", pDestIdx->zName));
  90530. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  90531. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  90532. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  90533. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  90534. sqlite3VdbeJumpHere(v, addr1);
  90535. }
  90536. sqlite3VdbeJumpHere(v, emptySrcTest);
  90537. sqlite3ReleaseTempReg(pParse, regRowid);
  90538. sqlite3ReleaseTempReg(pParse, regData);
  90539. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  90540. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90541. if( emptyDestTest ){
  90542. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  90543. sqlite3VdbeJumpHere(v, emptyDestTest);
  90544. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90545. return 0;
  90546. }else{
  90547. return 1;
  90548. }
  90549. }
  90550. #endif /* SQLITE_OMIT_XFER_OPT */
  90551. /************** End of insert.c **********************************************/
  90552. /************** Begin file legacy.c ******************************************/
  90553. /*
  90554. ** 2001 September 15
  90555. **
  90556. ** The author disclaims copyright to this source code. In place of
  90557. ** a legal notice, here is a blessing:
  90558. **
  90559. ** May you do good and not evil.
  90560. ** May you find forgiveness for yourself and forgive others.
  90561. ** May you share freely, never taking more than you give.
  90562. **
  90563. *************************************************************************
  90564. ** Main file for the SQLite library. The routines in this file
  90565. ** implement the programmer interface to the library. Routines in
  90566. ** other files are for internal use by SQLite and should not be
  90567. ** accessed by users of the library.
  90568. */
  90569. /*
  90570. ** Execute SQL code. Return one of the SQLITE_ success/failure
  90571. ** codes. Also write an error message into memory obtained from
  90572. ** malloc() and make *pzErrMsg point to that message.
  90573. **
  90574. ** If the SQL is a query, then for each row in the query result
  90575. ** the xCallback() function is called. pArg becomes the first
  90576. ** argument to xCallback(). If xCallback=NULL then no callback
  90577. ** is invoked, even for queries.
  90578. */
  90579. SQLITE_API int sqlite3_exec(
  90580. sqlite3 *db, /* The database on which the SQL executes */
  90581. const char *zSql, /* The SQL to be executed */
  90582. sqlite3_callback xCallback, /* Invoke this callback routine */
  90583. void *pArg, /* First argument to xCallback() */
  90584. char **pzErrMsg /* Write error messages here */
  90585. ){
  90586. int rc = SQLITE_OK; /* Return code */
  90587. const char *zLeftover; /* Tail of unprocessed SQL */
  90588. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  90589. char **azCols = 0; /* Names of result columns */
  90590. int callbackIsInit; /* True if callback data is initialized */
  90591. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  90592. if( zSql==0 ) zSql = "";
  90593. sqlite3_mutex_enter(db->mutex);
  90594. sqlite3Error(db, SQLITE_OK, 0);
  90595. while( rc==SQLITE_OK && zSql[0] ){
  90596. int nCol;
  90597. char **azVals = 0;
  90598. pStmt = 0;
  90599. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  90600. assert( rc==SQLITE_OK || pStmt==0 );
  90601. if( rc!=SQLITE_OK ){
  90602. continue;
  90603. }
  90604. if( !pStmt ){
  90605. /* this happens for a comment or white-space */
  90606. zSql = zLeftover;
  90607. continue;
  90608. }
  90609. callbackIsInit = 0;
  90610. nCol = sqlite3_column_count(pStmt);
  90611. while( 1 ){
  90612. int i;
  90613. rc = sqlite3_step(pStmt);
  90614. /* Invoke the callback function if required */
  90615. if( xCallback && (SQLITE_ROW==rc ||
  90616. (SQLITE_DONE==rc && !callbackIsInit
  90617. && db->flags&SQLITE_NullCallback)) ){
  90618. if( !callbackIsInit ){
  90619. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  90620. if( azCols==0 ){
  90621. goto exec_out;
  90622. }
  90623. for(i=0; i<nCol; i++){
  90624. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  90625. /* sqlite3VdbeSetColName() installs column names as UTF8
  90626. ** strings so there is no way for sqlite3_column_name() to fail. */
  90627. assert( azCols[i]!=0 );
  90628. }
  90629. callbackIsInit = 1;
  90630. }
  90631. if( rc==SQLITE_ROW ){
  90632. azVals = &azCols[nCol];
  90633. for(i=0; i<nCol; i++){
  90634. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  90635. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  90636. db->mallocFailed = 1;
  90637. goto exec_out;
  90638. }
  90639. }
  90640. }
  90641. if( xCallback(pArg, nCol, azVals, azCols) ){
  90642. rc = SQLITE_ABORT;
  90643. sqlite3VdbeFinalize((Vdbe *)pStmt);
  90644. pStmt = 0;
  90645. sqlite3Error(db, SQLITE_ABORT, 0);
  90646. goto exec_out;
  90647. }
  90648. }
  90649. if( rc!=SQLITE_ROW ){
  90650. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  90651. pStmt = 0;
  90652. zSql = zLeftover;
  90653. while( sqlite3Isspace(zSql[0]) ) zSql++;
  90654. break;
  90655. }
  90656. }
  90657. sqlite3DbFree(db, azCols);
  90658. azCols = 0;
  90659. }
  90660. exec_out:
  90661. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  90662. sqlite3DbFree(db, azCols);
  90663. rc = sqlite3ApiExit(db, rc);
  90664. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  90665. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  90666. *pzErrMsg = sqlite3Malloc(nErrMsg);
  90667. if( *pzErrMsg ){
  90668. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  90669. }else{
  90670. rc = SQLITE_NOMEM;
  90671. sqlite3Error(db, SQLITE_NOMEM, 0);
  90672. }
  90673. }else if( pzErrMsg ){
  90674. *pzErrMsg = 0;
  90675. }
  90676. assert( (rc&db->errMask)==rc );
  90677. sqlite3_mutex_leave(db->mutex);
  90678. return rc;
  90679. }
  90680. /************** End of legacy.c **********************************************/
  90681. /************** Begin file loadext.c *****************************************/
  90682. /*
  90683. ** 2006 June 7
  90684. **
  90685. ** The author disclaims copyright to this source code. In place of
  90686. ** a legal notice, here is a blessing:
  90687. **
  90688. ** May you do good and not evil.
  90689. ** May you find forgiveness for yourself and forgive others.
  90690. ** May you share freely, never taking more than you give.
  90691. **
  90692. *************************************************************************
  90693. ** This file contains code used to dynamically load extensions into
  90694. ** the SQLite library.
  90695. */
  90696. #ifndef SQLITE_CORE
  90697. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  90698. #endif
  90699. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  90700. /************** Begin file sqlite3ext.h **************************************/
  90701. /*
  90702. ** 2006 June 7
  90703. **
  90704. ** The author disclaims copyright to this source code. In place of
  90705. ** a legal notice, here is a blessing:
  90706. **
  90707. ** May you do good and not evil.
  90708. ** May you find forgiveness for yourself and forgive others.
  90709. ** May you share freely, never taking more than you give.
  90710. **
  90711. *************************************************************************
  90712. ** This header file defines the SQLite interface for use by
  90713. ** shared libraries that want to be imported as extensions into
  90714. ** an SQLite instance. Shared libraries that intend to be loaded
  90715. ** as extensions by SQLite should #include this file instead of
  90716. ** sqlite3.h.
  90717. */
  90718. #ifndef _SQLITE3EXT_H_
  90719. #define _SQLITE3EXT_H_
  90720. typedef struct sqlite3_api_routines sqlite3_api_routines;
  90721. /*
  90722. ** The following structure holds pointers to all of the SQLite API
  90723. ** routines.
  90724. **
  90725. ** WARNING: In order to maintain backwards compatibility, add new
  90726. ** interfaces to the end of this structure only. If you insert new
  90727. ** interfaces in the middle of this structure, then older different
  90728. ** versions of SQLite will not be able to load each others' shared
  90729. ** libraries!
  90730. */
  90731. struct sqlite3_api_routines {
  90732. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  90733. int (*aggregate_count)(sqlite3_context*);
  90734. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  90735. int (*bind_double)(sqlite3_stmt*,int,double);
  90736. int (*bind_int)(sqlite3_stmt*,int,int);
  90737. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  90738. int (*bind_null)(sqlite3_stmt*,int);
  90739. int (*bind_parameter_count)(sqlite3_stmt*);
  90740. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  90741. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  90742. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  90743. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  90744. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  90745. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  90746. int (*busy_timeout)(sqlite3*,int ms);
  90747. int (*changes)(sqlite3*);
  90748. int (*close)(sqlite3*);
  90749. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  90750. int eTextRep,const char*));
  90751. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  90752. int eTextRep,const void*));
  90753. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  90754. int (*column_bytes)(sqlite3_stmt*,int iCol);
  90755. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  90756. int (*column_count)(sqlite3_stmt*pStmt);
  90757. const char * (*column_database_name)(sqlite3_stmt*,int);
  90758. const void * (*column_database_name16)(sqlite3_stmt*,int);
  90759. const char * (*column_decltype)(sqlite3_stmt*,int i);
  90760. const void * (*column_decltype16)(sqlite3_stmt*,int);
  90761. double (*column_double)(sqlite3_stmt*,int iCol);
  90762. int (*column_int)(sqlite3_stmt*,int iCol);
  90763. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  90764. const char * (*column_name)(sqlite3_stmt*,int);
  90765. const void * (*column_name16)(sqlite3_stmt*,int);
  90766. const char * (*column_origin_name)(sqlite3_stmt*,int);
  90767. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  90768. const char * (*column_table_name)(sqlite3_stmt*,int);
  90769. const void * (*column_table_name16)(sqlite3_stmt*,int);
  90770. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  90771. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  90772. int (*column_type)(sqlite3_stmt*,int iCol);
  90773. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  90774. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  90775. int (*complete)(const char*sql);
  90776. int (*complete16)(const void*sql);
  90777. int (*create_collation)(sqlite3*,const char*,int,void*,
  90778. int(*)(void*,int,const void*,int,const void*));
  90779. int (*create_collation16)(sqlite3*,const void*,int,void*,
  90780. int(*)(void*,int,const void*,int,const void*));
  90781. int (*create_function)(sqlite3*,const char*,int,int,void*,
  90782. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90783. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90784. void (*xFinal)(sqlite3_context*));
  90785. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  90786. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90787. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90788. void (*xFinal)(sqlite3_context*));
  90789. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  90790. int (*data_count)(sqlite3_stmt*pStmt);
  90791. sqlite3 * (*db_handle)(sqlite3_stmt*);
  90792. int (*declare_vtab)(sqlite3*,const char*);
  90793. int (*enable_shared_cache)(int);
  90794. int (*errcode)(sqlite3*db);
  90795. const char * (*errmsg)(sqlite3*);
  90796. const void * (*errmsg16)(sqlite3*);
  90797. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  90798. int (*expired)(sqlite3_stmt*);
  90799. int (*finalize)(sqlite3_stmt*pStmt);
  90800. void (*free)(void*);
  90801. void (*free_table)(char**result);
  90802. int (*get_autocommit)(sqlite3*);
  90803. void * (*get_auxdata)(sqlite3_context*,int);
  90804. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  90805. int (*global_recover)(void);
  90806. void (*interruptx)(sqlite3*);
  90807. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  90808. const char * (*libversion)(void);
  90809. int (*libversion_number)(void);
  90810. void *(*malloc)(int);
  90811. char * (*mprintf)(const char*,...);
  90812. int (*open)(const char*,sqlite3**);
  90813. int (*open16)(const void*,sqlite3**);
  90814. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  90815. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  90816. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  90817. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  90818. void *(*realloc)(void*,int);
  90819. int (*reset)(sqlite3_stmt*pStmt);
  90820. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  90821. void (*result_double)(sqlite3_context*,double);
  90822. void (*result_error)(sqlite3_context*,const char*,int);
  90823. void (*result_error16)(sqlite3_context*,const void*,int);
  90824. void (*result_int)(sqlite3_context*,int);
  90825. void (*result_int64)(sqlite3_context*,sqlite_int64);
  90826. void (*result_null)(sqlite3_context*);
  90827. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  90828. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  90829. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  90830. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  90831. void (*result_value)(sqlite3_context*,sqlite3_value*);
  90832. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  90833. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  90834. const char*,const char*),void*);
  90835. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  90836. char * (*snprintf)(int,char*,const char*,...);
  90837. int (*step)(sqlite3_stmt*);
  90838. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  90839. char const**,char const**,int*,int*,int*);
  90840. void (*thread_cleanup)(void);
  90841. int (*total_changes)(sqlite3*);
  90842. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  90843. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  90844. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  90845. sqlite_int64),void*);
  90846. void * (*user_data)(sqlite3_context*);
  90847. const void * (*value_blob)(sqlite3_value*);
  90848. int (*value_bytes)(sqlite3_value*);
  90849. int (*value_bytes16)(sqlite3_value*);
  90850. double (*value_double)(sqlite3_value*);
  90851. int (*value_int)(sqlite3_value*);
  90852. sqlite_int64 (*value_int64)(sqlite3_value*);
  90853. int (*value_numeric_type)(sqlite3_value*);
  90854. const unsigned char * (*value_text)(sqlite3_value*);
  90855. const void * (*value_text16)(sqlite3_value*);
  90856. const void * (*value_text16be)(sqlite3_value*);
  90857. const void * (*value_text16le)(sqlite3_value*);
  90858. int (*value_type)(sqlite3_value*);
  90859. char *(*vmprintf)(const char*,va_list);
  90860. /* Added ??? */
  90861. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  90862. /* Added by 3.3.13 */
  90863. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  90864. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  90865. int (*clear_bindings)(sqlite3_stmt*);
  90866. /* Added by 3.4.1 */
  90867. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  90868. void (*xDestroy)(void *));
  90869. /* Added by 3.5.0 */
  90870. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  90871. int (*blob_bytes)(sqlite3_blob*);
  90872. int (*blob_close)(sqlite3_blob*);
  90873. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  90874. int,sqlite3_blob**);
  90875. int (*blob_read)(sqlite3_blob*,void*,int,int);
  90876. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  90877. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  90878. int(*)(void*,int,const void*,int,const void*),
  90879. void(*)(void*));
  90880. int (*file_control)(sqlite3*,const char*,int,void*);
  90881. sqlite3_int64 (*memory_highwater)(int);
  90882. sqlite3_int64 (*memory_used)(void);
  90883. sqlite3_mutex *(*mutex_alloc)(int);
  90884. void (*mutex_enter)(sqlite3_mutex*);
  90885. void (*mutex_free)(sqlite3_mutex*);
  90886. void (*mutex_leave)(sqlite3_mutex*);
  90887. int (*mutex_try)(sqlite3_mutex*);
  90888. int (*open_v2)(const char*,sqlite3**,int,const char*);
  90889. int (*release_memory)(int);
  90890. void (*result_error_nomem)(sqlite3_context*);
  90891. void (*result_error_toobig)(sqlite3_context*);
  90892. int (*sleep)(int);
  90893. void (*soft_heap_limit)(int);
  90894. sqlite3_vfs *(*vfs_find)(const char*);
  90895. int (*vfs_register)(sqlite3_vfs*,int);
  90896. int (*vfs_unregister)(sqlite3_vfs*);
  90897. int (*xthreadsafe)(void);
  90898. void (*result_zeroblob)(sqlite3_context*,int);
  90899. void (*result_error_code)(sqlite3_context*,int);
  90900. int (*test_control)(int, ...);
  90901. void (*randomness)(int,void*);
  90902. sqlite3 *(*context_db_handle)(sqlite3_context*);
  90903. int (*extended_result_codes)(sqlite3*,int);
  90904. int (*limit)(sqlite3*,int,int);
  90905. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  90906. const char *(*sql)(sqlite3_stmt*);
  90907. int (*status)(int,int*,int*,int);
  90908. int (*backup_finish)(sqlite3_backup*);
  90909. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  90910. int (*backup_pagecount)(sqlite3_backup*);
  90911. int (*backup_remaining)(sqlite3_backup*);
  90912. int (*backup_step)(sqlite3_backup*,int);
  90913. const char *(*compileoption_get)(int);
  90914. int (*compileoption_used)(const char*);
  90915. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  90916. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90917. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90918. void (*xFinal)(sqlite3_context*),
  90919. void(*xDestroy)(void*));
  90920. int (*db_config)(sqlite3*,int,...);
  90921. sqlite3_mutex *(*db_mutex)(sqlite3*);
  90922. int (*db_status)(sqlite3*,int,int*,int*,int);
  90923. int (*extended_errcode)(sqlite3*);
  90924. void (*log)(int,const char*,...);
  90925. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  90926. const char *(*sourceid)(void);
  90927. int (*stmt_status)(sqlite3_stmt*,int,int);
  90928. int (*strnicmp)(const char*,const char*,int);
  90929. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  90930. int (*wal_autocheckpoint)(sqlite3*,int);
  90931. int (*wal_checkpoint)(sqlite3*,const char*);
  90932. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  90933. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  90934. int (*vtab_config)(sqlite3*,int op,...);
  90935. int (*vtab_on_conflict)(sqlite3*);
  90936. /* Version 3.7.16 and later */
  90937. int (*close_v2)(sqlite3*);
  90938. const char *(*db_filename)(sqlite3*,const char*);
  90939. int (*db_readonly)(sqlite3*,const char*);
  90940. int (*db_release_memory)(sqlite3*);
  90941. const char *(*errstr)(int);
  90942. int (*stmt_busy)(sqlite3_stmt*);
  90943. int (*stmt_readonly)(sqlite3_stmt*);
  90944. int (*stricmp)(const char*,const char*);
  90945. int (*uri_boolean)(const char*,const char*,int);
  90946. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  90947. const char *(*uri_parameter)(const char*,const char*);
  90948. char *(*vsnprintf)(int,char*,const char*,va_list);
  90949. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  90950. };
  90951. /*
  90952. ** The following macros redefine the API routines so that they are
  90953. ** redirected throught the global sqlite3_api structure.
  90954. **
  90955. ** This header file is also used by the loadext.c source file
  90956. ** (part of the main SQLite library - not an extension) so that
  90957. ** it can get access to the sqlite3_api_routines structure
  90958. ** definition. But the main library does not want to redefine
  90959. ** the API. So the redefinition macros are only valid if the
  90960. ** SQLITE_CORE macros is undefined.
  90961. */
  90962. #ifndef SQLITE_CORE
  90963. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  90964. #ifndef SQLITE_OMIT_DEPRECATED
  90965. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  90966. #endif
  90967. #define sqlite3_bind_blob sqlite3_api->bind_blob
  90968. #define sqlite3_bind_double sqlite3_api->bind_double
  90969. #define sqlite3_bind_int sqlite3_api->bind_int
  90970. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  90971. #define sqlite3_bind_null sqlite3_api->bind_null
  90972. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  90973. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  90974. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  90975. #define sqlite3_bind_text sqlite3_api->bind_text
  90976. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  90977. #define sqlite3_bind_value sqlite3_api->bind_value
  90978. #define sqlite3_busy_handler sqlite3_api->busy_handler
  90979. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  90980. #define sqlite3_changes sqlite3_api->changes
  90981. #define sqlite3_close sqlite3_api->close
  90982. #define sqlite3_collation_needed sqlite3_api->collation_needed
  90983. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  90984. #define sqlite3_column_blob sqlite3_api->column_blob
  90985. #define sqlite3_column_bytes sqlite3_api->column_bytes
  90986. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  90987. #define sqlite3_column_count sqlite3_api->column_count
  90988. #define sqlite3_column_database_name sqlite3_api->column_database_name
  90989. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  90990. #define sqlite3_column_decltype sqlite3_api->column_decltype
  90991. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  90992. #define sqlite3_column_double sqlite3_api->column_double
  90993. #define sqlite3_column_int sqlite3_api->column_int
  90994. #define sqlite3_column_int64 sqlite3_api->column_int64
  90995. #define sqlite3_column_name sqlite3_api->column_name
  90996. #define sqlite3_column_name16 sqlite3_api->column_name16
  90997. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  90998. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  90999. #define sqlite3_column_table_name sqlite3_api->column_table_name
  91000. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  91001. #define sqlite3_column_text sqlite3_api->column_text
  91002. #define sqlite3_column_text16 sqlite3_api->column_text16
  91003. #define sqlite3_column_type sqlite3_api->column_type
  91004. #define sqlite3_column_value sqlite3_api->column_value
  91005. #define sqlite3_commit_hook sqlite3_api->commit_hook
  91006. #define sqlite3_complete sqlite3_api->complete
  91007. #define sqlite3_complete16 sqlite3_api->complete16
  91008. #define sqlite3_create_collation sqlite3_api->create_collation
  91009. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  91010. #define sqlite3_create_function sqlite3_api->create_function
  91011. #define sqlite3_create_function16 sqlite3_api->create_function16
  91012. #define sqlite3_create_module sqlite3_api->create_module
  91013. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  91014. #define sqlite3_data_count sqlite3_api->data_count
  91015. #define sqlite3_db_handle sqlite3_api->db_handle
  91016. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  91017. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  91018. #define sqlite3_errcode sqlite3_api->errcode
  91019. #define sqlite3_errmsg sqlite3_api->errmsg
  91020. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  91021. #define sqlite3_exec sqlite3_api->exec
  91022. #ifndef SQLITE_OMIT_DEPRECATED
  91023. #define sqlite3_expired sqlite3_api->expired
  91024. #endif
  91025. #define sqlite3_finalize sqlite3_api->finalize
  91026. #define sqlite3_free sqlite3_api->free
  91027. #define sqlite3_free_table sqlite3_api->free_table
  91028. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  91029. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  91030. #define sqlite3_get_table sqlite3_api->get_table
  91031. #ifndef SQLITE_OMIT_DEPRECATED
  91032. #define sqlite3_global_recover sqlite3_api->global_recover
  91033. #endif
  91034. #define sqlite3_interrupt sqlite3_api->interruptx
  91035. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  91036. #define sqlite3_libversion sqlite3_api->libversion
  91037. #define sqlite3_libversion_number sqlite3_api->libversion_number
  91038. #define sqlite3_malloc sqlite3_api->malloc
  91039. #define sqlite3_mprintf sqlite3_api->mprintf
  91040. #define sqlite3_open sqlite3_api->open
  91041. #define sqlite3_open16 sqlite3_api->open16
  91042. #define sqlite3_prepare sqlite3_api->prepare
  91043. #define sqlite3_prepare16 sqlite3_api->prepare16
  91044. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  91045. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  91046. #define sqlite3_profile sqlite3_api->profile
  91047. #define sqlite3_progress_handler sqlite3_api->progress_handler
  91048. #define sqlite3_realloc sqlite3_api->realloc
  91049. #define sqlite3_reset sqlite3_api->reset
  91050. #define sqlite3_result_blob sqlite3_api->result_blob
  91051. #define sqlite3_result_double sqlite3_api->result_double
  91052. #define sqlite3_result_error sqlite3_api->result_error
  91053. #define sqlite3_result_error16 sqlite3_api->result_error16
  91054. #define sqlite3_result_int sqlite3_api->result_int
  91055. #define sqlite3_result_int64 sqlite3_api->result_int64
  91056. #define sqlite3_result_null sqlite3_api->result_null
  91057. #define sqlite3_result_text sqlite3_api->result_text
  91058. #define sqlite3_result_text16 sqlite3_api->result_text16
  91059. #define sqlite3_result_text16be sqlite3_api->result_text16be
  91060. #define sqlite3_result_text16le sqlite3_api->result_text16le
  91061. #define sqlite3_result_value sqlite3_api->result_value
  91062. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  91063. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  91064. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  91065. #define sqlite3_snprintf sqlite3_api->snprintf
  91066. #define sqlite3_step sqlite3_api->step
  91067. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  91068. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  91069. #define sqlite3_total_changes sqlite3_api->total_changes
  91070. #define sqlite3_trace sqlite3_api->trace
  91071. #ifndef SQLITE_OMIT_DEPRECATED
  91072. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  91073. #endif
  91074. #define sqlite3_update_hook sqlite3_api->update_hook
  91075. #define sqlite3_user_data sqlite3_api->user_data
  91076. #define sqlite3_value_blob sqlite3_api->value_blob
  91077. #define sqlite3_value_bytes sqlite3_api->value_bytes
  91078. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  91079. #define sqlite3_value_double sqlite3_api->value_double
  91080. #define sqlite3_value_int sqlite3_api->value_int
  91081. #define sqlite3_value_int64 sqlite3_api->value_int64
  91082. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  91083. #define sqlite3_value_text sqlite3_api->value_text
  91084. #define sqlite3_value_text16 sqlite3_api->value_text16
  91085. #define sqlite3_value_text16be sqlite3_api->value_text16be
  91086. #define sqlite3_value_text16le sqlite3_api->value_text16le
  91087. #define sqlite3_value_type sqlite3_api->value_type
  91088. #define sqlite3_vmprintf sqlite3_api->vmprintf
  91089. #define sqlite3_overload_function sqlite3_api->overload_function
  91090. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  91091. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  91092. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  91093. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  91094. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  91095. #define sqlite3_blob_close sqlite3_api->blob_close
  91096. #define sqlite3_blob_open sqlite3_api->blob_open
  91097. #define sqlite3_blob_read sqlite3_api->blob_read
  91098. #define sqlite3_blob_write sqlite3_api->blob_write
  91099. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  91100. #define sqlite3_file_control sqlite3_api->file_control
  91101. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  91102. #define sqlite3_memory_used sqlite3_api->memory_used
  91103. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  91104. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  91105. #define sqlite3_mutex_free sqlite3_api->mutex_free
  91106. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  91107. #define sqlite3_mutex_try sqlite3_api->mutex_try
  91108. #define sqlite3_open_v2 sqlite3_api->open_v2
  91109. #define sqlite3_release_memory sqlite3_api->release_memory
  91110. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  91111. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  91112. #define sqlite3_sleep sqlite3_api->sleep
  91113. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  91114. #define sqlite3_vfs_find sqlite3_api->vfs_find
  91115. #define sqlite3_vfs_register sqlite3_api->vfs_register
  91116. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  91117. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  91118. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  91119. #define sqlite3_result_error_code sqlite3_api->result_error_code
  91120. #define sqlite3_test_control sqlite3_api->test_control
  91121. #define sqlite3_randomness sqlite3_api->randomness
  91122. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  91123. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  91124. #define sqlite3_limit sqlite3_api->limit
  91125. #define sqlite3_next_stmt sqlite3_api->next_stmt
  91126. #define sqlite3_sql sqlite3_api->sql
  91127. #define sqlite3_status sqlite3_api->status
  91128. #define sqlite3_backup_finish sqlite3_api->backup_finish
  91129. #define sqlite3_backup_init sqlite3_api->backup_init
  91130. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  91131. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  91132. #define sqlite3_backup_step sqlite3_api->backup_step
  91133. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  91134. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  91135. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  91136. #define sqlite3_db_config sqlite3_api->db_config
  91137. #define sqlite3_db_mutex sqlite3_api->db_mutex
  91138. #define sqlite3_db_status sqlite3_api->db_status
  91139. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  91140. #define sqlite3_log sqlite3_api->log
  91141. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  91142. #define sqlite3_sourceid sqlite3_api->sourceid
  91143. #define sqlite3_stmt_status sqlite3_api->stmt_status
  91144. #define sqlite3_strnicmp sqlite3_api->strnicmp
  91145. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  91146. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  91147. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  91148. #define sqlite3_wal_hook sqlite3_api->wal_hook
  91149. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  91150. #define sqlite3_vtab_config sqlite3_api->vtab_config
  91151. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  91152. /* Version 3.7.16 and later */
  91153. #define sqlite3_close_v2 sqlite3_api->close_v2
  91154. #define sqlite3_db_filename sqlite3_api->db_filename
  91155. #define sqlite3_db_readonly sqlite3_api->db_readonly
  91156. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  91157. #define sqlite3_errstr sqlite3_api->errstr
  91158. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  91159. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  91160. #define sqlite3_stricmp sqlite3_api->stricmp
  91161. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  91162. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  91163. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  91164. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  91165. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  91166. #endif /* SQLITE_CORE */
  91167. #ifndef SQLITE_CORE
  91168. /* This case when the file really is being compiled as a loadable
  91169. ** extension */
  91170. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  91171. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  91172. # define SQLITE_EXTENSION_INIT3 \
  91173. extern const sqlite3_api_routines *sqlite3_api;
  91174. #else
  91175. /* This case when the file is being statically linked into the
  91176. ** application */
  91177. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  91178. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  91179. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  91180. #endif
  91181. #endif /* _SQLITE3EXT_H_ */
  91182. /************** End of sqlite3ext.h ******************************************/
  91183. /************** Continuing where we left off in loadext.c ********************/
  91184. /* #include <string.h> */
  91185. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  91186. /*
  91187. ** Some API routines are omitted when various features are
  91188. ** excluded from a build of SQLite. Substitute a NULL pointer
  91189. ** for any missing APIs.
  91190. */
  91191. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  91192. # define sqlite3_column_database_name 0
  91193. # define sqlite3_column_database_name16 0
  91194. # define sqlite3_column_table_name 0
  91195. # define sqlite3_column_table_name16 0
  91196. # define sqlite3_column_origin_name 0
  91197. # define sqlite3_column_origin_name16 0
  91198. # define sqlite3_table_column_metadata 0
  91199. #endif
  91200. #ifdef SQLITE_OMIT_AUTHORIZATION
  91201. # define sqlite3_set_authorizer 0
  91202. #endif
  91203. #ifdef SQLITE_OMIT_UTF16
  91204. # define sqlite3_bind_text16 0
  91205. # define sqlite3_collation_needed16 0
  91206. # define sqlite3_column_decltype16 0
  91207. # define sqlite3_column_name16 0
  91208. # define sqlite3_column_text16 0
  91209. # define sqlite3_complete16 0
  91210. # define sqlite3_create_collation16 0
  91211. # define sqlite3_create_function16 0
  91212. # define sqlite3_errmsg16 0
  91213. # define sqlite3_open16 0
  91214. # define sqlite3_prepare16 0
  91215. # define sqlite3_prepare16_v2 0
  91216. # define sqlite3_result_error16 0
  91217. # define sqlite3_result_text16 0
  91218. # define sqlite3_result_text16be 0
  91219. # define sqlite3_result_text16le 0
  91220. # define sqlite3_value_text16 0
  91221. # define sqlite3_value_text16be 0
  91222. # define sqlite3_value_text16le 0
  91223. # define sqlite3_column_database_name16 0
  91224. # define sqlite3_column_table_name16 0
  91225. # define sqlite3_column_origin_name16 0
  91226. #endif
  91227. #ifdef SQLITE_OMIT_COMPLETE
  91228. # define sqlite3_complete 0
  91229. # define sqlite3_complete16 0
  91230. #endif
  91231. #ifdef SQLITE_OMIT_DECLTYPE
  91232. # define sqlite3_column_decltype16 0
  91233. # define sqlite3_column_decltype 0
  91234. #endif
  91235. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  91236. # define sqlite3_progress_handler 0
  91237. #endif
  91238. #ifdef SQLITE_OMIT_VIRTUALTABLE
  91239. # define sqlite3_create_module 0
  91240. # define sqlite3_create_module_v2 0
  91241. # define sqlite3_declare_vtab 0
  91242. # define sqlite3_vtab_config 0
  91243. # define sqlite3_vtab_on_conflict 0
  91244. #endif
  91245. #ifdef SQLITE_OMIT_SHARED_CACHE
  91246. # define sqlite3_enable_shared_cache 0
  91247. #endif
  91248. #ifdef SQLITE_OMIT_TRACE
  91249. # define sqlite3_profile 0
  91250. # define sqlite3_trace 0
  91251. #endif
  91252. #ifdef SQLITE_OMIT_GET_TABLE
  91253. # define sqlite3_free_table 0
  91254. # define sqlite3_get_table 0
  91255. #endif
  91256. #ifdef SQLITE_OMIT_INCRBLOB
  91257. #define sqlite3_bind_zeroblob 0
  91258. #define sqlite3_blob_bytes 0
  91259. #define sqlite3_blob_close 0
  91260. #define sqlite3_blob_open 0
  91261. #define sqlite3_blob_read 0
  91262. #define sqlite3_blob_write 0
  91263. #define sqlite3_blob_reopen 0
  91264. #endif
  91265. /*
  91266. ** The following structure contains pointers to all SQLite API routines.
  91267. ** A pointer to this structure is passed into extensions when they are
  91268. ** loaded so that the extension can make calls back into the SQLite
  91269. ** library.
  91270. **
  91271. ** When adding new APIs, add them to the bottom of this structure
  91272. ** in order to preserve backwards compatibility.
  91273. **
  91274. ** Extensions that use newer APIs should first call the
  91275. ** sqlite3_libversion_number() to make sure that the API they
  91276. ** intend to use is supported by the library. Extensions should
  91277. ** also check to make sure that the pointer to the function is
  91278. ** not NULL before calling it.
  91279. */
  91280. static const sqlite3_api_routines sqlite3Apis = {
  91281. sqlite3_aggregate_context,
  91282. #ifndef SQLITE_OMIT_DEPRECATED
  91283. sqlite3_aggregate_count,
  91284. #else
  91285. 0,
  91286. #endif
  91287. sqlite3_bind_blob,
  91288. sqlite3_bind_double,
  91289. sqlite3_bind_int,
  91290. sqlite3_bind_int64,
  91291. sqlite3_bind_null,
  91292. sqlite3_bind_parameter_count,
  91293. sqlite3_bind_parameter_index,
  91294. sqlite3_bind_parameter_name,
  91295. sqlite3_bind_text,
  91296. sqlite3_bind_text16,
  91297. sqlite3_bind_value,
  91298. sqlite3_busy_handler,
  91299. sqlite3_busy_timeout,
  91300. sqlite3_changes,
  91301. sqlite3_close,
  91302. sqlite3_collation_needed,
  91303. sqlite3_collation_needed16,
  91304. sqlite3_column_blob,
  91305. sqlite3_column_bytes,
  91306. sqlite3_column_bytes16,
  91307. sqlite3_column_count,
  91308. sqlite3_column_database_name,
  91309. sqlite3_column_database_name16,
  91310. sqlite3_column_decltype,
  91311. sqlite3_column_decltype16,
  91312. sqlite3_column_double,
  91313. sqlite3_column_int,
  91314. sqlite3_column_int64,
  91315. sqlite3_column_name,
  91316. sqlite3_column_name16,
  91317. sqlite3_column_origin_name,
  91318. sqlite3_column_origin_name16,
  91319. sqlite3_column_table_name,
  91320. sqlite3_column_table_name16,
  91321. sqlite3_column_text,
  91322. sqlite3_column_text16,
  91323. sqlite3_column_type,
  91324. sqlite3_column_value,
  91325. sqlite3_commit_hook,
  91326. sqlite3_complete,
  91327. sqlite3_complete16,
  91328. sqlite3_create_collation,
  91329. sqlite3_create_collation16,
  91330. sqlite3_create_function,
  91331. sqlite3_create_function16,
  91332. sqlite3_create_module,
  91333. sqlite3_data_count,
  91334. sqlite3_db_handle,
  91335. sqlite3_declare_vtab,
  91336. sqlite3_enable_shared_cache,
  91337. sqlite3_errcode,
  91338. sqlite3_errmsg,
  91339. sqlite3_errmsg16,
  91340. sqlite3_exec,
  91341. #ifndef SQLITE_OMIT_DEPRECATED
  91342. sqlite3_expired,
  91343. #else
  91344. 0,
  91345. #endif
  91346. sqlite3_finalize,
  91347. sqlite3_free,
  91348. sqlite3_free_table,
  91349. sqlite3_get_autocommit,
  91350. sqlite3_get_auxdata,
  91351. sqlite3_get_table,
  91352. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  91353. sqlite3_interrupt,
  91354. sqlite3_last_insert_rowid,
  91355. sqlite3_libversion,
  91356. sqlite3_libversion_number,
  91357. sqlite3_malloc,
  91358. sqlite3_mprintf,
  91359. sqlite3_open,
  91360. sqlite3_open16,
  91361. sqlite3_prepare,
  91362. sqlite3_prepare16,
  91363. sqlite3_profile,
  91364. sqlite3_progress_handler,
  91365. sqlite3_realloc,
  91366. sqlite3_reset,
  91367. sqlite3_result_blob,
  91368. sqlite3_result_double,
  91369. sqlite3_result_error,
  91370. sqlite3_result_error16,
  91371. sqlite3_result_int,
  91372. sqlite3_result_int64,
  91373. sqlite3_result_null,
  91374. sqlite3_result_text,
  91375. sqlite3_result_text16,
  91376. sqlite3_result_text16be,
  91377. sqlite3_result_text16le,
  91378. sqlite3_result_value,
  91379. sqlite3_rollback_hook,
  91380. sqlite3_set_authorizer,
  91381. sqlite3_set_auxdata,
  91382. sqlite3_snprintf,
  91383. sqlite3_step,
  91384. sqlite3_table_column_metadata,
  91385. #ifndef SQLITE_OMIT_DEPRECATED
  91386. sqlite3_thread_cleanup,
  91387. #else
  91388. 0,
  91389. #endif
  91390. sqlite3_total_changes,
  91391. sqlite3_trace,
  91392. #ifndef SQLITE_OMIT_DEPRECATED
  91393. sqlite3_transfer_bindings,
  91394. #else
  91395. 0,
  91396. #endif
  91397. sqlite3_update_hook,
  91398. sqlite3_user_data,
  91399. sqlite3_value_blob,
  91400. sqlite3_value_bytes,
  91401. sqlite3_value_bytes16,
  91402. sqlite3_value_double,
  91403. sqlite3_value_int,
  91404. sqlite3_value_int64,
  91405. sqlite3_value_numeric_type,
  91406. sqlite3_value_text,
  91407. sqlite3_value_text16,
  91408. sqlite3_value_text16be,
  91409. sqlite3_value_text16le,
  91410. sqlite3_value_type,
  91411. sqlite3_vmprintf,
  91412. /*
  91413. ** The original API set ends here. All extensions can call any
  91414. ** of the APIs above provided that the pointer is not NULL. But
  91415. ** before calling APIs that follow, extension should check the
  91416. ** sqlite3_libversion_number() to make sure they are dealing with
  91417. ** a library that is new enough to support that API.
  91418. *************************************************************************
  91419. */
  91420. sqlite3_overload_function,
  91421. /*
  91422. ** Added after 3.3.13
  91423. */
  91424. sqlite3_prepare_v2,
  91425. sqlite3_prepare16_v2,
  91426. sqlite3_clear_bindings,
  91427. /*
  91428. ** Added for 3.4.1
  91429. */
  91430. sqlite3_create_module_v2,
  91431. /*
  91432. ** Added for 3.5.0
  91433. */
  91434. sqlite3_bind_zeroblob,
  91435. sqlite3_blob_bytes,
  91436. sqlite3_blob_close,
  91437. sqlite3_blob_open,
  91438. sqlite3_blob_read,
  91439. sqlite3_blob_write,
  91440. sqlite3_create_collation_v2,
  91441. sqlite3_file_control,
  91442. sqlite3_memory_highwater,
  91443. sqlite3_memory_used,
  91444. #ifdef SQLITE_MUTEX_OMIT
  91445. 0,
  91446. 0,
  91447. 0,
  91448. 0,
  91449. 0,
  91450. #else
  91451. sqlite3_mutex_alloc,
  91452. sqlite3_mutex_enter,
  91453. sqlite3_mutex_free,
  91454. sqlite3_mutex_leave,
  91455. sqlite3_mutex_try,
  91456. #endif
  91457. sqlite3_open_v2,
  91458. sqlite3_release_memory,
  91459. sqlite3_result_error_nomem,
  91460. sqlite3_result_error_toobig,
  91461. sqlite3_sleep,
  91462. sqlite3_soft_heap_limit,
  91463. sqlite3_vfs_find,
  91464. sqlite3_vfs_register,
  91465. sqlite3_vfs_unregister,
  91466. /*
  91467. ** Added for 3.5.8
  91468. */
  91469. sqlite3_threadsafe,
  91470. sqlite3_result_zeroblob,
  91471. sqlite3_result_error_code,
  91472. sqlite3_test_control,
  91473. sqlite3_randomness,
  91474. sqlite3_context_db_handle,
  91475. /*
  91476. ** Added for 3.6.0
  91477. */
  91478. sqlite3_extended_result_codes,
  91479. sqlite3_limit,
  91480. sqlite3_next_stmt,
  91481. sqlite3_sql,
  91482. sqlite3_status,
  91483. /*
  91484. ** Added for 3.7.4
  91485. */
  91486. sqlite3_backup_finish,
  91487. sqlite3_backup_init,
  91488. sqlite3_backup_pagecount,
  91489. sqlite3_backup_remaining,
  91490. sqlite3_backup_step,
  91491. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  91492. sqlite3_compileoption_get,
  91493. sqlite3_compileoption_used,
  91494. #else
  91495. 0,
  91496. 0,
  91497. #endif
  91498. sqlite3_create_function_v2,
  91499. sqlite3_db_config,
  91500. sqlite3_db_mutex,
  91501. sqlite3_db_status,
  91502. sqlite3_extended_errcode,
  91503. sqlite3_log,
  91504. sqlite3_soft_heap_limit64,
  91505. sqlite3_sourceid,
  91506. sqlite3_stmt_status,
  91507. sqlite3_strnicmp,
  91508. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  91509. sqlite3_unlock_notify,
  91510. #else
  91511. 0,
  91512. #endif
  91513. #ifndef SQLITE_OMIT_WAL
  91514. sqlite3_wal_autocheckpoint,
  91515. sqlite3_wal_checkpoint,
  91516. sqlite3_wal_hook,
  91517. #else
  91518. 0,
  91519. 0,
  91520. 0,
  91521. #endif
  91522. sqlite3_blob_reopen,
  91523. sqlite3_vtab_config,
  91524. sqlite3_vtab_on_conflict,
  91525. sqlite3_close_v2,
  91526. sqlite3_db_filename,
  91527. sqlite3_db_readonly,
  91528. sqlite3_db_release_memory,
  91529. sqlite3_errstr,
  91530. sqlite3_stmt_busy,
  91531. sqlite3_stmt_readonly,
  91532. sqlite3_stricmp,
  91533. sqlite3_uri_boolean,
  91534. sqlite3_uri_int64,
  91535. sqlite3_uri_parameter,
  91536. sqlite3_vsnprintf,
  91537. sqlite3_wal_checkpoint_v2
  91538. };
  91539. /*
  91540. ** Attempt to load an SQLite extension library contained in the file
  91541. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  91542. ** default entry point name (sqlite3_extension_init) is used. Use
  91543. ** of the default name is recommended.
  91544. **
  91545. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  91546. **
  91547. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  91548. ** error message text. The calling function should free this memory
  91549. ** by calling sqlite3DbFree(db, ).
  91550. */
  91551. static int sqlite3LoadExtension(
  91552. sqlite3 *db, /* Load the extension into this database connection */
  91553. const char *zFile, /* Name of the shared library containing extension */
  91554. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  91555. char **pzErrMsg /* Put error message here if not 0 */
  91556. ){
  91557. sqlite3_vfs *pVfs = db->pVfs;
  91558. void *handle;
  91559. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  91560. char *zErrmsg = 0;
  91561. const char *zEntry;
  91562. char *zAltEntry = 0;
  91563. void **aHandle;
  91564. int nMsg = 300 + sqlite3Strlen30(zFile);
  91565. int ii;
  91566. /* Shared library endings to try if zFile cannot be loaded as written */
  91567. static const char *azEndings[] = {
  91568. #if SQLITE_OS_WIN
  91569. "dll"
  91570. #elif defined(__APPLE__)
  91571. "dylib"
  91572. #else
  91573. "so"
  91574. #endif
  91575. };
  91576. if( pzErrMsg ) *pzErrMsg = 0;
  91577. /* Ticket #1863. To avoid a creating security problems for older
  91578. ** applications that relink against newer versions of SQLite, the
  91579. ** ability to run load_extension is turned off by default. One
  91580. ** must call sqlite3_enable_load_extension() to turn on extension
  91581. ** loading. Otherwise you get the following error.
  91582. */
  91583. if( (db->flags & SQLITE_LoadExtension)==0 ){
  91584. if( pzErrMsg ){
  91585. *pzErrMsg = sqlite3_mprintf("not authorized");
  91586. }
  91587. return SQLITE_ERROR;
  91588. }
  91589. zEntry = zProc ? zProc : "sqlite3_extension_init";
  91590. handle = sqlite3OsDlOpen(pVfs, zFile);
  91591. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  91592. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  91593. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  91594. if( zAltFile==0 ) return SQLITE_NOMEM;
  91595. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  91596. sqlite3_free(zAltFile);
  91597. }
  91598. #endif
  91599. if( handle==0 ){
  91600. if( pzErrMsg ){
  91601. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  91602. if( zErrmsg ){
  91603. sqlite3_snprintf(nMsg, zErrmsg,
  91604. "unable to open shared library [%s]", zFile);
  91605. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  91606. }
  91607. }
  91608. return SQLITE_ERROR;
  91609. }
  91610. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91611. sqlite3OsDlSym(pVfs, handle, zEntry);
  91612. /* If no entry point was specified and the default legacy
  91613. ** entry point name "sqlite3_extension_init" was not found, then
  91614. ** construct an entry point name "sqlite3_X_init" where the X is
  91615. ** replaced by the lowercase value of every ASCII alphabetic
  91616. ** character in the filename after the last "/" upto the first ".",
  91617. ** and eliding the first three characters if they are "lib".
  91618. ** Examples:
  91619. **
  91620. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  91621. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  91622. */
  91623. if( xInit==0 && zProc==0 ){
  91624. int iFile, iEntry, c;
  91625. int ncFile = sqlite3Strlen30(zFile);
  91626. zAltEntry = sqlite3_malloc(ncFile+30);
  91627. if( zAltEntry==0 ){
  91628. sqlite3OsDlClose(pVfs, handle);
  91629. return SQLITE_NOMEM;
  91630. }
  91631. memcpy(zAltEntry, "sqlite3_", 8);
  91632. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  91633. iFile++;
  91634. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  91635. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  91636. if( sqlite3Isalpha(c) ){
  91637. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  91638. }
  91639. }
  91640. memcpy(zAltEntry+iEntry, "_init", 6);
  91641. zEntry = zAltEntry;
  91642. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91643. sqlite3OsDlSym(pVfs, handle, zEntry);
  91644. }
  91645. if( xInit==0 ){
  91646. if( pzErrMsg ){
  91647. nMsg += sqlite3Strlen30(zEntry);
  91648. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  91649. if( zErrmsg ){
  91650. sqlite3_snprintf(nMsg, zErrmsg,
  91651. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  91652. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  91653. }
  91654. }
  91655. sqlite3OsDlClose(pVfs, handle);
  91656. sqlite3_free(zAltEntry);
  91657. return SQLITE_ERROR;
  91658. }
  91659. sqlite3_free(zAltEntry);
  91660. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  91661. if( pzErrMsg ){
  91662. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  91663. }
  91664. sqlite3_free(zErrmsg);
  91665. sqlite3OsDlClose(pVfs, handle);
  91666. return SQLITE_ERROR;
  91667. }
  91668. /* Append the new shared library handle to the db->aExtension array. */
  91669. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  91670. if( aHandle==0 ){
  91671. return SQLITE_NOMEM;
  91672. }
  91673. if( db->nExtension>0 ){
  91674. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  91675. }
  91676. sqlite3DbFree(db, db->aExtension);
  91677. db->aExtension = aHandle;
  91678. db->aExtension[db->nExtension++] = handle;
  91679. return SQLITE_OK;
  91680. }
  91681. SQLITE_API int sqlite3_load_extension(
  91682. sqlite3 *db, /* Load the extension into this database connection */
  91683. const char *zFile, /* Name of the shared library containing extension */
  91684. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  91685. char **pzErrMsg /* Put error message here if not 0 */
  91686. ){
  91687. int rc;
  91688. sqlite3_mutex_enter(db->mutex);
  91689. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  91690. rc = sqlite3ApiExit(db, rc);
  91691. sqlite3_mutex_leave(db->mutex);
  91692. return rc;
  91693. }
  91694. /*
  91695. ** Call this routine when the database connection is closing in order
  91696. ** to clean up loaded extensions
  91697. */
  91698. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  91699. int i;
  91700. assert( sqlite3_mutex_held(db->mutex) );
  91701. for(i=0; i<db->nExtension; i++){
  91702. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  91703. }
  91704. sqlite3DbFree(db, db->aExtension);
  91705. }
  91706. /*
  91707. ** Enable or disable extension loading. Extension loading is disabled by
  91708. ** default so as not to open security holes in older applications.
  91709. */
  91710. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  91711. sqlite3_mutex_enter(db->mutex);
  91712. if( onoff ){
  91713. db->flags |= SQLITE_LoadExtension;
  91714. }else{
  91715. db->flags &= ~SQLITE_LoadExtension;
  91716. }
  91717. sqlite3_mutex_leave(db->mutex);
  91718. return SQLITE_OK;
  91719. }
  91720. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  91721. /*
  91722. ** The auto-extension code added regardless of whether or not extension
  91723. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  91724. ** code if regular extension loading is not available. This is that
  91725. ** dummy pointer.
  91726. */
  91727. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  91728. static const sqlite3_api_routines sqlite3Apis = { 0 };
  91729. #endif
  91730. /*
  91731. ** The following object holds the list of automatically loaded
  91732. ** extensions.
  91733. **
  91734. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  91735. ** mutex must be held while accessing this list.
  91736. */
  91737. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  91738. static SQLITE_WSD struct sqlite3AutoExtList {
  91739. int nExt; /* Number of entries in aExt[] */
  91740. void (**aExt)(void); /* Pointers to the extension init functions */
  91741. } sqlite3Autoext = { 0, 0 };
  91742. /* The "wsdAutoext" macro will resolve to the autoextension
  91743. ** state vector. If writable static data is unsupported on the target,
  91744. ** we have to locate the state vector at run-time. In the more common
  91745. ** case where writable static data is supported, wsdStat can refer directly
  91746. ** to the "sqlite3Autoext" state vector declared above.
  91747. */
  91748. #ifdef SQLITE_OMIT_WSD
  91749. # define wsdAutoextInit \
  91750. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  91751. # define wsdAutoext x[0]
  91752. #else
  91753. # define wsdAutoextInit
  91754. # define wsdAutoext sqlite3Autoext
  91755. #endif
  91756. /*
  91757. ** Register a statically linked extension that is automatically
  91758. ** loaded by every new database connection.
  91759. */
  91760. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  91761. int rc = SQLITE_OK;
  91762. #ifndef SQLITE_OMIT_AUTOINIT
  91763. rc = sqlite3_initialize();
  91764. if( rc ){
  91765. return rc;
  91766. }else
  91767. #endif
  91768. {
  91769. int i;
  91770. #if SQLITE_THREADSAFE
  91771. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91772. #endif
  91773. wsdAutoextInit;
  91774. sqlite3_mutex_enter(mutex);
  91775. for(i=0; i<wsdAutoext.nExt; i++){
  91776. if( wsdAutoext.aExt[i]==xInit ) break;
  91777. }
  91778. if( i==wsdAutoext.nExt ){
  91779. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  91780. void (**aNew)(void);
  91781. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  91782. if( aNew==0 ){
  91783. rc = SQLITE_NOMEM;
  91784. }else{
  91785. wsdAutoext.aExt = aNew;
  91786. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  91787. wsdAutoext.nExt++;
  91788. }
  91789. }
  91790. sqlite3_mutex_leave(mutex);
  91791. assert( (rc&0xff)==rc );
  91792. return rc;
  91793. }
  91794. }
  91795. /*
  91796. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  91797. ** set of routines that is invoked for each new database connection, if it
  91798. ** is currently on the list. If xInit is not on the list, then this
  91799. ** routine is a no-op.
  91800. **
  91801. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  91802. ** was not on the list.
  91803. */
  91804. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  91805. #if SQLITE_THREADSAFE
  91806. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91807. #endif
  91808. int i;
  91809. int n = 0;
  91810. wsdAutoextInit;
  91811. sqlite3_mutex_enter(mutex);
  91812. for(i=wsdAutoext.nExt-1; i>=0; i--){
  91813. if( wsdAutoext.aExt[i]==xInit ){
  91814. wsdAutoext.nExt--;
  91815. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  91816. n++;
  91817. break;
  91818. }
  91819. }
  91820. sqlite3_mutex_leave(mutex);
  91821. return n;
  91822. }
  91823. /*
  91824. ** Reset the automatic extension loading mechanism.
  91825. */
  91826. SQLITE_API void sqlite3_reset_auto_extension(void){
  91827. #ifndef SQLITE_OMIT_AUTOINIT
  91828. if( sqlite3_initialize()==SQLITE_OK )
  91829. #endif
  91830. {
  91831. #if SQLITE_THREADSAFE
  91832. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91833. #endif
  91834. wsdAutoextInit;
  91835. sqlite3_mutex_enter(mutex);
  91836. sqlite3_free(wsdAutoext.aExt);
  91837. wsdAutoext.aExt = 0;
  91838. wsdAutoext.nExt = 0;
  91839. sqlite3_mutex_leave(mutex);
  91840. }
  91841. }
  91842. /*
  91843. ** Load all automatic extensions.
  91844. **
  91845. ** If anything goes wrong, set an error in the database connection.
  91846. */
  91847. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  91848. int i;
  91849. int go = 1;
  91850. int rc;
  91851. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  91852. wsdAutoextInit;
  91853. if( wsdAutoext.nExt==0 ){
  91854. /* Common case: early out without every having to acquire a mutex */
  91855. return;
  91856. }
  91857. for(i=0; go; i++){
  91858. char *zErrmsg;
  91859. #if SQLITE_THREADSAFE
  91860. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91861. #endif
  91862. sqlite3_mutex_enter(mutex);
  91863. if( i>=wsdAutoext.nExt ){
  91864. xInit = 0;
  91865. go = 0;
  91866. }else{
  91867. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91868. wsdAutoext.aExt[i];
  91869. }
  91870. sqlite3_mutex_leave(mutex);
  91871. zErrmsg = 0;
  91872. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  91873. sqlite3Error(db, rc,
  91874. "automatic extension loading failed: %s", zErrmsg);
  91875. go = 0;
  91876. }
  91877. sqlite3_free(zErrmsg);
  91878. }
  91879. }
  91880. /************** End of loadext.c *********************************************/
  91881. /************** Begin file pragma.c ******************************************/
  91882. /*
  91883. ** 2003 April 6
  91884. **
  91885. ** The author disclaims copyright to this source code. In place of
  91886. ** a legal notice, here is a blessing:
  91887. **
  91888. ** May you do good and not evil.
  91889. ** May you find forgiveness for yourself and forgive others.
  91890. ** May you share freely, never taking more than you give.
  91891. **
  91892. *************************************************************************
  91893. ** This file contains code used to implement the PRAGMA command.
  91894. */
  91895. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  91896. # if defined(__APPLE__)
  91897. # define SQLITE_ENABLE_LOCKING_STYLE 1
  91898. # else
  91899. # define SQLITE_ENABLE_LOCKING_STYLE 0
  91900. # endif
  91901. #endif
  91902. /***************************************************************************
  91903. ** The next block of code, including the PragTyp_XXXX macro definitions and
  91904. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  91905. **
  91906. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  91907. ** that script. Then copy/paste the output in place of the following:
  91908. */
  91909. #define PragTyp_HEADER_VALUE 0
  91910. #define PragTyp_AUTO_VACUUM 1
  91911. #define PragTyp_FLAG 2
  91912. #define PragTyp_BUSY_TIMEOUT 3
  91913. #define PragTyp_CACHE_SIZE 4
  91914. #define PragTyp_CASE_SENSITIVE_LIKE 5
  91915. #define PragTyp_COLLATION_LIST 6
  91916. #define PragTyp_COMPILE_OPTIONS 7
  91917. #define PragTyp_DATA_STORE_DIRECTORY 8
  91918. #define PragTyp_DATABASE_LIST 9
  91919. #define PragTyp_DEFAULT_CACHE_SIZE 10
  91920. #define PragTyp_ENCODING 11
  91921. #define PragTyp_FOREIGN_KEY_CHECK 12
  91922. #define PragTyp_FOREIGN_KEY_LIST 13
  91923. #define PragTyp_INCREMENTAL_VACUUM 14
  91924. #define PragTyp_INDEX_INFO 15
  91925. #define PragTyp_INDEX_LIST 16
  91926. #define PragTyp_INTEGRITY_CHECK 17
  91927. #define PragTyp_JOURNAL_MODE 18
  91928. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  91929. #define PragTyp_LOCK_PROXY_FILE 20
  91930. #define PragTyp_LOCKING_MODE 21
  91931. #define PragTyp_PAGE_COUNT 22
  91932. #define PragTyp_MMAP_SIZE 23
  91933. #define PragTyp_PAGE_SIZE 24
  91934. #define PragTyp_SECURE_DELETE 25
  91935. #define PragTyp_SHRINK_MEMORY 26
  91936. #define PragTyp_SOFT_HEAP_LIMIT 27
  91937. #define PragTyp_STATS 28
  91938. #define PragTyp_SYNCHRONOUS 29
  91939. #define PragTyp_TABLE_INFO 30
  91940. #define PragTyp_TEMP_STORE 31
  91941. #define PragTyp_TEMP_STORE_DIRECTORY 32
  91942. #define PragTyp_WAL_AUTOCHECKPOINT 33
  91943. #define PragTyp_WAL_CHECKPOINT 34
  91944. #define PragTyp_ACTIVATE_EXTENSIONS 35
  91945. #define PragTyp_HEXKEY 36
  91946. #define PragTyp_KEY 37
  91947. #define PragTyp_REKEY 38
  91948. #define PragTyp_LOCK_STATUS 39
  91949. #define PragTyp_PARSER_TRACE 40
  91950. #define PragFlag_NeedSchema 0x01
  91951. static const struct sPragmaNames {
  91952. const char *const zName; /* Name of pragma */
  91953. u8 ePragTyp; /* PragTyp_XXX value */
  91954. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  91955. u32 iArg; /* Extra argument */
  91956. } aPragmaNames[] = {
  91957. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  91958. { /* zName: */ "activate_extensions",
  91959. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  91960. /* ePragFlag: */ 0,
  91961. /* iArg: */ 0 },
  91962. #endif
  91963. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  91964. { /* zName: */ "application_id",
  91965. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  91966. /* ePragFlag: */ 0,
  91967. /* iArg: */ 0 },
  91968. #endif
  91969. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  91970. { /* zName: */ "auto_vacuum",
  91971. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  91972. /* ePragFlag: */ PragFlag_NeedSchema,
  91973. /* iArg: */ 0 },
  91974. #endif
  91975. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  91976. { /* zName: */ "automatic_index",
  91977. /* ePragTyp: */ PragTyp_FLAG,
  91978. /* ePragFlag: */ 0,
  91979. /* iArg: */ SQLITE_AutoIndex },
  91980. #endif
  91981. { /* zName: */ "busy_timeout",
  91982. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  91983. /* ePragFlag: */ 0,
  91984. /* iArg: */ 0 },
  91985. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  91986. { /* zName: */ "cache_size",
  91987. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  91988. /* ePragFlag: */ PragFlag_NeedSchema,
  91989. /* iArg: */ 0 },
  91990. #endif
  91991. { /* zName: */ "cache_spill",
  91992. /* ePragTyp: */ PragTyp_FLAG,
  91993. /* ePragFlag: */ 0,
  91994. /* iArg: */ SQLITE_CacheSpill },
  91995. { /* zName: */ "case_sensitive_like",
  91996. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  91997. /* ePragFlag: */ 0,
  91998. /* iArg: */ 0 },
  91999. { /* zName: */ "checkpoint_fullfsync",
  92000. /* ePragTyp: */ PragTyp_FLAG,
  92001. /* ePragFlag: */ 0,
  92002. /* iArg: */ SQLITE_CkptFullFSync },
  92003. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92004. { /* zName: */ "collation_list",
  92005. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  92006. /* ePragFlag: */ 0,
  92007. /* iArg: */ 0 },
  92008. #endif
  92009. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  92010. { /* zName: */ "compile_options",
  92011. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  92012. /* ePragFlag: */ 0,
  92013. /* iArg: */ 0 },
  92014. #endif
  92015. { /* zName: */ "count_changes",
  92016. /* ePragTyp: */ PragTyp_FLAG,
  92017. /* ePragFlag: */ 0,
  92018. /* iArg: */ SQLITE_CountRows },
  92019. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  92020. { /* zName: */ "data_store_directory",
  92021. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  92022. /* ePragFlag: */ 0,
  92023. /* iArg: */ 0 },
  92024. #endif
  92025. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92026. { /* zName: */ "database_list",
  92027. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  92028. /* ePragFlag: */ PragFlag_NeedSchema,
  92029. /* iArg: */ 0 },
  92030. #endif
  92031. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  92032. { /* zName: */ "default_cache_size",
  92033. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  92034. /* ePragFlag: */ PragFlag_NeedSchema,
  92035. /* iArg: */ 0 },
  92036. #endif
  92037. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92038. { /* zName: */ "defer_foreign_keys",
  92039. /* ePragTyp: */ PragTyp_FLAG,
  92040. /* ePragFlag: */ 0,
  92041. /* iArg: */ SQLITE_DeferFKs },
  92042. #endif
  92043. { /* zName: */ "empty_result_callbacks",
  92044. /* ePragTyp: */ PragTyp_FLAG,
  92045. /* ePragFlag: */ 0,
  92046. /* iArg: */ SQLITE_NullCallback },
  92047. #if !defined(SQLITE_OMIT_UTF16)
  92048. { /* zName: */ "encoding",
  92049. /* ePragTyp: */ PragTyp_ENCODING,
  92050. /* ePragFlag: */ 0,
  92051. /* iArg: */ 0 },
  92052. #endif
  92053. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92054. { /* zName: */ "foreign_key_check",
  92055. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  92056. /* ePragFlag: */ PragFlag_NeedSchema,
  92057. /* iArg: */ 0 },
  92058. #endif
  92059. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  92060. { /* zName: */ "foreign_key_list",
  92061. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  92062. /* ePragFlag: */ PragFlag_NeedSchema,
  92063. /* iArg: */ 0 },
  92064. #endif
  92065. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92066. { /* zName: */ "foreign_keys",
  92067. /* ePragTyp: */ PragTyp_FLAG,
  92068. /* ePragFlag: */ 0,
  92069. /* iArg: */ SQLITE_ForeignKeys },
  92070. #endif
  92071. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92072. { /* zName: */ "freelist_count",
  92073. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92074. /* ePragFlag: */ 0,
  92075. /* iArg: */ 0 },
  92076. #endif
  92077. { /* zName: */ "full_column_names",
  92078. /* ePragTyp: */ PragTyp_FLAG,
  92079. /* ePragFlag: */ 0,
  92080. /* iArg: */ SQLITE_FullColNames },
  92081. { /* zName: */ "fullfsync",
  92082. /* ePragTyp: */ PragTyp_FLAG,
  92083. /* ePragFlag: */ 0,
  92084. /* iArg: */ SQLITE_FullFSync },
  92085. #if defined(SQLITE_HAS_CODEC)
  92086. { /* zName: */ "hexkey",
  92087. /* ePragTyp: */ PragTyp_HEXKEY,
  92088. /* ePragFlag: */ 0,
  92089. /* iArg: */ 0 },
  92090. { /* zName: */ "hexrekey",
  92091. /* ePragTyp: */ PragTyp_HEXKEY,
  92092. /* ePragFlag: */ 0,
  92093. /* iArg: */ 0 },
  92094. #endif
  92095. #if !defined(SQLITE_OMIT_CHECK)
  92096. { /* zName: */ "ignore_check_constraints",
  92097. /* ePragTyp: */ PragTyp_FLAG,
  92098. /* ePragFlag: */ 0,
  92099. /* iArg: */ SQLITE_IgnoreChecks },
  92100. #endif
  92101. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  92102. { /* zName: */ "incremental_vacuum",
  92103. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  92104. /* ePragFlag: */ PragFlag_NeedSchema,
  92105. /* iArg: */ 0 },
  92106. #endif
  92107. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92108. { /* zName: */ "index_info",
  92109. /* ePragTyp: */ PragTyp_INDEX_INFO,
  92110. /* ePragFlag: */ PragFlag_NeedSchema,
  92111. /* iArg: */ 0 },
  92112. { /* zName: */ "index_list",
  92113. /* ePragTyp: */ PragTyp_INDEX_LIST,
  92114. /* ePragFlag: */ PragFlag_NeedSchema,
  92115. /* iArg: */ 0 },
  92116. #endif
  92117. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  92118. { /* zName: */ "integrity_check",
  92119. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  92120. /* ePragFlag: */ PragFlag_NeedSchema,
  92121. /* iArg: */ 0 },
  92122. #endif
  92123. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92124. { /* zName: */ "journal_mode",
  92125. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  92126. /* ePragFlag: */ PragFlag_NeedSchema,
  92127. /* iArg: */ 0 },
  92128. { /* zName: */ "journal_size_limit",
  92129. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  92130. /* ePragFlag: */ 0,
  92131. /* iArg: */ 0 },
  92132. #endif
  92133. #if defined(SQLITE_HAS_CODEC)
  92134. { /* zName: */ "key",
  92135. /* ePragTyp: */ PragTyp_KEY,
  92136. /* ePragFlag: */ 0,
  92137. /* iArg: */ 0 },
  92138. #endif
  92139. { /* zName: */ "legacy_file_format",
  92140. /* ePragTyp: */ PragTyp_FLAG,
  92141. /* ePragFlag: */ 0,
  92142. /* iArg: */ SQLITE_LegacyFileFmt },
  92143. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  92144. { /* zName: */ "lock_proxy_file",
  92145. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  92146. /* ePragFlag: */ 0,
  92147. /* iArg: */ 0 },
  92148. #endif
  92149. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  92150. { /* zName: */ "lock_status",
  92151. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  92152. /* ePragFlag: */ 0,
  92153. /* iArg: */ 0 },
  92154. #endif
  92155. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92156. { /* zName: */ "locking_mode",
  92157. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  92158. /* ePragFlag: */ 0,
  92159. /* iArg: */ 0 },
  92160. { /* zName: */ "max_page_count",
  92161. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  92162. /* ePragFlag: */ PragFlag_NeedSchema,
  92163. /* iArg: */ 0 },
  92164. { /* zName: */ "mmap_size",
  92165. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  92166. /* ePragFlag: */ 0,
  92167. /* iArg: */ 0 },
  92168. { /* zName: */ "page_count",
  92169. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  92170. /* ePragFlag: */ PragFlag_NeedSchema,
  92171. /* iArg: */ 0 },
  92172. { /* zName: */ "page_size",
  92173. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  92174. /* ePragFlag: */ 0,
  92175. /* iArg: */ 0 },
  92176. #endif
  92177. #if defined(SQLITE_DEBUG)
  92178. { /* zName: */ "parser_trace",
  92179. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  92180. /* ePragFlag: */ 0,
  92181. /* iArg: */ 0 },
  92182. #endif
  92183. { /* zName: */ "query_only",
  92184. /* ePragTyp: */ PragTyp_FLAG,
  92185. /* ePragFlag: */ 0,
  92186. /* iArg: */ SQLITE_QueryOnly },
  92187. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  92188. { /* zName: */ "quick_check",
  92189. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  92190. /* ePragFlag: */ PragFlag_NeedSchema,
  92191. /* iArg: */ 0 },
  92192. #endif
  92193. { /* zName: */ "read_uncommitted",
  92194. /* ePragTyp: */ PragTyp_FLAG,
  92195. /* ePragFlag: */ 0,
  92196. /* iArg: */ SQLITE_ReadUncommitted },
  92197. { /* zName: */ "recursive_triggers",
  92198. /* ePragTyp: */ PragTyp_FLAG,
  92199. /* ePragFlag: */ 0,
  92200. /* iArg: */ SQLITE_RecTriggers },
  92201. #if defined(SQLITE_HAS_CODEC)
  92202. { /* zName: */ "rekey",
  92203. /* ePragTyp: */ PragTyp_REKEY,
  92204. /* ePragFlag: */ 0,
  92205. /* iArg: */ 0 },
  92206. #endif
  92207. { /* zName: */ "reverse_unordered_selects",
  92208. /* ePragTyp: */ PragTyp_FLAG,
  92209. /* ePragFlag: */ 0,
  92210. /* iArg: */ SQLITE_ReverseOrder },
  92211. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92212. { /* zName: */ "schema_version",
  92213. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92214. /* ePragFlag: */ 0,
  92215. /* iArg: */ 0 },
  92216. #endif
  92217. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92218. { /* zName: */ "secure_delete",
  92219. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  92220. /* ePragFlag: */ 0,
  92221. /* iArg: */ 0 },
  92222. #endif
  92223. { /* zName: */ "short_column_names",
  92224. /* ePragTyp: */ PragTyp_FLAG,
  92225. /* ePragFlag: */ 0,
  92226. /* iArg: */ SQLITE_ShortColNames },
  92227. { /* zName: */ "shrink_memory",
  92228. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  92229. /* ePragFlag: */ 0,
  92230. /* iArg: */ 0 },
  92231. { /* zName: */ "soft_heap_limit",
  92232. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  92233. /* ePragFlag: */ 0,
  92234. /* iArg: */ 0 },
  92235. #if defined(SQLITE_DEBUG)
  92236. { /* zName: */ "sql_trace",
  92237. /* ePragTyp: */ PragTyp_FLAG,
  92238. /* ePragFlag: */ 0,
  92239. /* iArg: */ SQLITE_SqlTrace },
  92240. #endif
  92241. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92242. { /* zName: */ "stats",
  92243. /* ePragTyp: */ PragTyp_STATS,
  92244. /* ePragFlag: */ PragFlag_NeedSchema,
  92245. /* iArg: */ 0 },
  92246. #endif
  92247. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92248. { /* zName: */ "synchronous",
  92249. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  92250. /* ePragFlag: */ PragFlag_NeedSchema,
  92251. /* iArg: */ 0 },
  92252. #endif
  92253. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92254. { /* zName: */ "table_info",
  92255. /* ePragTyp: */ PragTyp_TABLE_INFO,
  92256. /* ePragFlag: */ PragFlag_NeedSchema,
  92257. /* iArg: */ 0 },
  92258. #endif
  92259. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92260. { /* zName: */ "temp_store",
  92261. /* ePragTyp: */ PragTyp_TEMP_STORE,
  92262. /* ePragFlag: */ 0,
  92263. /* iArg: */ 0 },
  92264. { /* zName: */ "temp_store_directory",
  92265. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  92266. /* ePragFlag: */ 0,
  92267. /* iArg: */ 0 },
  92268. #endif
  92269. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92270. { /* zName: */ "user_version",
  92271. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92272. /* ePragFlag: */ 0,
  92273. /* iArg: */ 0 },
  92274. #endif
  92275. #if defined(SQLITE_DEBUG)
  92276. { /* zName: */ "vdbe_addoptrace",
  92277. /* ePragTyp: */ PragTyp_FLAG,
  92278. /* ePragFlag: */ 0,
  92279. /* iArg: */ SQLITE_VdbeAddopTrace },
  92280. { /* zName: */ "vdbe_debug",
  92281. /* ePragTyp: */ PragTyp_FLAG,
  92282. /* ePragFlag: */ 0,
  92283. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  92284. { /* zName: */ "vdbe_listing",
  92285. /* ePragTyp: */ PragTyp_FLAG,
  92286. /* ePragFlag: */ 0,
  92287. /* iArg: */ SQLITE_VdbeListing },
  92288. { /* zName: */ "vdbe_trace",
  92289. /* ePragTyp: */ PragTyp_FLAG,
  92290. /* ePragFlag: */ 0,
  92291. /* iArg: */ SQLITE_VdbeTrace },
  92292. #endif
  92293. #if !defined(SQLITE_OMIT_WAL)
  92294. { /* zName: */ "wal_autocheckpoint",
  92295. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  92296. /* ePragFlag: */ 0,
  92297. /* iArg: */ 0 },
  92298. { /* zName: */ "wal_checkpoint",
  92299. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  92300. /* ePragFlag: */ PragFlag_NeedSchema,
  92301. /* iArg: */ 0 },
  92302. #endif
  92303. { /* zName: */ "writable_schema",
  92304. /* ePragTyp: */ PragTyp_FLAG,
  92305. /* ePragFlag: */ 0,
  92306. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  92307. };
  92308. /* Number of pragmas: 56 on by default, 68 total. */
  92309. /* End of the automatically generated pragma table.
  92310. ***************************************************************************/
  92311. /*
  92312. ** Interpret the given string as a safety level. Return 0 for OFF,
  92313. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  92314. ** unrecognized string argument. The FULL option is disallowed
  92315. ** if the omitFull parameter it 1.
  92316. **
  92317. ** Note that the values returned are one less that the values that
  92318. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  92319. ** to support legacy SQL code. The safety level used to be boolean
  92320. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  92321. */
  92322. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  92323. /* 123456789 123456789 */
  92324. static const char zText[] = "onoffalseyestruefull";
  92325. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  92326. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  92327. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  92328. int i, n;
  92329. if( sqlite3Isdigit(*z) ){
  92330. return (u8)sqlite3Atoi(z);
  92331. }
  92332. n = sqlite3Strlen30(z);
  92333. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  92334. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  92335. return iValue[i];
  92336. }
  92337. }
  92338. return dflt;
  92339. }
  92340. /*
  92341. ** Interpret the given string as a boolean value.
  92342. */
  92343. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  92344. return getSafetyLevel(z,1,dflt)!=0;
  92345. }
  92346. /* The sqlite3GetBoolean() function is used by other modules but the
  92347. ** remainder of this file is specific to PRAGMA processing. So omit
  92348. ** the rest of the file if PRAGMAs are omitted from the build.
  92349. */
  92350. #if !defined(SQLITE_OMIT_PRAGMA)
  92351. /*
  92352. ** Interpret the given string as a locking mode value.
  92353. */
  92354. static int getLockingMode(const char *z){
  92355. if( z ){
  92356. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  92357. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  92358. }
  92359. return PAGER_LOCKINGMODE_QUERY;
  92360. }
  92361. #ifndef SQLITE_OMIT_AUTOVACUUM
  92362. /*
  92363. ** Interpret the given string as an auto-vacuum mode value.
  92364. **
  92365. ** The following strings, "none", "full" and "incremental" are
  92366. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  92367. */
  92368. static int getAutoVacuum(const char *z){
  92369. int i;
  92370. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  92371. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  92372. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  92373. i = sqlite3Atoi(z);
  92374. return (u8)((i>=0&&i<=2)?i:0);
  92375. }
  92376. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  92377. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92378. /*
  92379. ** Interpret the given string as a temp db location. Return 1 for file
  92380. ** backed temporary databases, 2 for the Red-Black tree in memory database
  92381. ** and 0 to use the compile-time default.
  92382. */
  92383. static int getTempStore(const char *z){
  92384. if( z[0]>='0' && z[0]<='2' ){
  92385. return z[0] - '0';
  92386. }else if( sqlite3StrICmp(z, "file")==0 ){
  92387. return 1;
  92388. }else if( sqlite3StrICmp(z, "memory")==0 ){
  92389. return 2;
  92390. }else{
  92391. return 0;
  92392. }
  92393. }
  92394. #endif /* SQLITE_PAGER_PRAGMAS */
  92395. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92396. /*
  92397. ** Invalidate temp storage, either when the temp storage is changed
  92398. ** from default, or when 'file' and the temp_store_directory has changed
  92399. */
  92400. static int invalidateTempStorage(Parse *pParse){
  92401. sqlite3 *db = pParse->db;
  92402. if( db->aDb[1].pBt!=0 ){
  92403. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  92404. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  92405. "from within a transaction");
  92406. return SQLITE_ERROR;
  92407. }
  92408. sqlite3BtreeClose(db->aDb[1].pBt);
  92409. db->aDb[1].pBt = 0;
  92410. sqlite3ResetAllSchemasOfConnection(db);
  92411. }
  92412. return SQLITE_OK;
  92413. }
  92414. #endif /* SQLITE_PAGER_PRAGMAS */
  92415. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92416. /*
  92417. ** If the TEMP database is open, close it and mark the database schema
  92418. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  92419. ** or DEFAULT_TEMP_STORE pragmas.
  92420. */
  92421. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  92422. int ts = getTempStore(zStorageType);
  92423. sqlite3 *db = pParse->db;
  92424. if( db->temp_store==ts ) return SQLITE_OK;
  92425. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  92426. return SQLITE_ERROR;
  92427. }
  92428. db->temp_store = (u8)ts;
  92429. return SQLITE_OK;
  92430. }
  92431. #endif /* SQLITE_PAGER_PRAGMAS */
  92432. /*
  92433. ** Generate code to return a single integer value.
  92434. */
  92435. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  92436. Vdbe *v = sqlite3GetVdbe(pParse);
  92437. int mem = ++pParse->nMem;
  92438. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  92439. if( pI64 ){
  92440. memcpy(pI64, &value, sizeof(value));
  92441. }
  92442. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  92443. sqlite3VdbeSetNumCols(v, 1);
  92444. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  92445. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  92446. }
  92447. /*
  92448. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  92449. ** set these values for all pagers.
  92450. */
  92451. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92452. static void setAllPagerFlags(sqlite3 *db){
  92453. if( db->autoCommit ){
  92454. Db *pDb = db->aDb;
  92455. int n = db->nDb;
  92456. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  92457. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  92458. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  92459. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  92460. == PAGER_FLAGS_MASK );
  92461. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  92462. while( (n--) > 0 ){
  92463. if( pDb->pBt ){
  92464. sqlite3BtreeSetPagerFlags(pDb->pBt,
  92465. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  92466. }
  92467. pDb++;
  92468. }
  92469. }
  92470. }
  92471. #else
  92472. # define setAllPagerFlags(X) /* no-op */
  92473. #endif
  92474. /*
  92475. ** Return a human-readable name for a constraint resolution action.
  92476. */
  92477. #ifndef SQLITE_OMIT_FOREIGN_KEY
  92478. static const char *actionName(u8 action){
  92479. const char *zName;
  92480. switch( action ){
  92481. case OE_SetNull: zName = "SET NULL"; break;
  92482. case OE_SetDflt: zName = "SET DEFAULT"; break;
  92483. case OE_Cascade: zName = "CASCADE"; break;
  92484. case OE_Restrict: zName = "RESTRICT"; break;
  92485. default: zName = "NO ACTION";
  92486. assert( action==OE_None ); break;
  92487. }
  92488. return zName;
  92489. }
  92490. #endif
  92491. /*
  92492. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  92493. ** defined in pager.h. This function returns the associated lowercase
  92494. ** journal-mode name.
  92495. */
  92496. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  92497. static char * const azModeName[] = {
  92498. "delete", "persist", "off", "truncate", "memory"
  92499. #ifndef SQLITE_OMIT_WAL
  92500. , "wal"
  92501. #endif
  92502. };
  92503. assert( PAGER_JOURNALMODE_DELETE==0 );
  92504. assert( PAGER_JOURNALMODE_PERSIST==1 );
  92505. assert( PAGER_JOURNALMODE_OFF==2 );
  92506. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  92507. assert( PAGER_JOURNALMODE_MEMORY==4 );
  92508. assert( PAGER_JOURNALMODE_WAL==5 );
  92509. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  92510. if( eMode==ArraySize(azModeName) ) return 0;
  92511. return azModeName[eMode];
  92512. }
  92513. /*
  92514. ** Process a pragma statement.
  92515. **
  92516. ** Pragmas are of this form:
  92517. **
  92518. ** PRAGMA [database.]id [= value]
  92519. **
  92520. ** The identifier might also be a string. The value is a string, and
  92521. ** identifier, or a number. If minusFlag is true, then the value is
  92522. ** a number that was preceded by a minus sign.
  92523. **
  92524. ** If the left side is "database.id" then pId1 is the database name
  92525. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  92526. ** id and pId2 is any empty string.
  92527. */
  92528. SQLITE_PRIVATE void sqlite3Pragma(
  92529. Parse *pParse,
  92530. Token *pId1, /* First part of [database.]id field */
  92531. Token *pId2, /* Second part of [database.]id field, or NULL */
  92532. Token *pValue, /* Token for <value>, or NULL */
  92533. int minusFlag /* True if a '-' sign preceded <value> */
  92534. ){
  92535. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  92536. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  92537. const char *zDb = 0; /* The database name */
  92538. Token *pId; /* Pointer to <id> token */
  92539. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  92540. int iDb; /* Database index for <database> */
  92541. int lwr, upr, mid; /* Binary search bounds */
  92542. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  92543. sqlite3 *db = pParse->db; /* The database connection */
  92544. Db *pDb; /* The specific database being pragmaed */
  92545. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  92546. if( v==0 ) return;
  92547. sqlite3VdbeRunOnlyOnce(v);
  92548. pParse->nMem = 2;
  92549. /* Interpret the [database.] part of the pragma statement. iDb is the
  92550. ** index of the database this pragma is being applied to in db.aDb[]. */
  92551. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  92552. if( iDb<0 ) return;
  92553. pDb = &db->aDb[iDb];
  92554. /* If the temp database has been explicitly named as part of the
  92555. ** pragma, make sure it is open.
  92556. */
  92557. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  92558. return;
  92559. }
  92560. zLeft = sqlite3NameFromToken(db, pId);
  92561. if( !zLeft ) return;
  92562. if( minusFlag ){
  92563. zRight = sqlite3MPrintf(db, "-%T", pValue);
  92564. }else{
  92565. zRight = sqlite3NameFromToken(db, pValue);
  92566. }
  92567. assert( pId2 );
  92568. zDb = pId2->n>0 ? pDb->zName : 0;
  92569. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  92570. goto pragma_out;
  92571. }
  92572. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  92573. ** connection. If it returns SQLITE_OK, then assume that the VFS
  92574. ** handled the pragma and generate a no-op prepared statement.
  92575. */
  92576. aFcntl[0] = 0;
  92577. aFcntl[1] = zLeft;
  92578. aFcntl[2] = zRight;
  92579. aFcntl[3] = 0;
  92580. db->busyHandler.nBusy = 0;
  92581. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  92582. if( rc==SQLITE_OK ){
  92583. if( aFcntl[0] ){
  92584. int mem = ++pParse->nMem;
  92585. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  92586. sqlite3VdbeSetNumCols(v, 1);
  92587. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  92588. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  92589. sqlite3_free(aFcntl[0]);
  92590. }
  92591. goto pragma_out;
  92592. }
  92593. if( rc!=SQLITE_NOTFOUND ){
  92594. if( aFcntl[0] ){
  92595. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  92596. sqlite3_free(aFcntl[0]);
  92597. }
  92598. pParse->nErr++;
  92599. pParse->rc = rc;
  92600. goto pragma_out;
  92601. }
  92602. /* Locate the pragma in the lookup table */
  92603. lwr = 0;
  92604. upr = ArraySize(aPragmaNames)-1;
  92605. while( lwr<=upr ){
  92606. mid = (lwr+upr)/2;
  92607. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  92608. if( rc==0 ) break;
  92609. if( rc<0 ){
  92610. upr = mid - 1;
  92611. }else{
  92612. lwr = mid + 1;
  92613. }
  92614. }
  92615. if( lwr>upr ) goto pragma_out;
  92616. /* Make sure the database schema is loaded if the pragma requires that */
  92617. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  92618. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  92619. }
  92620. /* Jump to the appropriate pragma handler */
  92621. switch( aPragmaNames[mid].ePragTyp ){
  92622. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  92623. /*
  92624. ** PRAGMA [database.]default_cache_size
  92625. ** PRAGMA [database.]default_cache_size=N
  92626. **
  92627. ** The first form reports the current persistent setting for the
  92628. ** page cache size. The value returned is the maximum number of
  92629. ** pages in the page cache. The second form sets both the current
  92630. ** page cache size value and the persistent page cache size value
  92631. ** stored in the database file.
  92632. **
  92633. ** Older versions of SQLite would set the default cache size to a
  92634. ** negative number to indicate synchronous=OFF. These days, synchronous
  92635. ** is always on by default regardless of the sign of the default cache
  92636. ** size. But continue to take the absolute value of the default cache
  92637. ** size of historical compatibility.
  92638. */
  92639. case PragTyp_DEFAULT_CACHE_SIZE: {
  92640. static const VdbeOpList getCacheSize[] = {
  92641. { OP_Transaction, 0, 0, 0}, /* 0 */
  92642. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  92643. { OP_IfPos, 1, 8, 0},
  92644. { OP_Integer, 0, 2, 0},
  92645. { OP_Subtract, 1, 2, 1},
  92646. { OP_IfPos, 1, 8, 0},
  92647. { OP_Integer, 0, 1, 0}, /* 6 */
  92648. { OP_Noop, 0, 0, 0},
  92649. { OP_ResultRow, 1, 1, 0},
  92650. };
  92651. int addr;
  92652. sqlite3VdbeUsesBtree(v, iDb);
  92653. if( !zRight ){
  92654. sqlite3VdbeSetNumCols(v, 1);
  92655. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  92656. pParse->nMem += 2;
  92657. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  92658. sqlite3VdbeChangeP1(v, addr, iDb);
  92659. sqlite3VdbeChangeP1(v, addr+1, iDb);
  92660. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  92661. }else{
  92662. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  92663. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92664. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  92665. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  92666. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92667. pDb->pSchema->cache_size = size;
  92668. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  92669. }
  92670. break;
  92671. }
  92672. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  92673. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92674. /*
  92675. ** PRAGMA [database.]page_size
  92676. ** PRAGMA [database.]page_size=N
  92677. **
  92678. ** The first form reports the current setting for the
  92679. ** database page size in bytes. The second form sets the
  92680. ** database page size value. The value can only be set if
  92681. ** the database has not yet been created.
  92682. */
  92683. case PragTyp_PAGE_SIZE: {
  92684. Btree *pBt = pDb->pBt;
  92685. assert( pBt!=0 );
  92686. if( !zRight ){
  92687. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  92688. returnSingleInt(pParse, "page_size", size);
  92689. }else{
  92690. /* Malloc may fail when setting the page-size, as there is an internal
  92691. ** buffer that the pager module resizes using sqlite3_realloc().
  92692. */
  92693. db->nextPagesize = sqlite3Atoi(zRight);
  92694. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  92695. db->mallocFailed = 1;
  92696. }
  92697. }
  92698. break;
  92699. }
  92700. /*
  92701. ** PRAGMA [database.]secure_delete
  92702. ** PRAGMA [database.]secure_delete=ON/OFF
  92703. **
  92704. ** The first form reports the current setting for the
  92705. ** secure_delete flag. The second form changes the secure_delete
  92706. ** flag setting and reports thenew value.
  92707. */
  92708. case PragTyp_SECURE_DELETE: {
  92709. Btree *pBt = pDb->pBt;
  92710. int b = -1;
  92711. assert( pBt!=0 );
  92712. if( zRight ){
  92713. b = sqlite3GetBoolean(zRight, 0);
  92714. }
  92715. if( pId2->n==0 && b>=0 ){
  92716. int ii;
  92717. for(ii=0; ii<db->nDb; ii++){
  92718. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  92719. }
  92720. }
  92721. b = sqlite3BtreeSecureDelete(pBt, b);
  92722. returnSingleInt(pParse, "secure_delete", b);
  92723. break;
  92724. }
  92725. /*
  92726. ** PRAGMA [database.]max_page_count
  92727. ** PRAGMA [database.]max_page_count=N
  92728. **
  92729. ** The first form reports the current setting for the
  92730. ** maximum number of pages in the database file. The
  92731. ** second form attempts to change this setting. Both
  92732. ** forms return the current setting.
  92733. **
  92734. ** The absolute value of N is used. This is undocumented and might
  92735. ** change. The only purpose is to provide an easy way to test
  92736. ** the sqlite3AbsInt32() function.
  92737. **
  92738. ** PRAGMA [database.]page_count
  92739. **
  92740. ** Return the number of pages in the specified database.
  92741. */
  92742. case PragTyp_PAGE_COUNT: {
  92743. int iReg;
  92744. sqlite3CodeVerifySchema(pParse, iDb);
  92745. iReg = ++pParse->nMem;
  92746. if( sqlite3Tolower(zLeft[0])=='p' ){
  92747. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  92748. }else{
  92749. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  92750. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  92751. }
  92752. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  92753. sqlite3VdbeSetNumCols(v, 1);
  92754. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  92755. break;
  92756. }
  92757. /*
  92758. ** PRAGMA [database.]locking_mode
  92759. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  92760. */
  92761. case PragTyp_LOCKING_MODE: {
  92762. const char *zRet = "normal";
  92763. int eMode = getLockingMode(zRight);
  92764. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  92765. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  92766. ** the current default locking mode (which may be different to
  92767. ** the locking-mode of the main database).
  92768. */
  92769. eMode = db->dfltLockMode;
  92770. }else{
  92771. Pager *pPager;
  92772. if( pId2->n==0 ){
  92773. /* This indicates that no database name was specified as part
  92774. ** of the PRAGMA command. In this case the locking-mode must be
  92775. ** set on all attached databases, as well as the main db file.
  92776. **
  92777. ** Also, the sqlite3.dfltLockMode variable is set so that
  92778. ** any subsequently attached databases also use the specified
  92779. ** locking mode.
  92780. */
  92781. int ii;
  92782. assert(pDb==&db->aDb[0]);
  92783. for(ii=2; ii<db->nDb; ii++){
  92784. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  92785. sqlite3PagerLockingMode(pPager, eMode);
  92786. }
  92787. db->dfltLockMode = (u8)eMode;
  92788. }
  92789. pPager = sqlite3BtreePager(pDb->pBt);
  92790. eMode = sqlite3PagerLockingMode(pPager, eMode);
  92791. }
  92792. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  92793. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  92794. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  92795. zRet = "exclusive";
  92796. }
  92797. sqlite3VdbeSetNumCols(v, 1);
  92798. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  92799. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  92800. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  92801. break;
  92802. }
  92803. /*
  92804. ** PRAGMA [database.]journal_mode
  92805. ** PRAGMA [database.]journal_mode =
  92806. ** (delete|persist|off|truncate|memory|wal|off)
  92807. */
  92808. case PragTyp_JOURNAL_MODE: {
  92809. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  92810. int ii; /* Loop counter */
  92811. sqlite3VdbeSetNumCols(v, 1);
  92812. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  92813. if( zRight==0 ){
  92814. /* If there is no "=MODE" part of the pragma, do a query for the
  92815. ** current mode */
  92816. eMode = PAGER_JOURNALMODE_QUERY;
  92817. }else{
  92818. const char *zMode;
  92819. int n = sqlite3Strlen30(zRight);
  92820. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  92821. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  92822. }
  92823. if( !zMode ){
  92824. /* If the "=MODE" part does not match any known journal mode,
  92825. ** then do a query */
  92826. eMode = PAGER_JOURNALMODE_QUERY;
  92827. }
  92828. }
  92829. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  92830. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  92831. iDb = 0;
  92832. pId2->n = 1;
  92833. }
  92834. for(ii=db->nDb-1; ii>=0; ii--){
  92835. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  92836. sqlite3VdbeUsesBtree(v, ii);
  92837. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  92838. }
  92839. }
  92840. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  92841. break;
  92842. }
  92843. /*
  92844. ** PRAGMA [database.]journal_size_limit
  92845. ** PRAGMA [database.]journal_size_limit=N
  92846. **
  92847. ** Get or set the size limit on rollback journal files.
  92848. */
  92849. case PragTyp_JOURNAL_SIZE_LIMIT: {
  92850. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  92851. i64 iLimit = -2;
  92852. if( zRight ){
  92853. sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
  92854. if( iLimit<-1 ) iLimit = -1;
  92855. }
  92856. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  92857. returnSingleInt(pParse, "journal_size_limit", iLimit);
  92858. break;
  92859. }
  92860. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  92861. /*
  92862. ** PRAGMA [database.]auto_vacuum
  92863. ** PRAGMA [database.]auto_vacuum=N
  92864. **
  92865. ** Get or set the value of the database 'auto-vacuum' parameter.
  92866. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  92867. */
  92868. #ifndef SQLITE_OMIT_AUTOVACUUM
  92869. case PragTyp_AUTO_VACUUM: {
  92870. Btree *pBt = pDb->pBt;
  92871. assert( pBt!=0 );
  92872. if( !zRight ){
  92873. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  92874. }else{
  92875. int eAuto = getAutoVacuum(zRight);
  92876. assert( eAuto>=0 && eAuto<=2 );
  92877. db->nextAutovac = (u8)eAuto;
  92878. /* Call SetAutoVacuum() to set initialize the internal auto and
  92879. ** incr-vacuum flags. This is required in case this connection
  92880. ** creates the database file. It is important that it is created
  92881. ** as an auto-vacuum capable db.
  92882. */
  92883. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  92884. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  92885. /* When setting the auto_vacuum mode to either "full" or
  92886. ** "incremental", write the value of meta[6] in the database
  92887. ** file. Before writing to meta[6], check that meta[3] indicates
  92888. ** that this really is an auto-vacuum capable database.
  92889. */
  92890. static const VdbeOpList setMeta6[] = {
  92891. { OP_Transaction, 0, 1, 0}, /* 0 */
  92892. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  92893. { OP_If, 1, 0, 0}, /* 2 */
  92894. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  92895. { OP_Integer, 0, 1, 0}, /* 4 */
  92896. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  92897. };
  92898. int iAddr;
  92899. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  92900. sqlite3VdbeChangeP1(v, iAddr, iDb);
  92901. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  92902. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  92903. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  92904. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  92905. sqlite3VdbeUsesBtree(v, iDb);
  92906. }
  92907. }
  92908. break;
  92909. }
  92910. #endif
  92911. /*
  92912. ** PRAGMA [database.]incremental_vacuum(N)
  92913. **
  92914. ** Do N steps of incremental vacuuming on a database.
  92915. */
  92916. #ifndef SQLITE_OMIT_AUTOVACUUM
  92917. case PragTyp_INCREMENTAL_VACUUM: {
  92918. int iLimit, addr;
  92919. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  92920. iLimit = 0x7fffffff;
  92921. }
  92922. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92923. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  92924. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  92925. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  92926. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  92927. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  92928. sqlite3VdbeJumpHere(v, addr);
  92929. break;
  92930. }
  92931. #endif
  92932. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92933. /*
  92934. ** PRAGMA [database.]cache_size
  92935. ** PRAGMA [database.]cache_size=N
  92936. **
  92937. ** The first form reports the current local setting for the
  92938. ** page cache size. The second form sets the local
  92939. ** page cache size value. If N is positive then that is the
  92940. ** number of pages in the cache. If N is negative, then the
  92941. ** number of pages is adjusted so that the cache uses -N kibibytes
  92942. ** of memory.
  92943. */
  92944. case PragTyp_CACHE_SIZE: {
  92945. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92946. if( !zRight ){
  92947. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  92948. }else{
  92949. int size = sqlite3Atoi(zRight);
  92950. pDb->pSchema->cache_size = size;
  92951. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  92952. }
  92953. break;
  92954. }
  92955. /*
  92956. ** PRAGMA [database.]mmap_size(N)
  92957. **
  92958. ** Used to set mapping size limit. The mapping size limit is
  92959. ** used to limit the aggregate size of all memory mapped regions of the
  92960. ** database file. If this parameter is set to zero, then memory mapping
  92961. ** is not used at all. If N is negative, then the default memory map
  92962. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  92963. ** The parameter N is measured in bytes.
  92964. **
  92965. ** This value is advisory. The underlying VFS is free to memory map
  92966. ** as little or as much as it wants. Except, if N is set to 0 then the
  92967. ** upper layers will never invoke the xFetch interfaces to the VFS.
  92968. */
  92969. case PragTyp_MMAP_SIZE: {
  92970. sqlite3_int64 sz;
  92971. #if SQLITE_MAX_MMAP_SIZE>0
  92972. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92973. if( zRight ){
  92974. int ii;
  92975. sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
  92976. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  92977. if( pId2->n==0 ) db->szMmap = sz;
  92978. for(ii=db->nDb-1; ii>=0; ii--){
  92979. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  92980. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  92981. }
  92982. }
  92983. }
  92984. sz = -1;
  92985. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  92986. #else
  92987. sz = 0;
  92988. rc = SQLITE_OK;
  92989. #endif
  92990. if( rc==SQLITE_OK ){
  92991. returnSingleInt(pParse, "mmap_size", sz);
  92992. }else if( rc!=SQLITE_NOTFOUND ){
  92993. pParse->nErr++;
  92994. pParse->rc = rc;
  92995. }
  92996. break;
  92997. }
  92998. /*
  92999. ** PRAGMA temp_store
  93000. ** PRAGMA temp_store = "default"|"memory"|"file"
  93001. **
  93002. ** Return or set the local value of the temp_store flag. Changing
  93003. ** the local value does not make changes to the disk file and the default
  93004. ** value will be restored the next time the database is opened.
  93005. **
  93006. ** Note that it is possible for the library compile-time options to
  93007. ** override this setting
  93008. */
  93009. case PragTyp_TEMP_STORE: {
  93010. if( !zRight ){
  93011. returnSingleInt(pParse, "temp_store", db->temp_store);
  93012. }else{
  93013. changeTempStorage(pParse, zRight);
  93014. }
  93015. break;
  93016. }
  93017. /*
  93018. ** PRAGMA temp_store_directory
  93019. ** PRAGMA temp_store_directory = ""|"directory_name"
  93020. **
  93021. ** Return or set the local value of the temp_store_directory flag. Changing
  93022. ** the value sets a specific directory to be used for temporary files.
  93023. ** Setting to a null string reverts to the default temporary directory search.
  93024. ** If temporary directory is changed, then invalidateTempStorage.
  93025. **
  93026. */
  93027. case PragTyp_TEMP_STORE_DIRECTORY: {
  93028. if( !zRight ){
  93029. if( sqlite3_temp_directory ){
  93030. sqlite3VdbeSetNumCols(v, 1);
  93031. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93032. "temp_store_directory", SQLITE_STATIC);
  93033. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  93034. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93035. }
  93036. }else{
  93037. #ifndef SQLITE_OMIT_WSD
  93038. if( zRight[0] ){
  93039. int res;
  93040. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  93041. if( rc!=SQLITE_OK || res==0 ){
  93042. sqlite3ErrorMsg(pParse, "not a writable directory");
  93043. goto pragma_out;
  93044. }
  93045. }
  93046. if( SQLITE_TEMP_STORE==0
  93047. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  93048. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  93049. ){
  93050. invalidateTempStorage(pParse);
  93051. }
  93052. sqlite3_free(sqlite3_temp_directory);
  93053. if( zRight[0] ){
  93054. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  93055. }else{
  93056. sqlite3_temp_directory = 0;
  93057. }
  93058. #endif /* SQLITE_OMIT_WSD */
  93059. }
  93060. break;
  93061. }
  93062. #if SQLITE_OS_WIN
  93063. /*
  93064. ** PRAGMA data_store_directory
  93065. ** PRAGMA data_store_directory = ""|"directory_name"
  93066. **
  93067. ** Return or set the local value of the data_store_directory flag. Changing
  93068. ** the value sets a specific directory to be used for database files that
  93069. ** were specified with a relative pathname. Setting to a null string reverts
  93070. ** to the default database directory, which for database files specified with
  93071. ** a relative path will probably be based on the current directory for the
  93072. ** process. Database file specified with an absolute path are not impacted
  93073. ** by this setting, regardless of its value.
  93074. **
  93075. */
  93076. case PragTyp_DATA_STORE_DIRECTORY: {
  93077. if( !zRight ){
  93078. if( sqlite3_data_directory ){
  93079. sqlite3VdbeSetNumCols(v, 1);
  93080. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93081. "data_store_directory", SQLITE_STATIC);
  93082. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  93083. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93084. }
  93085. }else{
  93086. #ifndef SQLITE_OMIT_WSD
  93087. if( zRight[0] ){
  93088. int res;
  93089. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  93090. if( rc!=SQLITE_OK || res==0 ){
  93091. sqlite3ErrorMsg(pParse, "not a writable directory");
  93092. goto pragma_out;
  93093. }
  93094. }
  93095. sqlite3_free(sqlite3_data_directory);
  93096. if( zRight[0] ){
  93097. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  93098. }else{
  93099. sqlite3_data_directory = 0;
  93100. }
  93101. #endif /* SQLITE_OMIT_WSD */
  93102. }
  93103. break;
  93104. }
  93105. #endif
  93106. #if SQLITE_ENABLE_LOCKING_STYLE
  93107. /*
  93108. ** PRAGMA [database.]lock_proxy_file
  93109. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  93110. **
  93111. ** Return or set the value of the lock_proxy_file flag. Changing
  93112. ** the value sets a specific file to be used for database access locks.
  93113. **
  93114. */
  93115. case PragTyp_LOCK_PROXY_FILE: {
  93116. if( !zRight ){
  93117. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  93118. char *proxy_file_path = NULL;
  93119. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  93120. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  93121. &proxy_file_path);
  93122. if( proxy_file_path ){
  93123. sqlite3VdbeSetNumCols(v, 1);
  93124. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93125. "lock_proxy_file", SQLITE_STATIC);
  93126. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  93127. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93128. }
  93129. }else{
  93130. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  93131. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  93132. int res;
  93133. if( zRight[0] ){
  93134. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  93135. zRight);
  93136. } else {
  93137. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  93138. NULL);
  93139. }
  93140. if( res!=SQLITE_OK ){
  93141. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  93142. goto pragma_out;
  93143. }
  93144. }
  93145. break;
  93146. }
  93147. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  93148. /*
  93149. ** PRAGMA [database.]synchronous
  93150. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  93151. **
  93152. ** Return or set the local value of the synchronous flag. Changing
  93153. ** the local value does not make changes to the disk file and the
  93154. ** default value will be restored the next time the database is
  93155. ** opened.
  93156. */
  93157. case PragTyp_SYNCHRONOUS: {
  93158. if( !zRight ){
  93159. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  93160. }else{
  93161. if( !db->autoCommit ){
  93162. sqlite3ErrorMsg(pParse,
  93163. "Safety level may not be changed inside a transaction");
  93164. }else{
  93165. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  93166. setAllPagerFlags(db);
  93167. }
  93168. }
  93169. break;
  93170. }
  93171. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  93172. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  93173. case PragTyp_FLAG: {
  93174. if( zRight==0 ){
  93175. returnSingleInt(pParse, aPragmaNames[mid].zName,
  93176. (db->flags & aPragmaNames[mid].iArg)!=0 );
  93177. }else{
  93178. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  93179. if( db->autoCommit==0 ){
  93180. /* Foreign key support may not be enabled or disabled while not
  93181. ** in auto-commit mode. */
  93182. mask &= ~(SQLITE_ForeignKeys);
  93183. }
  93184. if( sqlite3GetBoolean(zRight, 0) ){
  93185. db->flags |= mask;
  93186. }else{
  93187. db->flags &= ~mask;
  93188. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  93189. }
  93190. /* Many of the flag-pragmas modify the code generated by the SQL
  93191. ** compiler (eg. count_changes). So add an opcode to expire all
  93192. ** compiled SQL statements after modifying a pragma value.
  93193. */
  93194. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  93195. setAllPagerFlags(db);
  93196. }
  93197. break;
  93198. }
  93199. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  93200. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  93201. /*
  93202. ** PRAGMA table_info(<table>)
  93203. **
  93204. ** Return a single row for each column of the named table. The columns of
  93205. ** the returned data set are:
  93206. **
  93207. ** cid: Column id (numbered from left to right, starting at 0)
  93208. ** name: Column name
  93209. ** type: Column declaration type.
  93210. ** notnull: True if 'NOT NULL' is part of column declaration
  93211. ** dflt_value: The default value for the column, if any.
  93212. */
  93213. case PragTyp_TABLE_INFO: if( zRight ){
  93214. Table *pTab;
  93215. pTab = sqlite3FindTable(db, zRight, zDb);
  93216. if( pTab ){
  93217. int i, k;
  93218. int nHidden = 0;
  93219. Column *pCol;
  93220. Index *pPk;
  93221. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  93222. sqlite3VdbeSetNumCols(v, 6);
  93223. pParse->nMem = 6;
  93224. sqlite3CodeVerifySchema(pParse, iDb);
  93225. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  93226. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93227. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  93228. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  93229. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  93230. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  93231. sqlite3ViewGetColumnNames(pParse, pTab);
  93232. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  93233. if( IsHiddenColumn(pCol) ){
  93234. nHidden++;
  93235. continue;
  93236. }
  93237. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  93238. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  93239. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93240. pCol->zType ? pCol->zType : "", 0);
  93241. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  93242. if( pCol->zDflt ){
  93243. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  93244. }else{
  93245. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  93246. }
  93247. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  93248. k = 0;
  93249. }else if( pPk==0 ){
  93250. k = 1;
  93251. }else{
  93252. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  93253. }
  93254. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  93255. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  93256. }
  93257. }
  93258. }
  93259. break;
  93260. case PragTyp_STATS: {
  93261. Index *pIdx;
  93262. HashElem *i;
  93263. v = sqlite3GetVdbe(pParse);
  93264. sqlite3VdbeSetNumCols(v, 4);
  93265. pParse->nMem = 4;
  93266. sqlite3CodeVerifySchema(pParse, iDb);
  93267. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  93268. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  93269. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  93270. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  93271. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  93272. Table *pTab = sqliteHashData(i);
  93273. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  93274. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  93275. sqlite3VdbeAddOp2(v, OP_Integer,
  93276. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  93277. sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
  93278. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  93279. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93280. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  93281. sqlite3VdbeAddOp2(v, OP_Integer,
  93282. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  93283. sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
  93284. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  93285. }
  93286. }
  93287. }
  93288. break;
  93289. case PragTyp_INDEX_INFO: if( zRight ){
  93290. Index *pIdx;
  93291. Table *pTab;
  93292. pIdx = sqlite3FindIndex(db, zRight, zDb);
  93293. if( pIdx ){
  93294. int i;
  93295. pTab = pIdx->pTable;
  93296. sqlite3VdbeSetNumCols(v, 3);
  93297. pParse->nMem = 3;
  93298. sqlite3CodeVerifySchema(pParse, iDb);
  93299. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  93300. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  93301. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  93302. for(i=0; i<pIdx->nColumn; i++){
  93303. int cnum = pIdx->aiColumn[i];
  93304. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93305. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  93306. assert( pTab->nCol>cnum );
  93307. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  93308. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93309. }
  93310. }
  93311. }
  93312. break;
  93313. case PragTyp_INDEX_LIST: if( zRight ){
  93314. Index *pIdx;
  93315. Table *pTab;
  93316. int i;
  93317. pTab = sqlite3FindTable(db, zRight, zDb);
  93318. if( pTab ){
  93319. v = sqlite3GetVdbe(pParse);
  93320. sqlite3VdbeSetNumCols(v, 3);
  93321. pParse->nMem = 3;
  93322. sqlite3CodeVerifySchema(pParse, iDb);
  93323. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93324. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93325. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  93326. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  93327. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93328. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  93329. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  93330. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93331. }
  93332. }
  93333. }
  93334. break;
  93335. case PragTyp_DATABASE_LIST: {
  93336. int i;
  93337. sqlite3VdbeSetNumCols(v, 3);
  93338. pParse->nMem = 3;
  93339. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93340. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93341. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  93342. for(i=0; i<db->nDb; i++){
  93343. if( db->aDb[i].pBt==0 ) continue;
  93344. assert( db->aDb[i].zName!=0 );
  93345. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93346. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  93347. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93348. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  93349. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93350. }
  93351. }
  93352. break;
  93353. case PragTyp_COLLATION_LIST: {
  93354. int i = 0;
  93355. HashElem *p;
  93356. sqlite3VdbeSetNumCols(v, 2);
  93357. pParse->nMem = 2;
  93358. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93359. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93360. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  93361. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  93362. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  93363. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  93364. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  93365. }
  93366. }
  93367. break;
  93368. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  93369. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93370. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  93371. FKey *pFK;
  93372. Table *pTab;
  93373. pTab = sqlite3FindTable(db, zRight, zDb);
  93374. if( pTab ){
  93375. v = sqlite3GetVdbe(pParse);
  93376. pFK = pTab->pFKey;
  93377. if( pFK ){
  93378. int i = 0;
  93379. sqlite3VdbeSetNumCols(v, 8);
  93380. pParse->nMem = 8;
  93381. sqlite3CodeVerifySchema(pParse, iDb);
  93382. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  93383. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  93384. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  93385. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  93386. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  93387. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  93388. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  93389. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  93390. while(pFK){
  93391. int j;
  93392. for(j=0; j<pFK->nCol; j++){
  93393. char *zCol = pFK->aCol[j].zCol;
  93394. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  93395. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  93396. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93397. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  93398. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  93399. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  93400. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  93401. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  93402. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  93403. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  93404. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  93405. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  93406. }
  93407. ++i;
  93408. pFK = pFK->pNextFrom;
  93409. }
  93410. }
  93411. }
  93412. }
  93413. break;
  93414. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  93415. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93416. #ifndef SQLITE_OMIT_TRIGGER
  93417. case PragTyp_FOREIGN_KEY_CHECK: {
  93418. FKey *pFK; /* A foreign key constraint */
  93419. Table *pTab; /* Child table contain "REFERENCES" keyword */
  93420. Table *pParent; /* Parent table that child points to */
  93421. Index *pIdx; /* Index in the parent table */
  93422. int i; /* Loop counter: Foreign key number for pTab */
  93423. int j; /* Loop counter: Field of the foreign key */
  93424. HashElem *k; /* Loop counter: Next table in schema */
  93425. int x; /* result variable */
  93426. int regResult; /* 3 registers to hold a result row */
  93427. int regKey; /* Register to hold key for checking the FK */
  93428. int regRow; /* Registers to hold a row from pTab */
  93429. int addrTop; /* Top of a loop checking foreign keys */
  93430. int addrOk; /* Jump here if the key is OK */
  93431. int *aiCols; /* child to parent column mapping */
  93432. regResult = pParse->nMem+1;
  93433. pParse->nMem += 4;
  93434. regKey = ++pParse->nMem;
  93435. regRow = ++pParse->nMem;
  93436. v = sqlite3GetVdbe(pParse);
  93437. sqlite3VdbeSetNumCols(v, 4);
  93438. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  93439. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  93440. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  93441. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  93442. sqlite3CodeVerifySchema(pParse, iDb);
  93443. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  93444. while( k ){
  93445. if( zRight ){
  93446. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  93447. k = 0;
  93448. }else{
  93449. pTab = (Table*)sqliteHashData(k);
  93450. k = sqliteHashNext(k);
  93451. }
  93452. if( pTab==0 || pTab->pFKey==0 ) continue;
  93453. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  93454. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  93455. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  93456. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  93457. P4_TRANSIENT);
  93458. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  93459. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  93460. if( pParent==0 ) continue;
  93461. pIdx = 0;
  93462. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  93463. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  93464. if( x==0 ){
  93465. if( pIdx==0 ){
  93466. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  93467. }else{
  93468. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  93469. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  93470. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  93471. }
  93472. }else{
  93473. k = 0;
  93474. break;
  93475. }
  93476. }
  93477. assert( pParse->nErr>0 || pFK==0 );
  93478. if( pFK ) break;
  93479. if( pParse->nTab<i ) pParse->nTab = i;
  93480. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  93481. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  93482. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  93483. pIdx = 0;
  93484. aiCols = 0;
  93485. if( pParent ){
  93486. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  93487. assert( x==0 );
  93488. }
  93489. addrOk = sqlite3VdbeMakeLabel(v);
  93490. if( pParent && pIdx==0 ){
  93491. int iKey = pFK->aCol[0].iFrom;
  93492. assert( iKey>=0 && iKey<pTab->nCol );
  93493. if( iKey!=pTab->iPKey ){
  93494. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  93495. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  93496. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  93497. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  93498. sqlite3VdbeCurrentAddr(v)+3);
  93499. }else{
  93500. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  93501. }
  93502. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  93503. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  93504. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  93505. }else{
  93506. for(j=0; j<pFK->nCol; j++){
  93507. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  93508. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  93509. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  93510. }
  93511. if( pParent ){
  93512. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  93513. sqlite3VdbeChangeP4(v, -1,
  93514. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  93515. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  93516. }
  93517. }
  93518. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  93519. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  93520. pFK->zTo, P4_TRANSIENT);
  93521. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  93522. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  93523. sqlite3VdbeResolveLabel(v, addrOk);
  93524. sqlite3DbFree(db, aiCols);
  93525. }
  93526. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  93527. sqlite3VdbeJumpHere(v, addrTop);
  93528. }
  93529. }
  93530. break;
  93531. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  93532. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  93533. #ifndef NDEBUG
  93534. case PragTyp_PARSER_TRACE: {
  93535. if( zRight ){
  93536. if( sqlite3GetBoolean(zRight, 0) ){
  93537. sqlite3ParserTrace(stderr, "parser: ");
  93538. }else{
  93539. sqlite3ParserTrace(0, 0);
  93540. }
  93541. }
  93542. }
  93543. break;
  93544. #endif
  93545. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  93546. ** used will be case sensitive or not depending on the RHS.
  93547. */
  93548. case PragTyp_CASE_SENSITIVE_LIKE: {
  93549. if( zRight ){
  93550. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  93551. }
  93552. }
  93553. break;
  93554. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  93555. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  93556. #endif
  93557. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  93558. /* Pragma "quick_check" is reduced version of
  93559. ** integrity_check designed to detect most database corruption
  93560. ** without most of the overhead of a full integrity-check.
  93561. */
  93562. case PragTyp_INTEGRITY_CHECK: {
  93563. int i, j, addr, mxErr;
  93564. /* Code that appears at the end of the integrity check. If no error
  93565. ** messages have been generated, output OK. Otherwise output the
  93566. ** error message
  93567. */
  93568. static const VdbeOpList endCode[] = {
  93569. { OP_AddImm, 1, 0, 0}, /* 0 */
  93570. { OP_IfNeg, 1, 0, 0}, /* 1 */
  93571. { OP_String8, 0, 3, 0}, /* 2 */
  93572. { OP_ResultRow, 3, 1, 0},
  93573. };
  93574. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  93575. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  93576. ** then iDb is set to the index of the database identified by <db>.
  93577. ** In this case, the integrity of database iDb only is verified by
  93578. ** the VDBE created below.
  93579. **
  93580. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  93581. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  93582. ** to -1 here, to indicate that the VDBE should verify the integrity
  93583. ** of all attached databases. */
  93584. assert( iDb>=0 );
  93585. assert( iDb==0 || pId2->z );
  93586. if( pId2->z==0 ) iDb = -1;
  93587. /* Initialize the VDBE program */
  93588. pParse->nMem = 6;
  93589. sqlite3VdbeSetNumCols(v, 1);
  93590. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  93591. /* Set the maximum error count */
  93592. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  93593. if( zRight ){
  93594. sqlite3GetInt32(zRight, &mxErr);
  93595. if( mxErr<=0 ){
  93596. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  93597. }
  93598. }
  93599. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  93600. /* Do an integrity check on each database file */
  93601. for(i=0; i<db->nDb; i++){
  93602. HashElem *x;
  93603. Hash *pTbls;
  93604. int cnt = 0;
  93605. if( OMIT_TEMPDB && i==1 ) continue;
  93606. if( iDb>=0 && i!=iDb ) continue;
  93607. sqlite3CodeVerifySchema(pParse, i);
  93608. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  93609. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93610. sqlite3VdbeJumpHere(v, addr);
  93611. /* Do an integrity check of the B-Tree
  93612. **
  93613. ** Begin by filling registers 2, 3, ... with the root pages numbers
  93614. ** for all tables and indices in the database.
  93615. */
  93616. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  93617. pTbls = &db->aDb[i].pSchema->tblHash;
  93618. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  93619. Table *pTab = sqliteHashData(x);
  93620. Index *pIdx;
  93621. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  93622. cnt++;
  93623. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93624. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  93625. cnt++;
  93626. }
  93627. }
  93628. /* Make sure sufficient number of registers have been allocated */
  93629. pParse->nMem = MAX( pParse->nMem, cnt+7 );
  93630. /* Do the b-tree integrity checks */
  93631. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  93632. sqlite3VdbeChangeP5(v, (u8)i);
  93633. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  93634. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93635. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  93636. P4_DYNAMIC);
  93637. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  93638. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  93639. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  93640. sqlite3VdbeJumpHere(v, addr);
  93641. /* Make sure all the indices are constructed correctly.
  93642. */
  93643. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  93644. Table *pTab = sqliteHashData(x);
  93645. Index *pIdx;
  93646. int loopTop;
  93647. if( pTab->pIndex==0 ) continue;
  93648. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  93649. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93650. sqlite3VdbeJumpHere(v, addr);
  93651. sqlite3ExprCacheClear(pParse);
  93652. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  93653. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93654. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
  93655. }
  93656. pParse->nMem = MAX(pParse->nMem, 7+j);
  93657. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  93658. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93659. int jmp2, jmp3;
  93660. int r1;
  93661. static const VdbeOpList idxErr[] = {
  93662. { OP_AddImm, 1, -1, 0},
  93663. { OP_String8, 0, 3, 0}, /* 1 */
  93664. { OP_Rowid, 1, 4, 0},
  93665. { OP_String8, 0, 5, 0}, /* 3 */
  93666. { OP_String8, 0, 6, 0}, /* 4 */
  93667. { OP_Concat, 4, 3, 3},
  93668. { OP_Concat, 5, 3, 3},
  93669. { OP_Concat, 6, 3, 3},
  93670. { OP_ResultRow, 3, 1, 0},
  93671. { OP_IfPos, 1, 0, 0}, /* 9 */
  93672. { OP_Halt, 0, 0, 0},
  93673. };
  93674. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
  93675. sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
  93676. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  93677. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  93678. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  93679. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  93680. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  93681. sqlite3VdbeJumpHere(v, addr+9);
  93682. sqlite3VdbeJumpHere(v, jmp2);
  93683. sqlite3VdbeResolveLabel(v, jmp3);
  93684. }
  93685. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
  93686. sqlite3VdbeJumpHere(v, loopTop-1);
  93687. #ifndef SQLITE_OMIT_BTREECOUNT
  93688. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  93689. "wrong # of entries in index ", P4_STATIC);
  93690. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93691. addr = sqlite3VdbeCurrentAddr(v);
  93692. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  93693. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93694. sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
  93695. sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
  93696. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  93697. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  93698. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  93699. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  93700. }
  93701. #endif /* SQLITE_OMIT_BTREECOUNT */
  93702. }
  93703. }
  93704. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  93705. sqlite3VdbeChangeP2(v, addr, -mxErr);
  93706. sqlite3VdbeJumpHere(v, addr+1);
  93707. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  93708. }
  93709. break;
  93710. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  93711. #ifndef SQLITE_OMIT_UTF16
  93712. /*
  93713. ** PRAGMA encoding
  93714. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  93715. **
  93716. ** In its first form, this pragma returns the encoding of the main
  93717. ** database. If the database is not initialized, it is initialized now.
  93718. **
  93719. ** The second form of this pragma is a no-op if the main database file
  93720. ** has not already been initialized. In this case it sets the default
  93721. ** encoding that will be used for the main database file if a new file
  93722. ** is created. If an existing main database file is opened, then the
  93723. ** default text encoding for the existing database is used.
  93724. **
  93725. ** In all cases new databases created using the ATTACH command are
  93726. ** created to use the same default text encoding as the main database. If
  93727. ** the main database has not been initialized and/or created when ATTACH
  93728. ** is executed, this is done before the ATTACH operation.
  93729. **
  93730. ** In the second form this pragma sets the text encoding to be used in
  93731. ** new database files created using this database handle. It is only
  93732. ** useful if invoked immediately after the main database i
  93733. */
  93734. case PragTyp_ENCODING: {
  93735. static const struct EncName {
  93736. char *zName;
  93737. u8 enc;
  93738. } encnames[] = {
  93739. { "UTF8", SQLITE_UTF8 },
  93740. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  93741. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  93742. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  93743. { "UTF16le", SQLITE_UTF16LE },
  93744. { "UTF16be", SQLITE_UTF16BE },
  93745. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  93746. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  93747. { 0, 0 }
  93748. };
  93749. const struct EncName *pEnc;
  93750. if( !zRight ){ /* "PRAGMA encoding" */
  93751. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  93752. sqlite3VdbeSetNumCols(v, 1);
  93753. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  93754. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  93755. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  93756. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  93757. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  93758. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  93759. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93760. }else{ /* "PRAGMA encoding = XXX" */
  93761. /* Only change the value of sqlite.enc if the database handle is not
  93762. ** initialized. If the main database exists, the new sqlite.enc value
  93763. ** will be overwritten when the schema is next loaded. If it does not
  93764. ** already exists, it will be created to use the new encoding value.
  93765. */
  93766. if(
  93767. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  93768. DbHasProperty(db, 0, DB_Empty)
  93769. ){
  93770. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  93771. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  93772. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  93773. break;
  93774. }
  93775. }
  93776. if( !pEnc->zName ){
  93777. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  93778. }
  93779. }
  93780. }
  93781. }
  93782. break;
  93783. #endif /* SQLITE_OMIT_UTF16 */
  93784. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  93785. /*
  93786. ** PRAGMA [database.]schema_version
  93787. ** PRAGMA [database.]schema_version = <integer>
  93788. **
  93789. ** PRAGMA [database.]user_version
  93790. ** PRAGMA [database.]user_version = <integer>
  93791. **
  93792. ** PRAGMA [database.]freelist_count = <integer>
  93793. **
  93794. ** PRAGMA [database.]application_id
  93795. ** PRAGMA [database.]application_id = <integer>
  93796. **
  93797. ** The pragma's schema_version and user_version are used to set or get
  93798. ** the value of the schema-version and user-version, respectively. Both
  93799. ** the schema-version and the user-version are 32-bit signed integers
  93800. ** stored in the database header.
  93801. **
  93802. ** The schema-cookie is usually only manipulated internally by SQLite. It
  93803. ** is incremented by SQLite whenever the database schema is modified (by
  93804. ** creating or dropping a table or index). The schema version is used by
  93805. ** SQLite each time a query is executed to ensure that the internal cache
  93806. ** of the schema used when compiling the SQL query matches the schema of
  93807. ** the database against which the compiled query is actually executed.
  93808. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  93809. ** the schema-version is potentially dangerous and may lead to program
  93810. ** crashes or database corruption. Use with caution!
  93811. **
  93812. ** The user-version is not used internally by SQLite. It may be used by
  93813. ** applications for any purpose.
  93814. */
  93815. case PragTyp_HEADER_VALUE: {
  93816. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  93817. sqlite3VdbeUsesBtree(v, iDb);
  93818. switch( zLeft[0] ){
  93819. case 'a': case 'A':
  93820. iCookie = BTREE_APPLICATION_ID;
  93821. break;
  93822. case 'f': case 'F':
  93823. iCookie = BTREE_FREE_PAGE_COUNT;
  93824. break;
  93825. case 's': case 'S':
  93826. iCookie = BTREE_SCHEMA_VERSION;
  93827. break;
  93828. default:
  93829. iCookie = BTREE_USER_VERSION;
  93830. break;
  93831. }
  93832. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  93833. /* Write the specified cookie value */
  93834. static const VdbeOpList setCookie[] = {
  93835. { OP_Transaction, 0, 1, 0}, /* 0 */
  93836. { OP_Integer, 0, 1, 0}, /* 1 */
  93837. { OP_SetCookie, 0, 0, 1}, /* 2 */
  93838. };
  93839. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  93840. sqlite3VdbeChangeP1(v, addr, iDb);
  93841. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  93842. sqlite3VdbeChangeP1(v, addr+2, iDb);
  93843. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  93844. }else{
  93845. /* Read the specified cookie value */
  93846. static const VdbeOpList readCookie[] = {
  93847. { OP_Transaction, 0, 0, 0}, /* 0 */
  93848. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  93849. { OP_ResultRow, 1, 1, 0}
  93850. };
  93851. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  93852. sqlite3VdbeChangeP1(v, addr, iDb);
  93853. sqlite3VdbeChangeP1(v, addr+1, iDb);
  93854. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  93855. sqlite3VdbeSetNumCols(v, 1);
  93856. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  93857. }
  93858. }
  93859. break;
  93860. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  93861. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93862. /*
  93863. ** PRAGMA compile_options
  93864. **
  93865. ** Return the names of all compile-time options used in this build,
  93866. ** one option per row.
  93867. */
  93868. case PragTyp_COMPILE_OPTIONS: {
  93869. int i = 0;
  93870. const char *zOpt;
  93871. sqlite3VdbeSetNumCols(v, 1);
  93872. pParse->nMem = 1;
  93873. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  93874. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  93875. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  93876. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93877. }
  93878. }
  93879. break;
  93880. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  93881. #ifndef SQLITE_OMIT_WAL
  93882. /*
  93883. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  93884. **
  93885. ** Checkpoint the database.
  93886. */
  93887. case PragTyp_WAL_CHECKPOINT: {
  93888. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  93889. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  93890. if( zRight ){
  93891. if( sqlite3StrICmp(zRight, "full")==0 ){
  93892. eMode = SQLITE_CHECKPOINT_FULL;
  93893. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  93894. eMode = SQLITE_CHECKPOINT_RESTART;
  93895. }
  93896. }
  93897. sqlite3VdbeSetNumCols(v, 3);
  93898. pParse->nMem = 3;
  93899. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  93900. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  93901. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  93902. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  93903. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93904. }
  93905. break;
  93906. /*
  93907. ** PRAGMA wal_autocheckpoint
  93908. ** PRAGMA wal_autocheckpoint = N
  93909. **
  93910. ** Configure a database connection to automatically checkpoint a database
  93911. ** after accumulating N frames in the log. Or query for the current value
  93912. ** of N.
  93913. */
  93914. case PragTyp_WAL_AUTOCHECKPOINT: {
  93915. if( zRight ){
  93916. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  93917. }
  93918. returnSingleInt(pParse, "wal_autocheckpoint",
  93919. db->xWalCallback==sqlite3WalDefaultHook ?
  93920. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  93921. }
  93922. break;
  93923. #endif
  93924. /*
  93925. ** PRAGMA shrink_memory
  93926. **
  93927. ** This pragma attempts to free as much memory as possible from the
  93928. ** current database connection.
  93929. */
  93930. case PragTyp_SHRINK_MEMORY: {
  93931. sqlite3_db_release_memory(db);
  93932. break;
  93933. }
  93934. /*
  93935. ** PRAGMA busy_timeout
  93936. ** PRAGMA busy_timeout = N
  93937. **
  93938. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  93939. ** if one is set. If no busy handler or a different busy handler is set
  93940. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  93941. ** disables the timeout.
  93942. */
  93943. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  93944. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  93945. if( zRight ){
  93946. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  93947. }
  93948. returnSingleInt(pParse, "timeout", db->busyTimeout);
  93949. break;
  93950. }
  93951. /*
  93952. ** PRAGMA soft_heap_limit
  93953. ** PRAGMA soft_heap_limit = N
  93954. **
  93955. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  93956. ** use -1.
  93957. */
  93958. case PragTyp_SOFT_HEAP_LIMIT: {
  93959. sqlite3_int64 N;
  93960. if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
  93961. sqlite3_soft_heap_limit64(N);
  93962. }
  93963. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  93964. break;
  93965. }
  93966. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  93967. /*
  93968. ** Report the current state of file logs for all databases
  93969. */
  93970. case PragTyp_LOCK_STATUS: {
  93971. static const char *const azLockName[] = {
  93972. "unlocked", "shared", "reserved", "pending", "exclusive"
  93973. };
  93974. int i;
  93975. sqlite3VdbeSetNumCols(v, 2);
  93976. pParse->nMem = 2;
  93977. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  93978. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  93979. for(i=0; i<db->nDb; i++){
  93980. Btree *pBt;
  93981. const char *zState = "unknown";
  93982. int j;
  93983. if( db->aDb[i].zName==0 ) continue;
  93984. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  93985. pBt = db->aDb[i].pBt;
  93986. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  93987. zState = "closed";
  93988. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  93989. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  93990. zState = azLockName[j];
  93991. }
  93992. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  93993. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  93994. }
  93995. break;
  93996. }
  93997. #endif
  93998. #ifdef SQLITE_HAS_CODEC
  93999. case PragTyp_KEY: {
  94000. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  94001. break;
  94002. }
  94003. case PragTyp_REKEY: {
  94004. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  94005. break;
  94006. }
  94007. case PragTyp_HEXKEY: {
  94008. if( zRight ){
  94009. u8 iByte;
  94010. int i;
  94011. char zKey[40];
  94012. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  94013. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  94014. if( (i&1)!=0 ) zKey[i/2] = iByte;
  94015. }
  94016. if( (zLeft[3] & 0xf)==0xb ){
  94017. sqlite3_key_v2(db, zDb, zKey, i/2);
  94018. }else{
  94019. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  94020. }
  94021. }
  94022. break;
  94023. }
  94024. #endif
  94025. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  94026. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  94027. #ifdef SQLITE_HAS_CODEC
  94028. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  94029. sqlite3_activate_see(&zRight[4]);
  94030. }
  94031. #endif
  94032. #ifdef SQLITE_ENABLE_CEROD
  94033. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  94034. sqlite3_activate_cerod(&zRight[6]);
  94035. }
  94036. #endif
  94037. }
  94038. break;
  94039. #endif
  94040. } /* End of the PRAGMA switch */
  94041. pragma_out:
  94042. sqlite3DbFree(db, zLeft);
  94043. sqlite3DbFree(db, zRight);
  94044. }
  94045. #endif /* SQLITE_OMIT_PRAGMA */
  94046. /************** End of pragma.c **********************************************/
  94047. /************** Begin file prepare.c *****************************************/
  94048. /*
  94049. ** 2005 May 25
  94050. **
  94051. ** The author disclaims copyright to this source code. In place of
  94052. ** a legal notice, here is a blessing:
  94053. **
  94054. ** May you do good and not evil.
  94055. ** May you find forgiveness for yourself and forgive others.
  94056. ** May you share freely, never taking more than you give.
  94057. **
  94058. *************************************************************************
  94059. ** This file contains the implementation of the sqlite3_prepare()
  94060. ** interface, and routines that contribute to loading the database schema
  94061. ** from disk.
  94062. */
  94063. /*
  94064. ** Fill the InitData structure with an error message that indicates
  94065. ** that the database is corrupt.
  94066. */
  94067. static void corruptSchema(
  94068. InitData *pData, /* Initialization context */
  94069. const char *zObj, /* Object being parsed at the point of error */
  94070. const char *zExtra /* Error information */
  94071. ){
  94072. sqlite3 *db = pData->db;
  94073. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  94074. if( zObj==0 ) zObj = "?";
  94075. sqlite3SetString(pData->pzErrMsg, db,
  94076. "malformed database schema (%s)", zObj);
  94077. if( zExtra ){
  94078. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  94079. "%s - %s", *pData->pzErrMsg, zExtra);
  94080. }
  94081. }
  94082. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  94083. }
  94084. /*
  94085. ** This is the callback routine for the code that initializes the
  94086. ** database. See sqlite3Init() below for additional information.
  94087. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  94088. **
  94089. ** Each callback contains the following information:
  94090. **
  94091. ** argv[0] = name of thing being created
  94092. ** argv[1] = root page number for table or index. 0 for trigger or view.
  94093. ** argv[2] = SQL text for the CREATE statement.
  94094. **
  94095. */
  94096. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  94097. InitData *pData = (InitData*)pInit;
  94098. sqlite3 *db = pData->db;
  94099. int iDb = pData->iDb;
  94100. assert( argc==3 );
  94101. UNUSED_PARAMETER2(NotUsed, argc);
  94102. assert( sqlite3_mutex_held(db->mutex) );
  94103. DbClearProperty(db, iDb, DB_Empty);
  94104. if( db->mallocFailed ){
  94105. corruptSchema(pData, argv[0], 0);
  94106. return 1;
  94107. }
  94108. assert( iDb>=0 && iDb<db->nDb );
  94109. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  94110. if( argv[1]==0 ){
  94111. corruptSchema(pData, argv[0], 0);
  94112. }else if( argv[2] && argv[2][0] ){
  94113. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  94114. ** But because db->init.busy is set to 1, no VDBE code is generated
  94115. ** or executed. All the parser does is build the internal data
  94116. ** structures that describe the table, index, or view.
  94117. */
  94118. int rc;
  94119. sqlite3_stmt *pStmt;
  94120. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  94121. assert( db->init.busy );
  94122. db->init.iDb = iDb;
  94123. db->init.newTnum = sqlite3Atoi(argv[1]);
  94124. db->init.orphanTrigger = 0;
  94125. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  94126. rc = db->errCode;
  94127. assert( (rc&0xFF)==(rcp&0xFF) );
  94128. db->init.iDb = 0;
  94129. if( SQLITE_OK!=rc ){
  94130. if( db->init.orphanTrigger ){
  94131. assert( iDb==1 );
  94132. }else{
  94133. pData->rc = rc;
  94134. if( rc==SQLITE_NOMEM ){
  94135. db->mallocFailed = 1;
  94136. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  94137. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  94138. }
  94139. }
  94140. }
  94141. sqlite3_finalize(pStmt);
  94142. }else if( argv[0]==0 ){
  94143. corruptSchema(pData, 0, 0);
  94144. }else{
  94145. /* If the SQL column is blank it means this is an index that
  94146. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  94147. ** constraint for a CREATE TABLE. The index should have already
  94148. ** been created when we processed the CREATE TABLE. All we have
  94149. ** to do here is record the root page number for that index.
  94150. */
  94151. Index *pIndex;
  94152. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  94153. if( pIndex==0 ){
  94154. /* This can occur if there exists an index on a TEMP table which
  94155. ** has the same name as another index on a permanent index. Since
  94156. ** the permanent table is hidden by the TEMP table, we can also
  94157. ** safely ignore the index on the permanent table.
  94158. */
  94159. /* Do Nothing */;
  94160. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  94161. corruptSchema(pData, argv[0], "invalid rootpage");
  94162. }
  94163. }
  94164. return 0;
  94165. }
  94166. /*
  94167. ** Attempt to read the database schema and initialize internal
  94168. ** data structures for a single database file. The index of the
  94169. ** database file is given by iDb. iDb==0 is used for the main
  94170. ** database. iDb==1 should never be used. iDb>=2 is used for
  94171. ** auxiliary databases. Return one of the SQLITE_ error codes to
  94172. ** indicate success or failure.
  94173. */
  94174. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  94175. int rc;
  94176. int i;
  94177. #ifndef SQLITE_OMIT_DEPRECATED
  94178. int size;
  94179. #endif
  94180. Table *pTab;
  94181. Db *pDb;
  94182. char const *azArg[4];
  94183. int meta[5];
  94184. InitData initData;
  94185. char const *zMasterSchema;
  94186. char const *zMasterName;
  94187. int openedTransaction = 0;
  94188. /*
  94189. ** The master database table has a structure like this
  94190. */
  94191. static const char master_schema[] =
  94192. "CREATE TABLE sqlite_master(\n"
  94193. " type text,\n"
  94194. " name text,\n"
  94195. " tbl_name text,\n"
  94196. " rootpage integer,\n"
  94197. " sql text\n"
  94198. ")"
  94199. ;
  94200. #ifndef SQLITE_OMIT_TEMPDB
  94201. static const char temp_master_schema[] =
  94202. "CREATE TEMP TABLE sqlite_temp_master(\n"
  94203. " type text,\n"
  94204. " name text,\n"
  94205. " tbl_name text,\n"
  94206. " rootpage integer,\n"
  94207. " sql text\n"
  94208. ")"
  94209. ;
  94210. #else
  94211. #define temp_master_schema 0
  94212. #endif
  94213. assert( iDb>=0 && iDb<db->nDb );
  94214. assert( db->aDb[iDb].pSchema );
  94215. assert( sqlite3_mutex_held(db->mutex) );
  94216. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  94217. /* zMasterSchema and zInitScript are set to point at the master schema
  94218. ** and initialisation script appropriate for the database being
  94219. ** initialized. zMasterName is the name of the master table.
  94220. */
  94221. if( !OMIT_TEMPDB && iDb==1 ){
  94222. zMasterSchema = temp_master_schema;
  94223. }else{
  94224. zMasterSchema = master_schema;
  94225. }
  94226. zMasterName = SCHEMA_TABLE(iDb);
  94227. /* Construct the schema tables. */
  94228. azArg[0] = zMasterName;
  94229. azArg[1] = "1";
  94230. azArg[2] = zMasterSchema;
  94231. azArg[3] = 0;
  94232. initData.db = db;
  94233. initData.iDb = iDb;
  94234. initData.rc = SQLITE_OK;
  94235. initData.pzErrMsg = pzErrMsg;
  94236. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  94237. if( initData.rc ){
  94238. rc = initData.rc;
  94239. goto error_out;
  94240. }
  94241. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  94242. if( ALWAYS(pTab) ){
  94243. pTab->tabFlags |= TF_Readonly;
  94244. }
  94245. /* Create a cursor to hold the database open
  94246. */
  94247. pDb = &db->aDb[iDb];
  94248. if( pDb->pBt==0 ){
  94249. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  94250. DbSetProperty(db, 1, DB_SchemaLoaded);
  94251. }
  94252. return SQLITE_OK;
  94253. }
  94254. /* If there is not already a read-only (or read-write) transaction opened
  94255. ** on the b-tree database, open one now. If a transaction is opened, it
  94256. ** will be closed before this function returns. */
  94257. sqlite3BtreeEnter(pDb->pBt);
  94258. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  94259. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  94260. if( rc!=SQLITE_OK ){
  94261. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  94262. goto initone_error_out;
  94263. }
  94264. openedTransaction = 1;
  94265. }
  94266. /* Get the database meta information.
  94267. **
  94268. ** Meta values are as follows:
  94269. ** meta[0] Schema cookie. Changes with each schema change.
  94270. ** meta[1] File format of schema layer.
  94271. ** meta[2] Size of the page cache.
  94272. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  94273. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  94274. ** meta[5] User version
  94275. ** meta[6] Incremental vacuum mode
  94276. ** meta[7] unused
  94277. ** meta[8] unused
  94278. ** meta[9] unused
  94279. **
  94280. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  94281. ** the possible values of meta[4].
  94282. */
  94283. for(i=0; i<ArraySize(meta); i++){
  94284. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  94285. }
  94286. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  94287. /* If opening a non-empty database, check the text encoding. For the
  94288. ** main database, set sqlite3.enc to the encoding of the main database.
  94289. ** For an attached db, it is an error if the encoding is not the same
  94290. ** as sqlite3.enc.
  94291. */
  94292. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  94293. if( iDb==0 ){
  94294. #ifndef SQLITE_OMIT_UTF16
  94295. u8 encoding;
  94296. /* If opening the main database, set ENC(db). */
  94297. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  94298. if( encoding==0 ) encoding = SQLITE_UTF8;
  94299. ENC(db) = encoding;
  94300. #else
  94301. ENC(db) = SQLITE_UTF8;
  94302. #endif
  94303. }else{
  94304. /* If opening an attached database, the encoding much match ENC(db) */
  94305. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  94306. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  94307. " text encoding as main database");
  94308. rc = SQLITE_ERROR;
  94309. goto initone_error_out;
  94310. }
  94311. }
  94312. }else{
  94313. DbSetProperty(db, iDb, DB_Empty);
  94314. }
  94315. pDb->pSchema->enc = ENC(db);
  94316. if( pDb->pSchema->cache_size==0 ){
  94317. #ifndef SQLITE_OMIT_DEPRECATED
  94318. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  94319. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  94320. pDb->pSchema->cache_size = size;
  94321. #else
  94322. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  94323. #endif
  94324. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  94325. }
  94326. /*
  94327. ** file_format==1 Version 3.0.0.
  94328. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  94329. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  94330. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  94331. */
  94332. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  94333. if( pDb->pSchema->file_format==0 ){
  94334. pDb->pSchema->file_format = 1;
  94335. }
  94336. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  94337. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  94338. rc = SQLITE_ERROR;
  94339. goto initone_error_out;
  94340. }
  94341. /* Ticket #2804: When we open a database in the newer file format,
  94342. ** clear the legacy_file_format pragma flag so that a VACUUM will
  94343. ** not downgrade the database and thus invalidate any descending
  94344. ** indices that the user might have created.
  94345. */
  94346. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  94347. db->flags &= ~SQLITE_LegacyFileFmt;
  94348. }
  94349. /* Read the schema information out of the schema tables
  94350. */
  94351. assert( db->init.busy );
  94352. {
  94353. char *zSql;
  94354. zSql = sqlite3MPrintf(db,
  94355. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  94356. db->aDb[iDb].zName, zMasterName);
  94357. #ifndef SQLITE_OMIT_AUTHORIZATION
  94358. {
  94359. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  94360. xAuth = db->xAuth;
  94361. db->xAuth = 0;
  94362. #endif
  94363. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  94364. #ifndef SQLITE_OMIT_AUTHORIZATION
  94365. db->xAuth = xAuth;
  94366. }
  94367. #endif
  94368. if( rc==SQLITE_OK ) rc = initData.rc;
  94369. sqlite3DbFree(db, zSql);
  94370. #ifndef SQLITE_OMIT_ANALYZE
  94371. if( rc==SQLITE_OK ){
  94372. sqlite3AnalysisLoad(db, iDb);
  94373. }
  94374. #endif
  94375. }
  94376. if( db->mallocFailed ){
  94377. rc = SQLITE_NOMEM;
  94378. sqlite3ResetAllSchemasOfConnection(db);
  94379. }
  94380. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  94381. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  94382. ** the schema loaded, even if errors occurred. In this situation the
  94383. ** current sqlite3_prepare() operation will fail, but the following one
  94384. ** will attempt to compile the supplied statement against whatever subset
  94385. ** of the schema was loaded before the error occurred. The primary
  94386. ** purpose of this is to allow access to the sqlite_master table
  94387. ** even when its contents have been corrupted.
  94388. */
  94389. DbSetProperty(db, iDb, DB_SchemaLoaded);
  94390. rc = SQLITE_OK;
  94391. }
  94392. /* Jump here for an error that occurs after successfully allocating
  94393. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  94394. ** before that point, jump to error_out.
  94395. */
  94396. initone_error_out:
  94397. if( openedTransaction ){
  94398. sqlite3BtreeCommit(pDb->pBt);
  94399. }
  94400. sqlite3BtreeLeave(pDb->pBt);
  94401. error_out:
  94402. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  94403. db->mallocFailed = 1;
  94404. }
  94405. return rc;
  94406. }
  94407. /*
  94408. ** Initialize all database files - the main database file, the file
  94409. ** used to store temporary tables, and any additional database files
  94410. ** created using ATTACH statements. Return a success code. If an
  94411. ** error occurs, write an error message into *pzErrMsg.
  94412. **
  94413. ** After a database is initialized, the DB_SchemaLoaded bit is set
  94414. ** bit is set in the flags field of the Db structure. If the database
  94415. ** file was of zero-length, then the DB_Empty flag is also set.
  94416. */
  94417. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  94418. int i, rc;
  94419. int commit_internal = !(db->flags&SQLITE_InternChanges);
  94420. assert( sqlite3_mutex_held(db->mutex) );
  94421. rc = SQLITE_OK;
  94422. db->init.busy = 1;
  94423. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  94424. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  94425. rc = sqlite3InitOne(db, i, pzErrMsg);
  94426. if( rc ){
  94427. sqlite3ResetOneSchema(db, i);
  94428. }
  94429. }
  94430. /* Once all the other databases have been initialized, load the schema
  94431. ** for the TEMP database. This is loaded last, as the TEMP database
  94432. ** schema may contain references to objects in other databases.
  94433. */
  94434. #ifndef SQLITE_OMIT_TEMPDB
  94435. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  94436. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  94437. rc = sqlite3InitOne(db, 1, pzErrMsg);
  94438. if( rc ){
  94439. sqlite3ResetOneSchema(db, 1);
  94440. }
  94441. }
  94442. #endif
  94443. db->init.busy = 0;
  94444. if( rc==SQLITE_OK && commit_internal ){
  94445. sqlite3CommitInternalChanges(db);
  94446. }
  94447. return rc;
  94448. }
  94449. /*
  94450. ** This routine is a no-op if the database schema is already initialized.
  94451. ** Otherwise, the schema is loaded. An error code is returned.
  94452. */
  94453. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  94454. int rc = SQLITE_OK;
  94455. sqlite3 *db = pParse->db;
  94456. assert( sqlite3_mutex_held(db->mutex) );
  94457. if( !db->init.busy ){
  94458. rc = sqlite3Init(db, &pParse->zErrMsg);
  94459. }
  94460. if( rc!=SQLITE_OK ){
  94461. pParse->rc = rc;
  94462. pParse->nErr++;
  94463. }
  94464. return rc;
  94465. }
  94466. /*
  94467. ** Check schema cookies in all databases. If any cookie is out
  94468. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  94469. ** make no changes to pParse->rc.
  94470. */
  94471. static void schemaIsValid(Parse *pParse){
  94472. sqlite3 *db = pParse->db;
  94473. int iDb;
  94474. int rc;
  94475. int cookie;
  94476. assert( pParse->checkSchema );
  94477. assert( sqlite3_mutex_held(db->mutex) );
  94478. for(iDb=0; iDb<db->nDb; iDb++){
  94479. int openedTransaction = 0; /* True if a transaction is opened */
  94480. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  94481. if( pBt==0 ) continue;
  94482. /* If there is not already a read-only (or read-write) transaction opened
  94483. ** on the b-tree database, open one now. If a transaction is opened, it
  94484. ** will be closed immediately after reading the meta-value. */
  94485. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  94486. rc = sqlite3BtreeBeginTrans(pBt, 0);
  94487. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  94488. db->mallocFailed = 1;
  94489. }
  94490. if( rc!=SQLITE_OK ) return;
  94491. openedTransaction = 1;
  94492. }
  94493. /* Read the schema cookie from the database. If it does not match the
  94494. ** value stored as part of the in-memory schema representation,
  94495. ** set Parse.rc to SQLITE_SCHEMA. */
  94496. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  94497. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94498. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  94499. sqlite3ResetOneSchema(db, iDb);
  94500. pParse->rc = SQLITE_SCHEMA;
  94501. }
  94502. /* Close the transaction, if one was opened. */
  94503. if( openedTransaction ){
  94504. sqlite3BtreeCommit(pBt);
  94505. }
  94506. }
  94507. }
  94508. /*
  94509. ** Convert a schema pointer into the iDb index that indicates
  94510. ** which database file in db->aDb[] the schema refers to.
  94511. **
  94512. ** If the same database is attached more than once, the first
  94513. ** attached database is returned.
  94514. */
  94515. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  94516. int i = -1000000;
  94517. /* If pSchema is NULL, then return -1000000. This happens when code in
  94518. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  94519. ** created by a sub-select). In this case the return value of this
  94520. ** function should never be used.
  94521. **
  94522. ** We return -1000000 instead of the more usual -1 simply because using
  94523. ** -1000000 as the incorrect index into db->aDb[] is much
  94524. ** more likely to cause a segfault than -1 (of course there are assert()
  94525. ** statements too, but it never hurts to play the odds).
  94526. */
  94527. assert( sqlite3_mutex_held(db->mutex) );
  94528. if( pSchema ){
  94529. for(i=0; ALWAYS(i<db->nDb); i++){
  94530. if( db->aDb[i].pSchema==pSchema ){
  94531. break;
  94532. }
  94533. }
  94534. assert( i>=0 && i<db->nDb );
  94535. }
  94536. return i;
  94537. }
  94538. /*
  94539. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  94540. */
  94541. static int sqlite3Prepare(
  94542. sqlite3 *db, /* Database handle. */
  94543. const char *zSql, /* UTF-8 encoded SQL statement. */
  94544. int nBytes, /* Length of zSql in bytes. */
  94545. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  94546. Vdbe *pReprepare, /* VM being reprepared */
  94547. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94548. const char **pzTail /* OUT: End of parsed string */
  94549. ){
  94550. Parse *pParse; /* Parsing context */
  94551. char *zErrMsg = 0; /* Error message */
  94552. int rc = SQLITE_OK; /* Result code */
  94553. int i; /* Loop counter */
  94554. /* Allocate the parsing context */
  94555. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  94556. if( pParse==0 ){
  94557. rc = SQLITE_NOMEM;
  94558. goto end_prepare;
  94559. }
  94560. pParse->pReprepare = pReprepare;
  94561. assert( ppStmt && *ppStmt==0 );
  94562. assert( !db->mallocFailed );
  94563. assert( sqlite3_mutex_held(db->mutex) );
  94564. /* Check to verify that it is possible to get a read lock on all
  94565. ** database schemas. The inability to get a read lock indicates that
  94566. ** some other database connection is holding a write-lock, which in
  94567. ** turn means that the other connection has made uncommitted changes
  94568. ** to the schema.
  94569. **
  94570. ** Were we to proceed and prepare the statement against the uncommitted
  94571. ** schema changes and if those schema changes are subsequently rolled
  94572. ** back and different changes are made in their place, then when this
  94573. ** prepared statement goes to run the schema cookie would fail to detect
  94574. ** the schema change. Disaster would follow.
  94575. **
  94576. ** This thread is currently holding mutexes on all Btrees (because
  94577. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  94578. ** is not possible for another thread to start a new schema change
  94579. ** while this routine is running. Hence, we do not need to hold
  94580. ** locks on the schema, we just need to make sure nobody else is
  94581. ** holding them.
  94582. **
  94583. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  94584. ** but it does *not* override schema lock detection, so this all still
  94585. ** works even if READ_UNCOMMITTED is set.
  94586. */
  94587. for(i=0; i<db->nDb; i++) {
  94588. Btree *pBt = db->aDb[i].pBt;
  94589. if( pBt ){
  94590. assert( sqlite3BtreeHoldsMutex(pBt) );
  94591. rc = sqlite3BtreeSchemaLocked(pBt);
  94592. if( rc ){
  94593. const char *zDb = db->aDb[i].zName;
  94594. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  94595. testcase( db->flags & SQLITE_ReadUncommitted );
  94596. goto end_prepare;
  94597. }
  94598. }
  94599. }
  94600. sqlite3VtabUnlockList(db);
  94601. pParse->db = db;
  94602. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  94603. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  94604. char *zSqlCopy;
  94605. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  94606. testcase( nBytes==mxLen );
  94607. testcase( nBytes==mxLen+1 );
  94608. if( nBytes>mxLen ){
  94609. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  94610. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  94611. goto end_prepare;
  94612. }
  94613. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  94614. if( zSqlCopy ){
  94615. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  94616. sqlite3DbFree(db, zSqlCopy);
  94617. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  94618. }else{
  94619. pParse->zTail = &zSql[nBytes];
  94620. }
  94621. }else{
  94622. sqlite3RunParser(pParse, zSql, &zErrMsg);
  94623. }
  94624. assert( 0==pParse->nQueryLoop );
  94625. if( db->mallocFailed ){
  94626. pParse->rc = SQLITE_NOMEM;
  94627. }
  94628. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  94629. if( pParse->checkSchema ){
  94630. schemaIsValid(pParse);
  94631. }
  94632. if( db->mallocFailed ){
  94633. pParse->rc = SQLITE_NOMEM;
  94634. }
  94635. if( pzTail ){
  94636. *pzTail = pParse->zTail;
  94637. }
  94638. rc = pParse->rc;
  94639. #ifndef SQLITE_OMIT_EXPLAIN
  94640. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  94641. static const char * const azColName[] = {
  94642. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  94643. "selectid", "order", "from", "detail"
  94644. };
  94645. int iFirst, mx;
  94646. if( pParse->explain==2 ){
  94647. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  94648. iFirst = 8;
  94649. mx = 12;
  94650. }else{
  94651. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  94652. iFirst = 0;
  94653. mx = 8;
  94654. }
  94655. for(i=iFirst; i<mx; i++){
  94656. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  94657. azColName[i], SQLITE_STATIC);
  94658. }
  94659. }
  94660. #endif
  94661. if( db->init.busy==0 ){
  94662. Vdbe *pVdbe = pParse->pVdbe;
  94663. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  94664. }
  94665. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  94666. sqlite3VdbeFinalize(pParse->pVdbe);
  94667. assert(!(*ppStmt));
  94668. }else{
  94669. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  94670. }
  94671. if( zErrMsg ){
  94672. sqlite3Error(db, rc, "%s", zErrMsg);
  94673. sqlite3DbFree(db, zErrMsg);
  94674. }else{
  94675. sqlite3Error(db, rc, 0);
  94676. }
  94677. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  94678. while( pParse->pTriggerPrg ){
  94679. TriggerPrg *pT = pParse->pTriggerPrg;
  94680. pParse->pTriggerPrg = pT->pNext;
  94681. sqlite3DbFree(db, pT);
  94682. }
  94683. end_prepare:
  94684. sqlite3StackFree(db, pParse);
  94685. rc = sqlite3ApiExit(db, rc);
  94686. assert( (rc&db->errMask)==rc );
  94687. return rc;
  94688. }
  94689. static int sqlite3LockAndPrepare(
  94690. sqlite3 *db, /* Database handle. */
  94691. const char *zSql, /* UTF-8 encoded SQL statement. */
  94692. int nBytes, /* Length of zSql in bytes. */
  94693. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  94694. Vdbe *pOld, /* VM being reprepared */
  94695. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94696. const char **pzTail /* OUT: End of parsed string */
  94697. ){
  94698. int rc;
  94699. assert( ppStmt!=0 );
  94700. *ppStmt = 0;
  94701. if( !sqlite3SafetyCheckOk(db) ){
  94702. return SQLITE_MISUSE_BKPT;
  94703. }
  94704. sqlite3_mutex_enter(db->mutex);
  94705. sqlite3BtreeEnterAll(db);
  94706. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  94707. if( rc==SQLITE_SCHEMA ){
  94708. sqlite3_finalize(*ppStmt);
  94709. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  94710. }
  94711. sqlite3BtreeLeaveAll(db);
  94712. sqlite3_mutex_leave(db->mutex);
  94713. assert( rc==SQLITE_OK || *ppStmt==0 );
  94714. return rc;
  94715. }
  94716. /*
  94717. ** Rerun the compilation of a statement after a schema change.
  94718. **
  94719. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  94720. ** if the statement cannot be recompiled because another connection has
  94721. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  94722. ** occurs, return SQLITE_SCHEMA.
  94723. */
  94724. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  94725. int rc;
  94726. sqlite3_stmt *pNew;
  94727. const char *zSql;
  94728. sqlite3 *db;
  94729. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  94730. zSql = sqlite3_sql((sqlite3_stmt *)p);
  94731. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  94732. db = sqlite3VdbeDb(p);
  94733. assert( sqlite3_mutex_held(db->mutex) );
  94734. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  94735. if( rc ){
  94736. if( rc==SQLITE_NOMEM ){
  94737. db->mallocFailed = 1;
  94738. }
  94739. assert( pNew==0 );
  94740. return rc;
  94741. }else{
  94742. assert( pNew!=0 );
  94743. }
  94744. sqlite3VdbeSwap((Vdbe*)pNew, p);
  94745. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  94746. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  94747. sqlite3VdbeFinalize((Vdbe*)pNew);
  94748. return SQLITE_OK;
  94749. }
  94750. /*
  94751. ** Two versions of the official API. Legacy and new use. In the legacy
  94752. ** version, the original SQL text is not saved in the prepared statement
  94753. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  94754. ** sqlite3_step(). In the new version, the original SQL text is retained
  94755. ** and the statement is automatically recompiled if an schema change
  94756. ** occurs.
  94757. */
  94758. SQLITE_API int sqlite3_prepare(
  94759. sqlite3 *db, /* Database handle. */
  94760. const char *zSql, /* UTF-8 encoded SQL statement. */
  94761. int nBytes, /* Length of zSql in bytes. */
  94762. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94763. const char **pzTail /* OUT: End of parsed string */
  94764. ){
  94765. int rc;
  94766. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  94767. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94768. return rc;
  94769. }
  94770. SQLITE_API int sqlite3_prepare_v2(
  94771. sqlite3 *db, /* Database handle. */
  94772. const char *zSql, /* UTF-8 encoded SQL statement. */
  94773. int nBytes, /* Length of zSql in bytes. */
  94774. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94775. const char **pzTail /* OUT: End of parsed string */
  94776. ){
  94777. int rc;
  94778. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  94779. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94780. return rc;
  94781. }
  94782. #ifndef SQLITE_OMIT_UTF16
  94783. /*
  94784. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  94785. */
  94786. static int sqlite3Prepare16(
  94787. sqlite3 *db, /* Database handle. */
  94788. const void *zSql, /* UTF-16 encoded SQL statement. */
  94789. int nBytes, /* Length of zSql in bytes. */
  94790. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  94791. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94792. const void **pzTail /* OUT: End of parsed string */
  94793. ){
  94794. /* This function currently works by first transforming the UTF-16
  94795. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  94796. ** tricky bit is figuring out the pointer to return in *pzTail.
  94797. */
  94798. char *zSql8;
  94799. const char *zTail8 = 0;
  94800. int rc = SQLITE_OK;
  94801. assert( ppStmt );
  94802. *ppStmt = 0;
  94803. if( !sqlite3SafetyCheckOk(db) ){
  94804. return SQLITE_MISUSE_BKPT;
  94805. }
  94806. if( nBytes>=0 ){
  94807. int sz;
  94808. const char *z = (const char*)zSql;
  94809. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  94810. nBytes = sz;
  94811. }
  94812. sqlite3_mutex_enter(db->mutex);
  94813. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  94814. if( zSql8 ){
  94815. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  94816. }
  94817. if( zTail8 && pzTail ){
  94818. /* If sqlite3_prepare returns a tail pointer, we calculate the
  94819. ** equivalent pointer into the UTF-16 string by counting the unicode
  94820. ** characters between zSql8 and zTail8, and then returning a pointer
  94821. ** the same number of characters into the UTF-16 string.
  94822. */
  94823. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  94824. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  94825. }
  94826. sqlite3DbFree(db, zSql8);
  94827. rc = sqlite3ApiExit(db, rc);
  94828. sqlite3_mutex_leave(db->mutex);
  94829. return rc;
  94830. }
  94831. /*
  94832. ** Two versions of the official API. Legacy and new use. In the legacy
  94833. ** version, the original SQL text is not saved in the prepared statement
  94834. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  94835. ** sqlite3_step(). In the new version, the original SQL text is retained
  94836. ** and the statement is automatically recompiled if an schema change
  94837. ** occurs.
  94838. */
  94839. SQLITE_API int sqlite3_prepare16(
  94840. sqlite3 *db, /* Database handle. */
  94841. const void *zSql, /* UTF-16 encoded SQL statement. */
  94842. int nBytes, /* Length of zSql in bytes. */
  94843. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94844. const void **pzTail /* OUT: End of parsed string */
  94845. ){
  94846. int rc;
  94847. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  94848. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94849. return rc;
  94850. }
  94851. SQLITE_API int sqlite3_prepare16_v2(
  94852. sqlite3 *db, /* Database handle. */
  94853. const void *zSql, /* UTF-16 encoded SQL statement. */
  94854. int nBytes, /* Length of zSql in bytes. */
  94855. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94856. const void **pzTail /* OUT: End of parsed string */
  94857. ){
  94858. int rc;
  94859. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  94860. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94861. return rc;
  94862. }
  94863. #endif /* SQLITE_OMIT_UTF16 */
  94864. /************** End of prepare.c *********************************************/
  94865. /************** Begin file select.c ******************************************/
  94866. /*
  94867. ** 2001 September 15
  94868. **
  94869. ** The author disclaims copyright to this source code. In place of
  94870. ** a legal notice, here is a blessing:
  94871. **
  94872. ** May you do good and not evil.
  94873. ** May you find forgiveness for yourself and forgive others.
  94874. ** May you share freely, never taking more than you give.
  94875. **
  94876. *************************************************************************
  94877. ** This file contains C code routines that are called by the parser
  94878. ** to handle SELECT statements in SQLite.
  94879. */
  94880. /*
  94881. ** Delete all the content of a Select structure but do not deallocate
  94882. ** the select structure itself.
  94883. */
  94884. static void clearSelect(sqlite3 *db, Select *p){
  94885. sqlite3ExprListDelete(db, p->pEList);
  94886. sqlite3SrcListDelete(db, p->pSrc);
  94887. sqlite3ExprDelete(db, p->pWhere);
  94888. sqlite3ExprListDelete(db, p->pGroupBy);
  94889. sqlite3ExprDelete(db, p->pHaving);
  94890. sqlite3ExprListDelete(db, p->pOrderBy);
  94891. sqlite3SelectDelete(db, p->pPrior);
  94892. sqlite3ExprDelete(db, p->pLimit);
  94893. sqlite3ExprDelete(db, p->pOffset);
  94894. }
  94895. /*
  94896. ** Initialize a SelectDest structure.
  94897. */
  94898. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  94899. pDest->eDest = (u8)eDest;
  94900. pDest->iSDParm = iParm;
  94901. pDest->affSdst = 0;
  94902. pDest->iSdst = 0;
  94903. pDest->nSdst = 0;
  94904. }
  94905. /*
  94906. ** Allocate a new Select structure and return a pointer to that
  94907. ** structure.
  94908. */
  94909. SQLITE_PRIVATE Select *sqlite3SelectNew(
  94910. Parse *pParse, /* Parsing context */
  94911. ExprList *pEList, /* which columns to include in the result */
  94912. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  94913. Expr *pWhere, /* the WHERE clause */
  94914. ExprList *pGroupBy, /* the GROUP BY clause */
  94915. Expr *pHaving, /* the HAVING clause */
  94916. ExprList *pOrderBy, /* the ORDER BY clause */
  94917. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  94918. Expr *pLimit, /* LIMIT value. NULL means not used */
  94919. Expr *pOffset /* OFFSET value. NULL means no offset */
  94920. ){
  94921. Select *pNew;
  94922. Select standin;
  94923. sqlite3 *db = pParse->db;
  94924. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  94925. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  94926. if( pNew==0 ){
  94927. assert( db->mallocFailed );
  94928. pNew = &standin;
  94929. memset(pNew, 0, sizeof(*pNew));
  94930. }
  94931. if( pEList==0 ){
  94932. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  94933. }
  94934. pNew->pEList = pEList;
  94935. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  94936. pNew->pSrc = pSrc;
  94937. pNew->pWhere = pWhere;
  94938. pNew->pGroupBy = pGroupBy;
  94939. pNew->pHaving = pHaving;
  94940. pNew->pOrderBy = pOrderBy;
  94941. pNew->selFlags = selFlags;
  94942. pNew->op = TK_SELECT;
  94943. pNew->pLimit = pLimit;
  94944. pNew->pOffset = pOffset;
  94945. assert( pOffset==0 || pLimit!=0 );
  94946. pNew->addrOpenEphm[0] = -1;
  94947. pNew->addrOpenEphm[1] = -1;
  94948. pNew->addrOpenEphm[2] = -1;
  94949. if( db->mallocFailed ) {
  94950. clearSelect(db, pNew);
  94951. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  94952. pNew = 0;
  94953. }else{
  94954. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  94955. }
  94956. assert( pNew!=&standin );
  94957. return pNew;
  94958. }
  94959. /*
  94960. ** Delete the given Select structure and all of its substructures.
  94961. */
  94962. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  94963. if( p ){
  94964. clearSelect(db, p);
  94965. sqlite3DbFree(db, p);
  94966. }
  94967. }
  94968. /*
  94969. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  94970. ** type of join. Return an integer constant that expresses that type
  94971. ** in terms of the following bit values:
  94972. **
  94973. ** JT_INNER
  94974. ** JT_CROSS
  94975. ** JT_OUTER
  94976. ** JT_NATURAL
  94977. ** JT_LEFT
  94978. ** JT_RIGHT
  94979. **
  94980. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  94981. **
  94982. ** If an illegal or unsupported join type is seen, then still return
  94983. ** a join type, but put an error in the pParse structure.
  94984. */
  94985. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  94986. int jointype = 0;
  94987. Token *apAll[3];
  94988. Token *p;
  94989. /* 0123456789 123456789 123456789 123 */
  94990. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  94991. static const struct {
  94992. u8 i; /* Beginning of keyword text in zKeyText[] */
  94993. u8 nChar; /* Length of the keyword in characters */
  94994. u8 code; /* Join type mask */
  94995. } aKeyword[] = {
  94996. /* natural */ { 0, 7, JT_NATURAL },
  94997. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  94998. /* outer */ { 10, 5, JT_OUTER },
  94999. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  95000. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  95001. /* inner */ { 23, 5, JT_INNER },
  95002. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  95003. };
  95004. int i, j;
  95005. apAll[0] = pA;
  95006. apAll[1] = pB;
  95007. apAll[2] = pC;
  95008. for(i=0; i<3 && apAll[i]; i++){
  95009. p = apAll[i];
  95010. for(j=0; j<ArraySize(aKeyword); j++){
  95011. if( p->n==aKeyword[j].nChar
  95012. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  95013. jointype |= aKeyword[j].code;
  95014. break;
  95015. }
  95016. }
  95017. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  95018. if( j>=ArraySize(aKeyword) ){
  95019. jointype |= JT_ERROR;
  95020. break;
  95021. }
  95022. }
  95023. if(
  95024. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  95025. (jointype & JT_ERROR)!=0
  95026. ){
  95027. const char *zSp = " ";
  95028. assert( pB!=0 );
  95029. if( pC==0 ){ zSp++; }
  95030. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  95031. "%T %T%s%T", pA, pB, zSp, pC);
  95032. jointype = JT_INNER;
  95033. }else if( (jointype & JT_OUTER)!=0
  95034. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  95035. sqlite3ErrorMsg(pParse,
  95036. "RIGHT and FULL OUTER JOINs are not currently supported");
  95037. jointype = JT_INNER;
  95038. }
  95039. return jointype;
  95040. }
  95041. /*
  95042. ** Return the index of a column in a table. Return -1 if the column
  95043. ** is not contained in the table.
  95044. */
  95045. static int columnIndex(Table *pTab, const char *zCol){
  95046. int i;
  95047. for(i=0; i<pTab->nCol; i++){
  95048. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  95049. }
  95050. return -1;
  95051. }
  95052. /*
  95053. ** Search the first N tables in pSrc, from left to right, looking for a
  95054. ** table that has a column named zCol.
  95055. **
  95056. ** When found, set *piTab and *piCol to the table index and column index
  95057. ** of the matching column and return TRUE.
  95058. **
  95059. ** If not found, return FALSE.
  95060. */
  95061. static int tableAndColumnIndex(
  95062. SrcList *pSrc, /* Array of tables to search */
  95063. int N, /* Number of tables in pSrc->a[] to search */
  95064. const char *zCol, /* Name of the column we are looking for */
  95065. int *piTab, /* Write index of pSrc->a[] here */
  95066. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  95067. ){
  95068. int i; /* For looping over tables in pSrc */
  95069. int iCol; /* Index of column matching zCol */
  95070. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  95071. for(i=0; i<N; i++){
  95072. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  95073. if( iCol>=0 ){
  95074. if( piTab ){
  95075. *piTab = i;
  95076. *piCol = iCol;
  95077. }
  95078. return 1;
  95079. }
  95080. }
  95081. return 0;
  95082. }
  95083. /*
  95084. ** This function is used to add terms implied by JOIN syntax to the
  95085. ** WHERE clause expression of a SELECT statement. The new term, which
  95086. ** is ANDed with the existing WHERE clause, is of the form:
  95087. **
  95088. ** (tab1.col1 = tab2.col2)
  95089. **
  95090. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  95091. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  95092. ** column iColRight of tab2.
  95093. */
  95094. static void addWhereTerm(
  95095. Parse *pParse, /* Parsing context */
  95096. SrcList *pSrc, /* List of tables in FROM clause */
  95097. int iLeft, /* Index of first table to join in pSrc */
  95098. int iColLeft, /* Index of column in first table */
  95099. int iRight, /* Index of second table in pSrc */
  95100. int iColRight, /* Index of column in second table */
  95101. int isOuterJoin, /* True if this is an OUTER join */
  95102. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  95103. ){
  95104. sqlite3 *db = pParse->db;
  95105. Expr *pE1;
  95106. Expr *pE2;
  95107. Expr *pEq;
  95108. assert( iLeft<iRight );
  95109. assert( pSrc->nSrc>iRight );
  95110. assert( pSrc->a[iLeft].pTab );
  95111. assert( pSrc->a[iRight].pTab );
  95112. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  95113. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  95114. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  95115. if( pEq && isOuterJoin ){
  95116. ExprSetProperty(pEq, EP_FromJoin);
  95117. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  95118. ExprSetVVAProperty(pEq, EP_NoReduce);
  95119. pEq->iRightJoinTable = (i16)pE2->iTable;
  95120. }
  95121. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  95122. }
  95123. /*
  95124. ** Set the EP_FromJoin property on all terms of the given expression.
  95125. ** And set the Expr.iRightJoinTable to iTable for every term in the
  95126. ** expression.
  95127. **
  95128. ** The EP_FromJoin property is used on terms of an expression to tell
  95129. ** the LEFT OUTER JOIN processing logic that this term is part of the
  95130. ** join restriction specified in the ON or USING clause and not a part
  95131. ** of the more general WHERE clause. These terms are moved over to the
  95132. ** WHERE clause during join processing but we need to remember that they
  95133. ** originated in the ON or USING clause.
  95134. **
  95135. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  95136. ** expression depends on table iRightJoinTable even if that table is not
  95137. ** explicitly mentioned in the expression. That information is needed
  95138. ** for cases like this:
  95139. **
  95140. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  95141. **
  95142. ** The where clause needs to defer the handling of the t1.x=5
  95143. ** term until after the t2 loop of the join. In that way, a
  95144. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  95145. ** defer the handling of t1.x=5, it will be processed immediately
  95146. ** after the t1 loop and rows with t1.x!=5 will never appear in
  95147. ** the output, which is incorrect.
  95148. */
  95149. static void setJoinExpr(Expr *p, int iTable){
  95150. while( p ){
  95151. ExprSetProperty(p, EP_FromJoin);
  95152. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  95153. ExprSetVVAProperty(p, EP_NoReduce);
  95154. p->iRightJoinTable = (i16)iTable;
  95155. setJoinExpr(p->pLeft, iTable);
  95156. p = p->pRight;
  95157. }
  95158. }
  95159. /*
  95160. ** This routine processes the join information for a SELECT statement.
  95161. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  95162. ** NATURAL joins also create extra WHERE clause terms.
  95163. **
  95164. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  95165. ** The left most table is the first entry in Select.pSrc. The right-most
  95166. ** table is the last entry. The join operator is held in the entry to
  95167. ** the left. Thus entry 0 contains the join operator for the join between
  95168. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  95169. ** also attached to the left entry.
  95170. **
  95171. ** This routine returns the number of errors encountered.
  95172. */
  95173. static int sqliteProcessJoin(Parse *pParse, Select *p){
  95174. SrcList *pSrc; /* All tables in the FROM clause */
  95175. int i, j; /* Loop counters */
  95176. struct SrcList_item *pLeft; /* Left table being joined */
  95177. struct SrcList_item *pRight; /* Right table being joined */
  95178. pSrc = p->pSrc;
  95179. pLeft = &pSrc->a[0];
  95180. pRight = &pLeft[1];
  95181. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  95182. Table *pLeftTab = pLeft->pTab;
  95183. Table *pRightTab = pRight->pTab;
  95184. int isOuter;
  95185. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  95186. isOuter = (pRight->jointype & JT_OUTER)!=0;
  95187. /* When the NATURAL keyword is present, add WHERE clause terms for
  95188. ** every column that the two tables have in common.
  95189. */
  95190. if( pRight->jointype & JT_NATURAL ){
  95191. if( pRight->pOn || pRight->pUsing ){
  95192. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  95193. "an ON or USING clause", 0);
  95194. return 1;
  95195. }
  95196. for(j=0; j<pRightTab->nCol; j++){
  95197. char *zName; /* Name of column in the right table */
  95198. int iLeft; /* Matching left table */
  95199. int iLeftCol; /* Matching column in the left table */
  95200. zName = pRightTab->aCol[j].zName;
  95201. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  95202. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  95203. isOuter, &p->pWhere);
  95204. }
  95205. }
  95206. }
  95207. /* Disallow both ON and USING clauses in the same join
  95208. */
  95209. if( pRight->pOn && pRight->pUsing ){
  95210. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  95211. "clauses in the same join");
  95212. return 1;
  95213. }
  95214. /* Add the ON clause to the end of the WHERE clause, connected by
  95215. ** an AND operator.
  95216. */
  95217. if( pRight->pOn ){
  95218. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  95219. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  95220. pRight->pOn = 0;
  95221. }
  95222. /* Create extra terms on the WHERE clause for each column named
  95223. ** in the USING clause. Example: If the two tables to be joined are
  95224. ** A and B and the USING clause names X, Y, and Z, then add this
  95225. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  95226. ** Report an error if any column mentioned in the USING clause is
  95227. ** not contained in both tables to be joined.
  95228. */
  95229. if( pRight->pUsing ){
  95230. IdList *pList = pRight->pUsing;
  95231. for(j=0; j<pList->nId; j++){
  95232. char *zName; /* Name of the term in the USING clause */
  95233. int iLeft; /* Table on the left with matching column name */
  95234. int iLeftCol; /* Column number of matching column on the left */
  95235. int iRightCol; /* Column number of matching column on the right */
  95236. zName = pList->a[j].zName;
  95237. iRightCol = columnIndex(pRightTab, zName);
  95238. if( iRightCol<0
  95239. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  95240. ){
  95241. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  95242. "not present in both tables", zName);
  95243. return 1;
  95244. }
  95245. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  95246. isOuter, &p->pWhere);
  95247. }
  95248. }
  95249. }
  95250. return 0;
  95251. }
  95252. /*
  95253. ** Insert code into "v" that will push the record on the top of the
  95254. ** stack into the sorter.
  95255. */
  95256. static void pushOntoSorter(
  95257. Parse *pParse, /* Parser context */
  95258. ExprList *pOrderBy, /* The ORDER BY clause */
  95259. Select *pSelect, /* The whole SELECT statement */
  95260. int regData /* Register holding data to be sorted */
  95261. ){
  95262. Vdbe *v = pParse->pVdbe;
  95263. int nExpr = pOrderBy->nExpr;
  95264. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  95265. int regRecord = sqlite3GetTempReg(pParse);
  95266. int op;
  95267. sqlite3ExprCacheClear(pParse);
  95268. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  95269. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  95270. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  95271. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  95272. if( pSelect->selFlags & SF_UseSorter ){
  95273. op = OP_SorterInsert;
  95274. }else{
  95275. op = OP_IdxInsert;
  95276. }
  95277. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  95278. sqlite3ReleaseTempReg(pParse, regRecord);
  95279. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  95280. if( pSelect->iLimit ){
  95281. int addr1, addr2;
  95282. int iLimit;
  95283. if( pSelect->iOffset ){
  95284. iLimit = pSelect->iOffset+1;
  95285. }else{
  95286. iLimit = pSelect->iLimit;
  95287. }
  95288. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  95289. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  95290. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  95291. sqlite3VdbeJumpHere(v, addr1);
  95292. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  95293. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  95294. sqlite3VdbeJumpHere(v, addr2);
  95295. }
  95296. }
  95297. /*
  95298. ** Add code to implement the OFFSET
  95299. */
  95300. static void codeOffset(
  95301. Vdbe *v, /* Generate code into this VM */
  95302. Select *p, /* The SELECT statement being coded */
  95303. int iContinue /* Jump here to skip the current record */
  95304. ){
  95305. if( p->iOffset && iContinue!=0 ){
  95306. int addr;
  95307. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  95308. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  95309. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  95310. VdbeComment((v, "skip OFFSET records"));
  95311. sqlite3VdbeJumpHere(v, addr);
  95312. }
  95313. }
  95314. /*
  95315. ** Add code that will check to make sure the N registers starting at iMem
  95316. ** form a distinct entry. iTab is a sorting index that holds previously
  95317. ** seen combinations of the N values. A new entry is made in iTab
  95318. ** if the current N values are new.
  95319. **
  95320. ** A jump to addrRepeat is made and the N+1 values are popped from the
  95321. ** stack if the top N elements are not distinct.
  95322. */
  95323. static void codeDistinct(
  95324. Parse *pParse, /* Parsing and code generating context */
  95325. int iTab, /* A sorting index used to test for distinctness */
  95326. int addrRepeat, /* Jump to here if not distinct */
  95327. int N, /* Number of elements */
  95328. int iMem /* First element */
  95329. ){
  95330. Vdbe *v;
  95331. int r1;
  95332. v = pParse->pVdbe;
  95333. r1 = sqlite3GetTempReg(pParse);
  95334. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  95335. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  95336. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  95337. sqlite3ReleaseTempReg(pParse, r1);
  95338. }
  95339. #ifndef SQLITE_OMIT_SUBQUERY
  95340. /*
  95341. ** Generate an error message when a SELECT is used within a subexpression
  95342. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  95343. ** column. We do this in a subroutine because the error used to occur
  95344. ** in multiple places. (The error only occurs in one place now, but we
  95345. ** retain the subroutine to minimize code disruption.)
  95346. */
  95347. static int checkForMultiColumnSelectError(
  95348. Parse *pParse, /* Parse context. */
  95349. SelectDest *pDest, /* Destination of SELECT results */
  95350. int nExpr /* Number of result columns returned by SELECT */
  95351. ){
  95352. int eDest = pDest->eDest;
  95353. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  95354. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  95355. "a SELECT that is part of an expression");
  95356. return 1;
  95357. }else{
  95358. return 0;
  95359. }
  95360. }
  95361. #endif
  95362. /*
  95363. ** An instance of the following object is used to record information about
  95364. ** how to process the DISTINCT keyword, to simplify passing that information
  95365. ** into the selectInnerLoop() routine.
  95366. */
  95367. typedef struct DistinctCtx DistinctCtx;
  95368. struct DistinctCtx {
  95369. u8 isTnct; /* True if the DISTINCT keyword is present */
  95370. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  95371. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  95372. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  95373. };
  95374. /*
  95375. ** This routine generates the code for the inside of the inner loop
  95376. ** of a SELECT.
  95377. **
  95378. ** If srcTab and nColumn are both zero, then the pEList expressions
  95379. ** are evaluated in order to get the data for this row. If nColumn>0
  95380. ** then data is pulled from srcTab and pEList is used only to get the
  95381. ** datatypes for each column.
  95382. */
  95383. static void selectInnerLoop(
  95384. Parse *pParse, /* The parser context */
  95385. Select *p, /* The complete select statement being coded */
  95386. ExprList *pEList, /* List of values being extracted */
  95387. int srcTab, /* Pull data from this table */
  95388. int nColumn, /* Number of columns in the source table */
  95389. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  95390. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  95391. SelectDest *pDest, /* How to dispose of the results */
  95392. int iContinue, /* Jump here to continue with next row */
  95393. int iBreak /* Jump here to break out of the inner loop */
  95394. ){
  95395. Vdbe *v = pParse->pVdbe;
  95396. int i;
  95397. int hasDistinct; /* True if the DISTINCT keyword is present */
  95398. int regResult; /* Start of memory holding result set */
  95399. int eDest = pDest->eDest; /* How to dispose of results */
  95400. int iParm = pDest->iSDParm; /* First argument to disposal method */
  95401. int nResultCol; /* Number of result columns */
  95402. assert( v );
  95403. if( NEVER(v==0) ) return;
  95404. assert( pEList!=0 );
  95405. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  95406. if( pOrderBy==0 && !hasDistinct ){
  95407. codeOffset(v, p, iContinue);
  95408. }
  95409. /* Pull the requested columns.
  95410. */
  95411. if( nColumn>0 ){
  95412. nResultCol = nColumn;
  95413. }else{
  95414. nResultCol = pEList->nExpr;
  95415. }
  95416. if( pDest->iSdst==0 ){
  95417. pDest->iSdst = pParse->nMem+1;
  95418. pDest->nSdst = nResultCol;
  95419. pParse->nMem += nResultCol;
  95420. }else{
  95421. assert( pDest->nSdst==nResultCol );
  95422. }
  95423. regResult = pDest->iSdst;
  95424. if( nColumn>0 ){
  95425. for(i=0; i<nColumn; i++){
  95426. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  95427. }
  95428. }else if( eDest!=SRT_Exists ){
  95429. /* If the destination is an EXISTS(...) expression, the actual
  95430. ** values returned by the SELECT are not required.
  95431. */
  95432. sqlite3ExprCacheClear(pParse);
  95433. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  95434. }
  95435. nColumn = nResultCol;
  95436. /* If the DISTINCT keyword was present on the SELECT statement
  95437. ** and this row has been seen before, then do not make this row
  95438. ** part of the result.
  95439. */
  95440. if( hasDistinct ){
  95441. assert( pEList!=0 );
  95442. assert( pEList->nExpr==nColumn );
  95443. switch( pDistinct->eTnctType ){
  95444. case WHERE_DISTINCT_ORDERED: {
  95445. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  95446. int iJump; /* Jump destination */
  95447. int regPrev; /* Previous row content */
  95448. /* Allocate space for the previous row */
  95449. regPrev = pParse->nMem+1;
  95450. pParse->nMem += nColumn;
  95451. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  95452. ** sets the MEM_Cleared bit on the first register of the
  95453. ** previous value. This will cause the OP_Ne below to always
  95454. ** fail on the first iteration of the loop even if the first
  95455. ** row is all NULLs.
  95456. */
  95457. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  95458. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  95459. pOp->opcode = OP_Null;
  95460. pOp->p1 = 1;
  95461. pOp->p2 = regPrev;
  95462. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  95463. for(i=0; i<nColumn; i++){
  95464. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  95465. if( i<nColumn-1 ){
  95466. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  95467. }else{
  95468. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  95469. }
  95470. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  95471. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  95472. }
  95473. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  95474. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  95475. break;
  95476. }
  95477. case WHERE_DISTINCT_UNIQUE: {
  95478. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  95479. break;
  95480. }
  95481. default: {
  95482. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  95483. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  95484. break;
  95485. }
  95486. }
  95487. if( pOrderBy==0 ){
  95488. codeOffset(v, p, iContinue);
  95489. }
  95490. }
  95491. switch( eDest ){
  95492. /* In this mode, write each query result to the key of the temporary
  95493. ** table iParm.
  95494. */
  95495. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  95496. case SRT_Union: {
  95497. int r1;
  95498. r1 = sqlite3GetTempReg(pParse);
  95499. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95500. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  95501. sqlite3ReleaseTempReg(pParse, r1);
  95502. break;
  95503. }
  95504. /* Construct a record from the query result, but instead of
  95505. ** saving that record, use it as a key to delete elements from
  95506. ** the temporary table iParm.
  95507. */
  95508. case SRT_Except: {
  95509. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  95510. break;
  95511. }
  95512. #endif
  95513. /* Store the result as data using a unique key.
  95514. */
  95515. case SRT_Table:
  95516. case SRT_EphemTab: {
  95517. int r1 = sqlite3GetTempReg(pParse);
  95518. testcase( eDest==SRT_Table );
  95519. testcase( eDest==SRT_EphemTab );
  95520. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95521. if( pOrderBy ){
  95522. pushOntoSorter(pParse, pOrderBy, p, r1);
  95523. }else{
  95524. int r2 = sqlite3GetTempReg(pParse);
  95525. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  95526. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  95527. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95528. sqlite3ReleaseTempReg(pParse, r2);
  95529. }
  95530. sqlite3ReleaseTempReg(pParse, r1);
  95531. break;
  95532. }
  95533. #ifndef SQLITE_OMIT_SUBQUERY
  95534. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  95535. ** then there should be a single item on the stack. Write this
  95536. ** item into the set table with bogus data.
  95537. */
  95538. case SRT_Set: {
  95539. assert( nColumn==1 );
  95540. pDest->affSdst =
  95541. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  95542. if( pOrderBy ){
  95543. /* At first glance you would think we could optimize out the
  95544. ** ORDER BY in this case since the order of entries in the set
  95545. ** does not matter. But there might be a LIMIT clause, in which
  95546. ** case the order does matter */
  95547. pushOntoSorter(pParse, pOrderBy, p, regResult);
  95548. }else{
  95549. int r1 = sqlite3GetTempReg(pParse);
  95550. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  95551. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  95552. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  95553. sqlite3ReleaseTempReg(pParse, r1);
  95554. }
  95555. break;
  95556. }
  95557. /* If any row exist in the result set, record that fact and abort.
  95558. */
  95559. case SRT_Exists: {
  95560. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  95561. /* The LIMIT clause will terminate the loop for us */
  95562. break;
  95563. }
  95564. /* If this is a scalar select that is part of an expression, then
  95565. ** store the results in the appropriate memory cell and break out
  95566. ** of the scan loop.
  95567. */
  95568. case SRT_Mem: {
  95569. assert( nColumn==1 );
  95570. if( pOrderBy ){
  95571. pushOntoSorter(pParse, pOrderBy, p, regResult);
  95572. }else{
  95573. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  95574. /* The LIMIT clause will jump out of the loop for us */
  95575. }
  95576. break;
  95577. }
  95578. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  95579. /* Send the data to the callback function or to a subroutine. In the
  95580. ** case of a subroutine, the subroutine itself is responsible for
  95581. ** popping the data from the stack.
  95582. */
  95583. case SRT_Coroutine:
  95584. case SRT_Output: {
  95585. testcase( eDest==SRT_Coroutine );
  95586. testcase( eDest==SRT_Output );
  95587. if( pOrderBy ){
  95588. int r1 = sqlite3GetTempReg(pParse);
  95589. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95590. pushOntoSorter(pParse, pOrderBy, p, r1);
  95591. sqlite3ReleaseTempReg(pParse, r1);
  95592. }else if( eDest==SRT_Coroutine ){
  95593. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  95594. }else{
  95595. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  95596. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  95597. }
  95598. break;
  95599. }
  95600. #if !defined(SQLITE_OMIT_TRIGGER)
  95601. /* Discard the results. This is used for SELECT statements inside
  95602. ** the body of a TRIGGER. The purpose of such selects is to call
  95603. ** user-defined functions that have side effects. We do not care
  95604. ** about the actual results of the select.
  95605. */
  95606. default: {
  95607. assert( eDest==SRT_Discard );
  95608. break;
  95609. }
  95610. #endif
  95611. }
  95612. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  95613. ** there is a sorter, in which case the sorter has already limited
  95614. ** the output for us.
  95615. */
  95616. if( pOrderBy==0 && p->iLimit ){
  95617. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  95618. }
  95619. }
  95620. /*
  95621. ** Allocate a KeyInfo object sufficient for an index of N columns.
  95622. **
  95623. ** Actually, always allocate one extra column for the rowid at the end
  95624. ** of the index. So the KeyInfo returned will have space sufficient for
  95625. ** N+1 columns.
  95626. */
  95627. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
  95628. KeyInfo *p = sqlite3DbMallocZero(db,
  95629. sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
  95630. if( p ){
  95631. p->aSortOrder = (u8*)&p->aColl[N+1];
  95632. p->nField = (u16)N;
  95633. p->enc = ENC(db);
  95634. p->db = db;
  95635. }
  95636. return p;
  95637. }
  95638. /*
  95639. ** Given an expression list, generate a KeyInfo structure that records
  95640. ** the collating sequence for each expression in that expression list.
  95641. **
  95642. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  95643. ** KeyInfo structure is appropriate for initializing a virtual index to
  95644. ** implement that clause. If the ExprList is the result set of a SELECT
  95645. ** then the KeyInfo structure is appropriate for initializing a virtual
  95646. ** index to implement a DISTINCT test.
  95647. **
  95648. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  95649. ** function is responsible for seeing that this structure is eventually
  95650. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  95651. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  95652. */
  95653. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  95654. int nExpr;
  95655. KeyInfo *pInfo;
  95656. struct ExprList_item *pItem;
  95657. sqlite3 *db = pParse->db;
  95658. int i;
  95659. nExpr = pList->nExpr;
  95660. pInfo = sqlite3KeyInfoAlloc(db, nExpr);
  95661. if( pInfo ){
  95662. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  95663. CollSeq *pColl;
  95664. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  95665. if( !pColl ) pColl = db->pDfltColl;
  95666. pInfo->aColl[i] = pColl;
  95667. pInfo->aSortOrder[i] = pItem->sortOrder;
  95668. }
  95669. }
  95670. return pInfo;
  95671. }
  95672. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  95673. /*
  95674. ** Name of the connection operator, used for error messages.
  95675. */
  95676. static const char *selectOpName(int id){
  95677. char *z;
  95678. switch( id ){
  95679. case TK_ALL: z = "UNION ALL"; break;
  95680. case TK_INTERSECT: z = "INTERSECT"; break;
  95681. case TK_EXCEPT: z = "EXCEPT"; break;
  95682. default: z = "UNION"; break;
  95683. }
  95684. return z;
  95685. }
  95686. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  95687. #ifndef SQLITE_OMIT_EXPLAIN
  95688. /*
  95689. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  95690. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  95691. ** where the caption is of the form:
  95692. **
  95693. ** "USE TEMP B-TREE FOR xxx"
  95694. **
  95695. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  95696. ** is determined by the zUsage argument.
  95697. */
  95698. static void explainTempTable(Parse *pParse, const char *zUsage){
  95699. if( pParse->explain==2 ){
  95700. Vdbe *v = pParse->pVdbe;
  95701. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  95702. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  95703. }
  95704. }
  95705. /*
  95706. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  95707. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  95708. ** in sqlite3Select() to assign values to structure member variables that
  95709. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  95710. ** code with #ifndef directives.
  95711. */
  95712. # define explainSetInteger(a, b) a = b
  95713. #else
  95714. /* No-op versions of the explainXXX() functions and macros. */
  95715. # define explainTempTable(y,z)
  95716. # define explainSetInteger(y,z)
  95717. #endif
  95718. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  95719. /*
  95720. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  95721. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  95722. ** where the caption is of one of the two forms:
  95723. **
  95724. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  95725. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  95726. **
  95727. ** where iSub1 and iSub2 are the integers passed as the corresponding
  95728. ** function parameters, and op is the text representation of the parameter
  95729. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  95730. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  95731. ** false, or the second form if it is true.
  95732. */
  95733. static void explainComposite(
  95734. Parse *pParse, /* Parse context */
  95735. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  95736. int iSub1, /* Subquery id 1 */
  95737. int iSub2, /* Subquery id 2 */
  95738. int bUseTmp /* True if a temp table was used */
  95739. ){
  95740. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  95741. if( pParse->explain==2 ){
  95742. Vdbe *v = pParse->pVdbe;
  95743. char *zMsg = sqlite3MPrintf(
  95744. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  95745. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  95746. );
  95747. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  95748. }
  95749. }
  95750. #else
  95751. /* No-op versions of the explainXXX() functions and macros. */
  95752. # define explainComposite(v,w,x,y,z)
  95753. #endif
  95754. /*
  95755. ** If the inner loop was generated using a non-null pOrderBy argument,
  95756. ** then the results were placed in a sorter. After the loop is terminated
  95757. ** we need to run the sorter and output the results. The following
  95758. ** routine generates the code needed to do that.
  95759. */
  95760. static void generateSortTail(
  95761. Parse *pParse, /* Parsing context */
  95762. Select *p, /* The SELECT statement */
  95763. Vdbe *v, /* Generate code into this VDBE */
  95764. int nColumn, /* Number of columns of data */
  95765. SelectDest *pDest /* Write the sorted results here */
  95766. ){
  95767. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  95768. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  95769. int addr;
  95770. int iTab;
  95771. int pseudoTab = 0;
  95772. ExprList *pOrderBy = p->pOrderBy;
  95773. int eDest = pDest->eDest;
  95774. int iParm = pDest->iSDParm;
  95775. int regRow;
  95776. int regRowid;
  95777. iTab = pOrderBy->iECursor;
  95778. regRow = sqlite3GetTempReg(pParse);
  95779. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  95780. pseudoTab = pParse->nTab++;
  95781. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  95782. regRowid = 0;
  95783. }else{
  95784. regRowid = sqlite3GetTempReg(pParse);
  95785. }
  95786. if( p->selFlags & SF_UseSorter ){
  95787. int regSortOut = ++pParse->nMem;
  95788. int ptab2 = pParse->nTab++;
  95789. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  95790. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  95791. codeOffset(v, p, addrContinue);
  95792. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  95793. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  95794. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  95795. }else{
  95796. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  95797. codeOffset(v, p, addrContinue);
  95798. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  95799. }
  95800. switch( eDest ){
  95801. case SRT_Table:
  95802. case SRT_EphemTab: {
  95803. testcase( eDest==SRT_Table );
  95804. testcase( eDest==SRT_EphemTab );
  95805. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  95806. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  95807. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95808. break;
  95809. }
  95810. #ifndef SQLITE_OMIT_SUBQUERY
  95811. case SRT_Set: {
  95812. assert( nColumn==1 );
  95813. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  95814. &pDest->affSdst, 1);
  95815. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  95816. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  95817. break;
  95818. }
  95819. case SRT_Mem: {
  95820. assert( nColumn==1 );
  95821. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  95822. /* The LIMIT clause will terminate the loop for us */
  95823. break;
  95824. }
  95825. #endif
  95826. default: {
  95827. int i;
  95828. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  95829. testcase( eDest==SRT_Output );
  95830. testcase( eDest==SRT_Coroutine );
  95831. for(i=0; i<nColumn; i++){
  95832. assert( regRow!=pDest->iSdst+i );
  95833. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  95834. if( i==0 ){
  95835. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  95836. }
  95837. }
  95838. if( eDest==SRT_Output ){
  95839. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  95840. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  95841. }else{
  95842. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  95843. }
  95844. break;
  95845. }
  95846. }
  95847. sqlite3ReleaseTempReg(pParse, regRow);
  95848. sqlite3ReleaseTempReg(pParse, regRowid);
  95849. /* The bottom of the loop
  95850. */
  95851. sqlite3VdbeResolveLabel(v, addrContinue);
  95852. if( p->selFlags & SF_UseSorter ){
  95853. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  95854. }else{
  95855. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  95856. }
  95857. sqlite3VdbeResolveLabel(v, addrBreak);
  95858. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  95859. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  95860. }
  95861. }
  95862. /*
  95863. ** Return a pointer to a string containing the 'declaration type' of the
  95864. ** expression pExpr. The string may be treated as static by the caller.
  95865. **
  95866. ** Also try to estimate the size of the returned value and return that
  95867. ** result in *pEstWidth.
  95868. **
  95869. ** The declaration type is the exact datatype definition extracted from the
  95870. ** original CREATE TABLE statement if the expression is a column. The
  95871. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  95872. ** is considered a column can be complex in the presence of subqueries. The
  95873. ** result-set expression in all of the following SELECT statements is
  95874. ** considered a column by this function.
  95875. **
  95876. ** SELECT col FROM tbl;
  95877. ** SELECT (SELECT col FROM tbl;
  95878. ** SELECT (SELECT col FROM tbl);
  95879. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  95880. **
  95881. ** The declaration type for any expression other than a column is NULL.
  95882. **
  95883. ** This routine has either 3 or 6 parameters depending on whether or not
  95884. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  95885. */
  95886. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  95887. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  95888. static const char *columnTypeImpl(
  95889. NameContext *pNC,
  95890. Expr *pExpr,
  95891. const char **pzOrigDb,
  95892. const char **pzOrigTab,
  95893. const char **pzOrigCol,
  95894. u8 *pEstWidth
  95895. ){
  95896. char const *zOrigDb = 0;
  95897. char const *zOrigTab = 0;
  95898. char const *zOrigCol = 0;
  95899. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  95900. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  95901. static const char *columnTypeImpl(
  95902. NameContext *pNC,
  95903. Expr *pExpr,
  95904. u8 *pEstWidth
  95905. ){
  95906. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  95907. char const *zType = 0;
  95908. int j;
  95909. u8 estWidth = 1;
  95910. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  95911. switch( pExpr->op ){
  95912. case TK_AGG_COLUMN:
  95913. case TK_COLUMN: {
  95914. /* The expression is a column. Locate the table the column is being
  95915. ** extracted from in NameContext.pSrcList. This table may be real
  95916. ** database table or a subquery.
  95917. */
  95918. Table *pTab = 0; /* Table structure column is extracted from */
  95919. Select *pS = 0; /* Select the column is extracted from */
  95920. int iCol = pExpr->iColumn; /* Index of column in pTab */
  95921. testcase( pExpr->op==TK_AGG_COLUMN );
  95922. testcase( pExpr->op==TK_COLUMN );
  95923. while( pNC && !pTab ){
  95924. SrcList *pTabList = pNC->pSrcList;
  95925. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  95926. if( j<pTabList->nSrc ){
  95927. pTab = pTabList->a[j].pTab;
  95928. pS = pTabList->a[j].pSelect;
  95929. }else{
  95930. pNC = pNC->pNext;
  95931. }
  95932. }
  95933. if( pTab==0 ){
  95934. /* At one time, code such as "SELECT new.x" within a trigger would
  95935. ** cause this condition to run. Since then, we have restructured how
  95936. ** trigger code is generated and so this condition is no longer
  95937. ** possible. However, it can still be true for statements like
  95938. ** the following:
  95939. **
  95940. ** CREATE TABLE t1(col INTEGER);
  95941. ** SELECT (SELECT t1.col) FROM FROM t1;
  95942. **
  95943. ** when columnType() is called on the expression "t1.col" in the
  95944. ** sub-select. In this case, set the column type to NULL, even
  95945. ** though it should really be "INTEGER".
  95946. **
  95947. ** This is not a problem, as the column type of "t1.col" is never
  95948. ** used. When columnType() is called on the expression
  95949. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  95950. ** branch below. */
  95951. break;
  95952. }
  95953. assert( pTab && pExpr->pTab==pTab );
  95954. if( pS ){
  95955. /* The "table" is actually a sub-select or a view in the FROM clause
  95956. ** of the SELECT statement. Return the declaration type and origin
  95957. ** data for the result-set column of the sub-select.
  95958. */
  95959. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  95960. /* If iCol is less than zero, then the expression requests the
  95961. ** rowid of the sub-select or view. This expression is legal (see
  95962. ** test case misc2.2.2) - it always evaluates to NULL.
  95963. */
  95964. NameContext sNC;
  95965. Expr *p = pS->pEList->a[iCol].pExpr;
  95966. sNC.pSrcList = pS->pSrc;
  95967. sNC.pNext = pNC;
  95968. sNC.pParse = pNC->pParse;
  95969. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  95970. }
  95971. }else if( ALWAYS(pTab->pSchema) ){
  95972. /* A real table */
  95973. assert( !pS );
  95974. if( iCol<0 ) iCol = pTab->iPKey;
  95975. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  95976. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  95977. if( iCol<0 ){
  95978. zType = "INTEGER";
  95979. zOrigCol = "rowid";
  95980. }else{
  95981. zType = pTab->aCol[iCol].zType;
  95982. zOrigCol = pTab->aCol[iCol].zName;
  95983. estWidth = pTab->aCol[iCol].szEst;
  95984. }
  95985. zOrigTab = pTab->zName;
  95986. if( pNC->pParse ){
  95987. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  95988. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  95989. }
  95990. #else
  95991. if( iCol<0 ){
  95992. zType = "INTEGER";
  95993. }else{
  95994. zType = pTab->aCol[iCol].zType;
  95995. estWidth = pTab->aCol[iCol].szEst;
  95996. }
  95997. #endif
  95998. }
  95999. break;
  96000. }
  96001. #ifndef SQLITE_OMIT_SUBQUERY
  96002. case TK_SELECT: {
  96003. /* The expression is a sub-select. Return the declaration type and
  96004. ** origin info for the single column in the result set of the SELECT
  96005. ** statement.
  96006. */
  96007. NameContext sNC;
  96008. Select *pS = pExpr->x.pSelect;
  96009. Expr *p = pS->pEList->a[0].pExpr;
  96010. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  96011. sNC.pSrcList = pS->pSrc;
  96012. sNC.pNext = pNC;
  96013. sNC.pParse = pNC->pParse;
  96014. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  96015. break;
  96016. }
  96017. #endif
  96018. }
  96019. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  96020. if( pzOrigDb ){
  96021. assert( pzOrigTab && pzOrigCol );
  96022. *pzOrigDb = zOrigDb;
  96023. *pzOrigTab = zOrigTab;
  96024. *pzOrigCol = zOrigCol;
  96025. }
  96026. #endif
  96027. if( pEstWidth ) *pEstWidth = estWidth;
  96028. return zType;
  96029. }
  96030. /*
  96031. ** Generate code that will tell the VDBE the declaration types of columns
  96032. ** in the result set.
  96033. */
  96034. static void generateColumnTypes(
  96035. Parse *pParse, /* Parser context */
  96036. SrcList *pTabList, /* List of tables */
  96037. ExprList *pEList /* Expressions defining the result set */
  96038. ){
  96039. #ifndef SQLITE_OMIT_DECLTYPE
  96040. Vdbe *v = pParse->pVdbe;
  96041. int i;
  96042. NameContext sNC;
  96043. sNC.pSrcList = pTabList;
  96044. sNC.pParse = pParse;
  96045. for(i=0; i<pEList->nExpr; i++){
  96046. Expr *p = pEList->a[i].pExpr;
  96047. const char *zType;
  96048. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  96049. const char *zOrigDb = 0;
  96050. const char *zOrigTab = 0;
  96051. const char *zOrigCol = 0;
  96052. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  96053. /* The vdbe must make its own copy of the column-type and other
  96054. ** column specific strings, in case the schema is reset before this
  96055. ** virtual machine is deleted.
  96056. */
  96057. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  96058. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  96059. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  96060. #else
  96061. zType = columnType(&sNC, p, 0, 0, 0, 0);
  96062. #endif
  96063. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  96064. }
  96065. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  96066. }
  96067. /*
  96068. ** Generate code that will tell the VDBE the names of columns
  96069. ** in the result set. This information is used to provide the
  96070. ** azCol[] values in the callback.
  96071. */
  96072. static void generateColumnNames(
  96073. Parse *pParse, /* Parser context */
  96074. SrcList *pTabList, /* List of tables */
  96075. ExprList *pEList /* Expressions defining the result set */
  96076. ){
  96077. Vdbe *v = pParse->pVdbe;
  96078. int i, j;
  96079. sqlite3 *db = pParse->db;
  96080. int fullNames, shortNames;
  96081. #ifndef SQLITE_OMIT_EXPLAIN
  96082. /* If this is an EXPLAIN, skip this step */
  96083. if( pParse->explain ){
  96084. return;
  96085. }
  96086. #endif
  96087. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  96088. pParse->colNamesSet = 1;
  96089. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  96090. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  96091. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  96092. for(i=0; i<pEList->nExpr; i++){
  96093. Expr *p;
  96094. p = pEList->a[i].pExpr;
  96095. if( NEVER(p==0) ) continue;
  96096. if( pEList->a[i].zName ){
  96097. char *zName = pEList->a[i].zName;
  96098. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  96099. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  96100. Table *pTab;
  96101. char *zCol;
  96102. int iCol = p->iColumn;
  96103. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  96104. if( pTabList->a[j].iCursor==p->iTable ) break;
  96105. }
  96106. assert( j<pTabList->nSrc );
  96107. pTab = pTabList->a[j].pTab;
  96108. if( iCol<0 ) iCol = pTab->iPKey;
  96109. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  96110. if( iCol<0 ){
  96111. zCol = "rowid";
  96112. }else{
  96113. zCol = pTab->aCol[iCol].zName;
  96114. }
  96115. if( !shortNames && !fullNames ){
  96116. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  96117. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  96118. }else if( fullNames ){
  96119. char *zName = 0;
  96120. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  96121. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  96122. }else{
  96123. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  96124. }
  96125. }else{
  96126. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  96127. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  96128. }
  96129. }
  96130. generateColumnTypes(pParse, pTabList, pEList);
  96131. }
  96132. /*
  96133. ** Given a an expression list (which is really the list of expressions
  96134. ** that form the result set of a SELECT statement) compute appropriate
  96135. ** column names for a table that would hold the expression list.
  96136. **
  96137. ** All column names will be unique.
  96138. **
  96139. ** Only the column names are computed. Column.zType, Column.zColl,
  96140. ** and other fields of Column are zeroed.
  96141. **
  96142. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  96143. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  96144. */
  96145. static int selectColumnsFromExprList(
  96146. Parse *pParse, /* Parsing context */
  96147. ExprList *pEList, /* Expr list from which to derive column names */
  96148. i16 *pnCol, /* Write the number of columns here */
  96149. Column **paCol /* Write the new column list here */
  96150. ){
  96151. sqlite3 *db = pParse->db; /* Database connection */
  96152. int i, j; /* Loop counters */
  96153. int cnt; /* Index added to make the name unique */
  96154. Column *aCol, *pCol; /* For looping over result columns */
  96155. int nCol; /* Number of columns in the result set */
  96156. Expr *p; /* Expression for a single result column */
  96157. char *zName; /* Column name */
  96158. int nName; /* Size of name in zName[] */
  96159. if( pEList ){
  96160. nCol = pEList->nExpr;
  96161. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  96162. testcase( aCol==0 );
  96163. }else{
  96164. nCol = 0;
  96165. aCol = 0;
  96166. }
  96167. *pnCol = nCol;
  96168. *paCol = aCol;
  96169. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  96170. /* Get an appropriate name for the column
  96171. */
  96172. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  96173. if( (zName = pEList->a[i].zName)!=0 ){
  96174. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  96175. zName = sqlite3DbStrDup(db, zName);
  96176. }else{
  96177. Expr *pColExpr = p; /* The expression that is the result column name */
  96178. Table *pTab; /* Table associated with this expression */
  96179. while( pColExpr->op==TK_DOT ){
  96180. pColExpr = pColExpr->pRight;
  96181. assert( pColExpr!=0 );
  96182. }
  96183. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  96184. /* For columns use the column name name */
  96185. int iCol = pColExpr->iColumn;
  96186. pTab = pColExpr->pTab;
  96187. if( iCol<0 ) iCol = pTab->iPKey;
  96188. zName = sqlite3MPrintf(db, "%s",
  96189. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  96190. }else if( pColExpr->op==TK_ID ){
  96191. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  96192. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  96193. }else{
  96194. /* Use the original text of the column expression as its name */
  96195. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  96196. }
  96197. }
  96198. if( db->mallocFailed ){
  96199. sqlite3DbFree(db, zName);
  96200. break;
  96201. }
  96202. /* Make sure the column name is unique. If the name is not unique,
  96203. ** append a integer to the name so that it becomes unique.
  96204. */
  96205. nName = sqlite3Strlen30(zName);
  96206. for(j=cnt=0; j<i; j++){
  96207. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  96208. char *zNewName;
  96209. int k;
  96210. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  96211. if( zName[k]==':' ) nName = k;
  96212. zName[nName] = 0;
  96213. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  96214. sqlite3DbFree(db, zName);
  96215. zName = zNewName;
  96216. j = -1;
  96217. if( zName==0 ) break;
  96218. }
  96219. }
  96220. pCol->zName = zName;
  96221. }
  96222. if( db->mallocFailed ){
  96223. for(j=0; j<i; j++){
  96224. sqlite3DbFree(db, aCol[j].zName);
  96225. }
  96226. sqlite3DbFree(db, aCol);
  96227. *paCol = 0;
  96228. *pnCol = 0;
  96229. return SQLITE_NOMEM;
  96230. }
  96231. return SQLITE_OK;
  96232. }
  96233. /*
  96234. ** Add type and collation information to a column list based on
  96235. ** a SELECT statement.
  96236. **
  96237. ** The column list presumably came from selectColumnNamesFromExprList().
  96238. ** The column list has only names, not types or collations. This
  96239. ** routine goes through and adds the types and collations.
  96240. **
  96241. ** This routine requires that all identifiers in the SELECT
  96242. ** statement be resolved.
  96243. */
  96244. static void selectAddColumnTypeAndCollation(
  96245. Parse *pParse, /* Parsing contexts */
  96246. Table *pTab, /* Add column type information to this table */
  96247. Select *pSelect /* SELECT used to determine types and collations */
  96248. ){
  96249. sqlite3 *db = pParse->db;
  96250. NameContext sNC;
  96251. Column *pCol;
  96252. CollSeq *pColl;
  96253. int i;
  96254. Expr *p;
  96255. struct ExprList_item *a;
  96256. u64 szAll = 0;
  96257. assert( pSelect!=0 );
  96258. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  96259. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  96260. if( db->mallocFailed ) return;
  96261. memset(&sNC, 0, sizeof(sNC));
  96262. sNC.pSrcList = pSelect->pSrc;
  96263. a = pSelect->pEList->a;
  96264. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  96265. p = a[i].pExpr;
  96266. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  96267. szAll += pCol->szEst;
  96268. pCol->affinity = sqlite3ExprAffinity(p);
  96269. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  96270. pColl = sqlite3ExprCollSeq(pParse, p);
  96271. if( pColl ){
  96272. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  96273. }
  96274. }
  96275. pTab->szTabRow = sqlite3LogEst(szAll*4);
  96276. }
  96277. /*
  96278. ** Given a SELECT statement, generate a Table structure that describes
  96279. ** the result set of that SELECT.
  96280. */
  96281. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  96282. Table *pTab;
  96283. sqlite3 *db = pParse->db;
  96284. int savedFlags;
  96285. savedFlags = db->flags;
  96286. db->flags &= ~SQLITE_FullColNames;
  96287. db->flags |= SQLITE_ShortColNames;
  96288. sqlite3SelectPrep(pParse, pSelect, 0);
  96289. if( pParse->nErr ) return 0;
  96290. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  96291. db->flags = savedFlags;
  96292. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  96293. if( pTab==0 ){
  96294. return 0;
  96295. }
  96296. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  96297. ** is disabled */
  96298. assert( db->lookaside.bEnabled==0 );
  96299. pTab->nRef = 1;
  96300. pTab->zName = 0;
  96301. pTab->nRowEst = 1048576;
  96302. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  96303. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  96304. pTab->iPKey = -1;
  96305. if( db->mallocFailed ){
  96306. sqlite3DeleteTable(db, pTab);
  96307. return 0;
  96308. }
  96309. return pTab;
  96310. }
  96311. /*
  96312. ** Get a VDBE for the given parser context. Create a new one if necessary.
  96313. ** If an error occurs, return NULL and leave a message in pParse.
  96314. */
  96315. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  96316. Vdbe *v = pParse->pVdbe;
  96317. if( v==0 ){
  96318. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  96319. #ifndef SQLITE_OMIT_TRACE
  96320. if( v ){
  96321. sqlite3VdbeAddOp0(v, OP_Trace);
  96322. }
  96323. #endif
  96324. }
  96325. return v;
  96326. }
  96327. /*
  96328. ** Compute the iLimit and iOffset fields of the SELECT based on the
  96329. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  96330. ** that appear in the original SQL statement after the LIMIT and OFFSET
  96331. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  96332. ** are the integer memory register numbers for counters used to compute
  96333. ** the limit and offset. If there is no limit and/or offset, then
  96334. ** iLimit and iOffset are negative.
  96335. **
  96336. ** This routine changes the values of iLimit and iOffset only if
  96337. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  96338. ** iOffset should have been preset to appropriate default values
  96339. ** (usually but not always -1) prior to calling this routine.
  96340. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  96341. ** redefined. The UNION ALL operator uses this property to force
  96342. ** the reuse of the same limit and offset registers across multiple
  96343. ** SELECT statements.
  96344. */
  96345. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  96346. Vdbe *v = 0;
  96347. int iLimit = 0;
  96348. int iOffset;
  96349. int addr1, n;
  96350. if( p->iLimit ) return;
  96351. /*
  96352. ** "LIMIT -1" always shows all rows. There is some
  96353. ** controversy about what the correct behavior should be.
  96354. ** The current implementation interprets "LIMIT 0" to mean
  96355. ** no rows.
  96356. */
  96357. sqlite3ExprCacheClear(pParse);
  96358. assert( p->pOffset==0 || p->pLimit!=0 );
  96359. if( p->pLimit ){
  96360. p->iLimit = iLimit = ++pParse->nMem;
  96361. v = sqlite3GetVdbe(pParse);
  96362. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  96363. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  96364. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  96365. VdbeComment((v, "LIMIT counter"));
  96366. if( n==0 ){
  96367. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  96368. }else if( n>=0 && p->nSelectRow>(u64)n ){
  96369. p->nSelectRow = n;
  96370. }
  96371. }else{
  96372. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  96373. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  96374. VdbeComment((v, "LIMIT counter"));
  96375. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  96376. }
  96377. if( p->pOffset ){
  96378. p->iOffset = iOffset = ++pParse->nMem;
  96379. pParse->nMem++; /* Allocate an extra register for limit+offset */
  96380. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  96381. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  96382. VdbeComment((v, "OFFSET counter"));
  96383. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  96384. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  96385. sqlite3VdbeJumpHere(v, addr1);
  96386. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  96387. VdbeComment((v, "LIMIT+OFFSET"));
  96388. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  96389. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  96390. sqlite3VdbeJumpHere(v, addr1);
  96391. }
  96392. }
  96393. }
  96394. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  96395. /*
  96396. ** Return the appropriate collating sequence for the iCol-th column of
  96397. ** the result set for the compound-select statement "p". Return NULL if
  96398. ** the column has no default collating sequence.
  96399. **
  96400. ** The collating sequence for the compound select is taken from the
  96401. ** left-most term of the select that has a collating sequence.
  96402. */
  96403. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  96404. CollSeq *pRet;
  96405. if( p->pPrior ){
  96406. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  96407. }else{
  96408. pRet = 0;
  96409. }
  96410. assert( iCol>=0 );
  96411. if( pRet==0 && iCol<p->pEList->nExpr ){
  96412. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  96413. }
  96414. return pRet;
  96415. }
  96416. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  96417. /* Forward reference */
  96418. static int multiSelectOrderBy(
  96419. Parse *pParse, /* Parsing context */
  96420. Select *p, /* The right-most of SELECTs to be coded */
  96421. SelectDest *pDest /* What to do with query results */
  96422. );
  96423. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  96424. /*
  96425. ** This routine is called to process a compound query form from
  96426. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  96427. ** INTERSECT
  96428. **
  96429. ** "p" points to the right-most of the two queries. the query on the
  96430. ** left is p->pPrior. The left query could also be a compound query
  96431. ** in which case this routine will be called recursively.
  96432. **
  96433. ** The results of the total query are to be written into a destination
  96434. ** of type eDest with parameter iParm.
  96435. **
  96436. ** Example 1: Consider a three-way compound SQL statement.
  96437. **
  96438. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  96439. **
  96440. ** This statement is parsed up as follows:
  96441. **
  96442. ** SELECT c FROM t3
  96443. ** |
  96444. ** `-----> SELECT b FROM t2
  96445. ** |
  96446. ** `------> SELECT a FROM t1
  96447. **
  96448. ** The arrows in the diagram above represent the Select.pPrior pointer.
  96449. ** So if this routine is called with p equal to the t3 query, then
  96450. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  96451. **
  96452. ** Notice that because of the way SQLite parses compound SELECTs, the
  96453. ** individual selects always group from left to right.
  96454. */
  96455. static int multiSelect(
  96456. Parse *pParse, /* Parsing context */
  96457. Select *p, /* The right-most of SELECTs to be coded */
  96458. SelectDest *pDest /* What to do with query results */
  96459. ){
  96460. int rc = SQLITE_OK; /* Success code from a subroutine */
  96461. Select *pPrior; /* Another SELECT immediately to our left */
  96462. Vdbe *v; /* Generate code to this VDBE */
  96463. SelectDest dest; /* Alternative data destination */
  96464. Select *pDelete = 0; /* Chain of simple selects to delete */
  96465. sqlite3 *db; /* Database connection */
  96466. #ifndef SQLITE_OMIT_EXPLAIN
  96467. int iSub1; /* EQP id of left-hand query */
  96468. int iSub2; /* EQP id of right-hand query */
  96469. #endif
  96470. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  96471. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  96472. */
  96473. assert( p && p->pPrior ); /* Calling function guarantees this much */
  96474. db = pParse->db;
  96475. pPrior = p->pPrior;
  96476. assert( pPrior->pRightmost!=pPrior );
  96477. assert( pPrior->pRightmost==p->pRightmost );
  96478. dest = *pDest;
  96479. if( pPrior->pOrderBy ){
  96480. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  96481. selectOpName(p->op));
  96482. rc = 1;
  96483. goto multi_select_end;
  96484. }
  96485. if( pPrior->pLimit ){
  96486. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  96487. selectOpName(p->op));
  96488. rc = 1;
  96489. goto multi_select_end;
  96490. }
  96491. v = sqlite3GetVdbe(pParse);
  96492. assert( v!=0 ); /* The VDBE already created by calling function */
  96493. /* Create the destination temporary table if necessary
  96494. */
  96495. if( dest.eDest==SRT_EphemTab ){
  96496. assert( p->pEList );
  96497. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  96498. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  96499. dest.eDest = SRT_Table;
  96500. }
  96501. /* Make sure all SELECTs in the statement have the same number of elements
  96502. ** in their result sets.
  96503. */
  96504. assert( p->pEList && pPrior->pEList );
  96505. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  96506. if( p->selFlags & SF_Values ){
  96507. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  96508. }else{
  96509. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  96510. " do not have the same number of result columns", selectOpName(p->op));
  96511. }
  96512. rc = 1;
  96513. goto multi_select_end;
  96514. }
  96515. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  96516. */
  96517. if( p->pOrderBy ){
  96518. return multiSelectOrderBy(pParse, p, pDest);
  96519. }
  96520. /* Generate code for the left and right SELECT statements.
  96521. */
  96522. switch( p->op ){
  96523. case TK_ALL: {
  96524. int addr = 0;
  96525. int nLimit;
  96526. assert( !pPrior->pLimit );
  96527. pPrior->iLimit = p->iLimit;
  96528. pPrior->iOffset = p->iOffset;
  96529. pPrior->pLimit = p->pLimit;
  96530. pPrior->pOffset = p->pOffset;
  96531. explainSetInteger(iSub1, pParse->iNextSelectId);
  96532. rc = sqlite3Select(pParse, pPrior, &dest);
  96533. p->pLimit = 0;
  96534. p->pOffset = 0;
  96535. if( rc ){
  96536. goto multi_select_end;
  96537. }
  96538. p->pPrior = 0;
  96539. p->iLimit = pPrior->iLimit;
  96540. p->iOffset = pPrior->iOffset;
  96541. if( p->iLimit ){
  96542. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  96543. VdbeComment((v, "Jump ahead if LIMIT reached"));
  96544. }
  96545. explainSetInteger(iSub2, pParse->iNextSelectId);
  96546. rc = sqlite3Select(pParse, p, &dest);
  96547. testcase( rc!=SQLITE_OK );
  96548. pDelete = p->pPrior;
  96549. p->pPrior = pPrior;
  96550. p->nSelectRow += pPrior->nSelectRow;
  96551. if( pPrior->pLimit
  96552. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  96553. && nLimit>0 && p->nSelectRow > (u64)nLimit
  96554. ){
  96555. p->nSelectRow = nLimit;
  96556. }
  96557. if( addr ){
  96558. sqlite3VdbeJumpHere(v, addr);
  96559. }
  96560. break;
  96561. }
  96562. case TK_EXCEPT:
  96563. case TK_UNION: {
  96564. int unionTab; /* Cursor number of the temporary table holding result */
  96565. u8 op = 0; /* One of the SRT_ operations to apply to self */
  96566. int priorOp; /* The SRT_ operation to apply to prior selects */
  96567. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  96568. int addr;
  96569. SelectDest uniondest;
  96570. testcase( p->op==TK_EXCEPT );
  96571. testcase( p->op==TK_UNION );
  96572. priorOp = SRT_Union;
  96573. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  96574. /* We can reuse a temporary table generated by a SELECT to our
  96575. ** right.
  96576. */
  96577. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  96578. ** of a 3-way or more compound */
  96579. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  96580. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  96581. unionTab = dest.iSDParm;
  96582. }else{
  96583. /* We will need to create our own temporary table to hold the
  96584. ** intermediate results.
  96585. */
  96586. unionTab = pParse->nTab++;
  96587. assert( p->pOrderBy==0 );
  96588. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  96589. assert( p->addrOpenEphm[0] == -1 );
  96590. p->addrOpenEphm[0] = addr;
  96591. p->pRightmost->selFlags |= SF_UsesEphemeral;
  96592. assert( p->pEList );
  96593. }
  96594. /* Code the SELECT statements to our left
  96595. */
  96596. assert( !pPrior->pOrderBy );
  96597. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  96598. explainSetInteger(iSub1, pParse->iNextSelectId);
  96599. rc = sqlite3Select(pParse, pPrior, &uniondest);
  96600. if( rc ){
  96601. goto multi_select_end;
  96602. }
  96603. /* Code the current SELECT statement
  96604. */
  96605. if( p->op==TK_EXCEPT ){
  96606. op = SRT_Except;
  96607. }else{
  96608. assert( p->op==TK_UNION );
  96609. op = SRT_Union;
  96610. }
  96611. p->pPrior = 0;
  96612. pLimit = p->pLimit;
  96613. p->pLimit = 0;
  96614. pOffset = p->pOffset;
  96615. p->pOffset = 0;
  96616. uniondest.eDest = op;
  96617. explainSetInteger(iSub2, pParse->iNextSelectId);
  96618. rc = sqlite3Select(pParse, p, &uniondest);
  96619. testcase( rc!=SQLITE_OK );
  96620. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  96621. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  96622. sqlite3ExprListDelete(db, p->pOrderBy);
  96623. pDelete = p->pPrior;
  96624. p->pPrior = pPrior;
  96625. p->pOrderBy = 0;
  96626. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  96627. sqlite3ExprDelete(db, p->pLimit);
  96628. p->pLimit = pLimit;
  96629. p->pOffset = pOffset;
  96630. p->iLimit = 0;
  96631. p->iOffset = 0;
  96632. /* Convert the data in the temporary table into whatever form
  96633. ** it is that we currently need.
  96634. */
  96635. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  96636. if( dest.eDest!=priorOp ){
  96637. int iCont, iBreak, iStart;
  96638. assert( p->pEList );
  96639. if( dest.eDest==SRT_Output ){
  96640. Select *pFirst = p;
  96641. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  96642. generateColumnNames(pParse, 0, pFirst->pEList);
  96643. }
  96644. iBreak = sqlite3VdbeMakeLabel(v);
  96645. iCont = sqlite3VdbeMakeLabel(v);
  96646. computeLimitRegisters(pParse, p, iBreak);
  96647. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  96648. iStart = sqlite3VdbeCurrentAddr(v);
  96649. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  96650. 0, 0, &dest, iCont, iBreak);
  96651. sqlite3VdbeResolveLabel(v, iCont);
  96652. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  96653. sqlite3VdbeResolveLabel(v, iBreak);
  96654. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  96655. }
  96656. break;
  96657. }
  96658. default: assert( p->op==TK_INTERSECT ); {
  96659. int tab1, tab2;
  96660. int iCont, iBreak, iStart;
  96661. Expr *pLimit, *pOffset;
  96662. int addr;
  96663. SelectDest intersectdest;
  96664. int r1;
  96665. /* INTERSECT is different from the others since it requires
  96666. ** two temporary tables. Hence it has its own case. Begin
  96667. ** by allocating the tables we will need.
  96668. */
  96669. tab1 = pParse->nTab++;
  96670. tab2 = pParse->nTab++;
  96671. assert( p->pOrderBy==0 );
  96672. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  96673. assert( p->addrOpenEphm[0] == -1 );
  96674. p->addrOpenEphm[0] = addr;
  96675. p->pRightmost->selFlags |= SF_UsesEphemeral;
  96676. assert( p->pEList );
  96677. /* Code the SELECTs to our left into temporary table "tab1".
  96678. */
  96679. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  96680. explainSetInteger(iSub1, pParse->iNextSelectId);
  96681. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  96682. if( rc ){
  96683. goto multi_select_end;
  96684. }
  96685. /* Code the current SELECT into temporary table "tab2"
  96686. */
  96687. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  96688. assert( p->addrOpenEphm[1] == -1 );
  96689. p->addrOpenEphm[1] = addr;
  96690. p->pPrior = 0;
  96691. pLimit = p->pLimit;
  96692. p->pLimit = 0;
  96693. pOffset = p->pOffset;
  96694. p->pOffset = 0;
  96695. intersectdest.iSDParm = tab2;
  96696. explainSetInteger(iSub2, pParse->iNextSelectId);
  96697. rc = sqlite3Select(pParse, p, &intersectdest);
  96698. testcase( rc!=SQLITE_OK );
  96699. pDelete = p->pPrior;
  96700. p->pPrior = pPrior;
  96701. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  96702. sqlite3ExprDelete(db, p->pLimit);
  96703. p->pLimit = pLimit;
  96704. p->pOffset = pOffset;
  96705. /* Generate code to take the intersection of the two temporary
  96706. ** tables.
  96707. */
  96708. assert( p->pEList );
  96709. if( dest.eDest==SRT_Output ){
  96710. Select *pFirst = p;
  96711. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  96712. generateColumnNames(pParse, 0, pFirst->pEList);
  96713. }
  96714. iBreak = sqlite3VdbeMakeLabel(v);
  96715. iCont = sqlite3VdbeMakeLabel(v);
  96716. computeLimitRegisters(pParse, p, iBreak);
  96717. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  96718. r1 = sqlite3GetTempReg(pParse);
  96719. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  96720. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  96721. sqlite3ReleaseTempReg(pParse, r1);
  96722. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  96723. 0, 0, &dest, iCont, iBreak);
  96724. sqlite3VdbeResolveLabel(v, iCont);
  96725. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  96726. sqlite3VdbeResolveLabel(v, iBreak);
  96727. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  96728. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  96729. break;
  96730. }
  96731. }
  96732. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  96733. /* Compute collating sequences used by
  96734. ** temporary tables needed to implement the compound select.
  96735. ** Attach the KeyInfo structure to all temporary tables.
  96736. **
  96737. ** This section is run by the right-most SELECT statement only.
  96738. ** SELECT statements to the left always skip this part. The right-most
  96739. ** SELECT might also skip this part if it has no ORDER BY clause and
  96740. ** no temp tables are required.
  96741. */
  96742. if( p->selFlags & SF_UsesEphemeral ){
  96743. int i; /* Loop counter */
  96744. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  96745. Select *pLoop; /* For looping through SELECT statements */
  96746. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  96747. int nCol; /* Number of columns in result set */
  96748. assert( p->pRightmost==p );
  96749. nCol = p->pEList->nExpr;
  96750. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  96751. if( !pKeyInfo ){
  96752. rc = SQLITE_NOMEM;
  96753. goto multi_select_end;
  96754. }
  96755. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  96756. *apColl = multiSelectCollSeq(pParse, p, i);
  96757. if( 0==*apColl ){
  96758. *apColl = db->pDfltColl;
  96759. }
  96760. }
  96761. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  96762. for(i=0; i<2; i++){
  96763. int addr = pLoop->addrOpenEphm[i];
  96764. if( addr<0 ){
  96765. /* If [0] is unused then [1] is also unused. So we can
  96766. ** always safely abort as soon as the first unused slot is found */
  96767. assert( pLoop->addrOpenEphm[1]<0 );
  96768. break;
  96769. }
  96770. sqlite3VdbeChangeP2(v, addr, nCol);
  96771. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  96772. pLoop->addrOpenEphm[i] = -1;
  96773. }
  96774. }
  96775. sqlite3DbFree(db, pKeyInfo);
  96776. }
  96777. multi_select_end:
  96778. pDest->iSdst = dest.iSdst;
  96779. pDest->nSdst = dest.nSdst;
  96780. sqlite3SelectDelete(db, pDelete);
  96781. return rc;
  96782. }
  96783. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  96784. /*
  96785. ** Code an output subroutine for a coroutine implementation of a
  96786. ** SELECT statment.
  96787. **
  96788. ** The data to be output is contained in pIn->iSdst. There are
  96789. ** pIn->nSdst columns to be output. pDest is where the output should
  96790. ** be sent.
  96791. **
  96792. ** regReturn is the number of the register holding the subroutine
  96793. ** return address.
  96794. **
  96795. ** If regPrev>0 then it is the first register in a vector that
  96796. ** records the previous output. mem[regPrev] is a flag that is false
  96797. ** if there has been no previous output. If regPrev>0 then code is
  96798. ** generated to suppress duplicates. pKeyInfo is used for comparing
  96799. ** keys.
  96800. **
  96801. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  96802. ** iBreak.
  96803. */
  96804. static int generateOutputSubroutine(
  96805. Parse *pParse, /* Parsing context */
  96806. Select *p, /* The SELECT statement */
  96807. SelectDest *pIn, /* Coroutine supplying data */
  96808. SelectDest *pDest, /* Where to send the data */
  96809. int regReturn, /* The return address register */
  96810. int regPrev, /* Previous result register. No uniqueness if 0 */
  96811. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  96812. int p4type, /* The p4 type for pKeyInfo */
  96813. int iBreak /* Jump here if we hit the LIMIT */
  96814. ){
  96815. Vdbe *v = pParse->pVdbe;
  96816. int iContinue;
  96817. int addr;
  96818. addr = sqlite3VdbeCurrentAddr(v);
  96819. iContinue = sqlite3VdbeMakeLabel(v);
  96820. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  96821. */
  96822. if( regPrev ){
  96823. int j1, j2;
  96824. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  96825. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  96826. (char*)pKeyInfo, p4type);
  96827. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  96828. sqlite3VdbeJumpHere(v, j1);
  96829. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  96830. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  96831. }
  96832. if( pParse->db->mallocFailed ) return 0;
  96833. /* Suppress the first OFFSET entries if there is an OFFSET clause
  96834. */
  96835. codeOffset(v, p, iContinue);
  96836. switch( pDest->eDest ){
  96837. /* Store the result as data using a unique key.
  96838. */
  96839. case SRT_Table:
  96840. case SRT_EphemTab: {
  96841. int r1 = sqlite3GetTempReg(pParse);
  96842. int r2 = sqlite3GetTempReg(pParse);
  96843. testcase( pDest->eDest==SRT_Table );
  96844. testcase( pDest->eDest==SRT_EphemTab );
  96845. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  96846. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  96847. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  96848. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  96849. sqlite3ReleaseTempReg(pParse, r2);
  96850. sqlite3ReleaseTempReg(pParse, r1);
  96851. break;
  96852. }
  96853. #ifndef SQLITE_OMIT_SUBQUERY
  96854. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  96855. ** then there should be a single item on the stack. Write this
  96856. ** item into the set table with bogus data.
  96857. */
  96858. case SRT_Set: {
  96859. int r1;
  96860. assert( pIn->nSdst==1 );
  96861. pDest->affSdst =
  96862. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  96863. r1 = sqlite3GetTempReg(pParse);
  96864. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  96865. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  96866. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  96867. sqlite3ReleaseTempReg(pParse, r1);
  96868. break;
  96869. }
  96870. #if 0 /* Never occurs on an ORDER BY query */
  96871. /* If any row exist in the result set, record that fact and abort.
  96872. */
  96873. case SRT_Exists: {
  96874. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  96875. /* The LIMIT clause will terminate the loop for us */
  96876. break;
  96877. }
  96878. #endif
  96879. /* If this is a scalar select that is part of an expression, then
  96880. ** store the results in the appropriate memory cell and break out
  96881. ** of the scan loop.
  96882. */
  96883. case SRT_Mem: {
  96884. assert( pIn->nSdst==1 );
  96885. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  96886. /* The LIMIT clause will jump out of the loop for us */
  96887. break;
  96888. }
  96889. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  96890. /* The results are stored in a sequence of registers
  96891. ** starting at pDest->iSdst. Then the co-routine yields.
  96892. */
  96893. case SRT_Coroutine: {
  96894. if( pDest->iSdst==0 ){
  96895. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  96896. pDest->nSdst = pIn->nSdst;
  96897. }
  96898. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  96899. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  96900. break;
  96901. }
  96902. /* If none of the above, then the result destination must be
  96903. ** SRT_Output. This routine is never called with any other
  96904. ** destination other than the ones handled above or SRT_Output.
  96905. **
  96906. ** For SRT_Output, results are stored in a sequence of registers.
  96907. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  96908. ** return the next row of result.
  96909. */
  96910. default: {
  96911. assert( pDest->eDest==SRT_Output );
  96912. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  96913. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  96914. break;
  96915. }
  96916. }
  96917. /* Jump to the end of the loop if the LIMIT is reached.
  96918. */
  96919. if( p->iLimit ){
  96920. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  96921. }
  96922. /* Generate the subroutine return
  96923. */
  96924. sqlite3VdbeResolveLabel(v, iContinue);
  96925. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  96926. return addr;
  96927. }
  96928. /*
  96929. ** Alternative compound select code generator for cases when there
  96930. ** is an ORDER BY clause.
  96931. **
  96932. ** We assume a query of the following form:
  96933. **
  96934. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  96935. **
  96936. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  96937. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  96938. ** co-routines. Then run the co-routines in parallel and merge the results
  96939. ** into the output. In addition to the two coroutines (called selectA and
  96940. ** selectB) there are 7 subroutines:
  96941. **
  96942. ** outA: Move the output of the selectA coroutine into the output
  96943. ** of the compound query.
  96944. **
  96945. ** outB: Move the output of the selectB coroutine into the output
  96946. ** of the compound query. (Only generated for UNION and
  96947. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  96948. ** appears only in B.)
  96949. **
  96950. ** AltB: Called when there is data from both coroutines and A<B.
  96951. **
  96952. ** AeqB: Called when there is data from both coroutines and A==B.
  96953. **
  96954. ** AgtB: Called when there is data from both coroutines and A>B.
  96955. **
  96956. ** EofA: Called when data is exhausted from selectA.
  96957. **
  96958. ** EofB: Called when data is exhausted from selectB.
  96959. **
  96960. ** The implementation of the latter five subroutines depend on which
  96961. ** <operator> is used:
  96962. **
  96963. **
  96964. ** UNION ALL UNION EXCEPT INTERSECT
  96965. ** ------------- ----------------- -------------- -----------------
  96966. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  96967. **
  96968. ** AeqB: outA, nextA nextA nextA outA, nextA
  96969. **
  96970. ** AgtB: outB, nextB outB, nextB nextB nextB
  96971. **
  96972. ** EofA: outB, nextB outB, nextB halt halt
  96973. **
  96974. ** EofB: outA, nextA outA, nextA outA, nextA halt
  96975. **
  96976. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  96977. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  96978. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  96979. ** following nextX causes a jump to the end of the select processing.
  96980. **
  96981. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  96982. ** within the output subroutine. The regPrev register set holds the previously
  96983. ** output value. A comparison is made against this value and the output
  96984. ** is skipped if the next results would be the same as the previous.
  96985. **
  96986. ** The implementation plan is to implement the two coroutines and seven
  96987. ** subroutines first, then put the control logic at the bottom. Like this:
  96988. **
  96989. ** goto Init
  96990. ** coA: coroutine for left query (A)
  96991. ** coB: coroutine for right query (B)
  96992. ** outA: output one row of A
  96993. ** outB: output one row of B (UNION and UNION ALL only)
  96994. ** EofA: ...
  96995. ** EofB: ...
  96996. ** AltB: ...
  96997. ** AeqB: ...
  96998. ** AgtB: ...
  96999. ** Init: initialize coroutine registers
  97000. ** yield coA
  97001. ** if eof(A) goto EofA
  97002. ** yield coB
  97003. ** if eof(B) goto EofB
  97004. ** Cmpr: Compare A, B
  97005. ** Jump AltB, AeqB, AgtB
  97006. ** End: ...
  97007. **
  97008. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  97009. ** actually called using Gosub and they do not Return. EofA and EofB loop
  97010. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  97011. ** and AgtB jump to either L2 or to one of EofA or EofB.
  97012. */
  97013. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  97014. static int multiSelectOrderBy(
  97015. Parse *pParse, /* Parsing context */
  97016. Select *p, /* The right-most of SELECTs to be coded */
  97017. SelectDest *pDest /* What to do with query results */
  97018. ){
  97019. int i, j; /* Loop counters */
  97020. Select *pPrior; /* Another SELECT immediately to our left */
  97021. Vdbe *v; /* Generate code to this VDBE */
  97022. SelectDest destA; /* Destination for coroutine A */
  97023. SelectDest destB; /* Destination for coroutine B */
  97024. int regAddrA; /* Address register for select-A coroutine */
  97025. int regEofA; /* Flag to indicate when select-A is complete */
  97026. int regAddrB; /* Address register for select-B coroutine */
  97027. int regEofB; /* Flag to indicate when select-B is complete */
  97028. int addrSelectA; /* Address of the select-A coroutine */
  97029. int addrSelectB; /* Address of the select-B coroutine */
  97030. int regOutA; /* Address register for the output-A subroutine */
  97031. int regOutB; /* Address register for the output-B subroutine */
  97032. int addrOutA; /* Address of the output-A subroutine */
  97033. int addrOutB = 0; /* Address of the output-B subroutine */
  97034. int addrEofA; /* Address of the select-A-exhausted subroutine */
  97035. int addrEofB; /* Address of the select-B-exhausted subroutine */
  97036. int addrAltB; /* Address of the A<B subroutine */
  97037. int addrAeqB; /* Address of the A==B subroutine */
  97038. int addrAgtB; /* Address of the A>B subroutine */
  97039. int regLimitA; /* Limit register for select-A */
  97040. int regLimitB; /* Limit register for select-A */
  97041. int regPrev; /* A range of registers to hold previous output */
  97042. int savedLimit; /* Saved value of p->iLimit */
  97043. int savedOffset; /* Saved value of p->iOffset */
  97044. int labelCmpr; /* Label for the start of the merge algorithm */
  97045. int labelEnd; /* Label for the end of the overall SELECT stmt */
  97046. int j1; /* Jump instructions that get retargetted */
  97047. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  97048. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  97049. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  97050. sqlite3 *db; /* Database connection */
  97051. ExprList *pOrderBy; /* The ORDER BY clause */
  97052. int nOrderBy; /* Number of terms in the ORDER BY clause */
  97053. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  97054. #ifndef SQLITE_OMIT_EXPLAIN
  97055. int iSub1; /* EQP id of left-hand query */
  97056. int iSub2; /* EQP id of right-hand query */
  97057. #endif
  97058. assert( p->pOrderBy!=0 );
  97059. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  97060. db = pParse->db;
  97061. v = pParse->pVdbe;
  97062. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  97063. labelEnd = sqlite3VdbeMakeLabel(v);
  97064. labelCmpr = sqlite3VdbeMakeLabel(v);
  97065. /* Patch up the ORDER BY clause
  97066. */
  97067. op = p->op;
  97068. pPrior = p->pPrior;
  97069. assert( pPrior->pOrderBy==0 );
  97070. pOrderBy = p->pOrderBy;
  97071. assert( pOrderBy );
  97072. nOrderBy = pOrderBy->nExpr;
  97073. /* For operators other than UNION ALL we have to make sure that
  97074. ** the ORDER BY clause covers every term of the result set. Add
  97075. ** terms to the ORDER BY clause as necessary.
  97076. */
  97077. if( op!=TK_ALL ){
  97078. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  97079. struct ExprList_item *pItem;
  97080. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  97081. assert( pItem->iOrderByCol>0 );
  97082. if( pItem->iOrderByCol==i ) break;
  97083. }
  97084. if( j==nOrderBy ){
  97085. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  97086. if( pNew==0 ) return SQLITE_NOMEM;
  97087. pNew->flags |= EP_IntValue;
  97088. pNew->u.iValue = i;
  97089. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  97090. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  97091. }
  97092. }
  97093. }
  97094. /* Compute the comparison permutation and keyinfo that is used with
  97095. ** the permutation used to determine if the next
  97096. ** row of results comes from selectA or selectB. Also add explicit
  97097. ** collations to the ORDER BY clause terms so that when the subqueries
  97098. ** to the right and the left are evaluated, they use the correct
  97099. ** collation.
  97100. */
  97101. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  97102. if( aPermute ){
  97103. struct ExprList_item *pItem;
  97104. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  97105. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  97106. aPermute[i] = pItem->iOrderByCol - 1;
  97107. }
  97108. pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  97109. if( pKeyMerge ){
  97110. for(i=0; i<nOrderBy; i++){
  97111. CollSeq *pColl;
  97112. Expr *pTerm = pOrderBy->a[i].pExpr;
  97113. if( pTerm->flags & EP_Collate ){
  97114. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  97115. }else{
  97116. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  97117. if( pColl==0 ) pColl = db->pDfltColl;
  97118. pOrderBy->a[i].pExpr =
  97119. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  97120. }
  97121. pKeyMerge->aColl[i] = pColl;
  97122. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  97123. }
  97124. }
  97125. }else{
  97126. pKeyMerge = 0;
  97127. }
  97128. /* Reattach the ORDER BY clause to the query.
  97129. */
  97130. p->pOrderBy = pOrderBy;
  97131. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  97132. /* Allocate a range of temporary registers and the KeyInfo needed
  97133. ** for the logic that removes duplicate result rows when the
  97134. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  97135. */
  97136. if( op==TK_ALL ){
  97137. regPrev = 0;
  97138. }else{
  97139. int nExpr = p->pEList->nExpr;
  97140. assert( nOrderBy>=nExpr || db->mallocFailed );
  97141. regPrev = pParse->nMem+1;
  97142. pParse->nMem += nExpr+1;
  97143. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  97144. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  97145. if( pKeyDup ){
  97146. for(i=0; i<nExpr; i++){
  97147. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  97148. pKeyDup->aSortOrder[i] = 0;
  97149. }
  97150. }
  97151. }
  97152. /* Separate the left and the right query from one another
  97153. */
  97154. p->pPrior = 0;
  97155. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  97156. if( pPrior->pPrior==0 ){
  97157. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  97158. }
  97159. /* Compute the limit registers */
  97160. computeLimitRegisters(pParse, p, labelEnd);
  97161. if( p->iLimit && op==TK_ALL ){
  97162. regLimitA = ++pParse->nMem;
  97163. regLimitB = ++pParse->nMem;
  97164. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  97165. regLimitA);
  97166. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  97167. }else{
  97168. regLimitA = regLimitB = 0;
  97169. }
  97170. sqlite3ExprDelete(db, p->pLimit);
  97171. p->pLimit = 0;
  97172. sqlite3ExprDelete(db, p->pOffset);
  97173. p->pOffset = 0;
  97174. regAddrA = ++pParse->nMem;
  97175. regEofA = ++pParse->nMem;
  97176. regAddrB = ++pParse->nMem;
  97177. regEofB = ++pParse->nMem;
  97178. regOutA = ++pParse->nMem;
  97179. regOutB = ++pParse->nMem;
  97180. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  97181. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  97182. /* Jump past the various subroutines and coroutines to the main
  97183. ** merge loop
  97184. */
  97185. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  97186. addrSelectA = sqlite3VdbeCurrentAddr(v);
  97187. /* Generate a coroutine to evaluate the SELECT statement to the
  97188. ** left of the compound operator - the "A" select.
  97189. */
  97190. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  97191. pPrior->iLimit = regLimitA;
  97192. explainSetInteger(iSub1, pParse->iNextSelectId);
  97193. sqlite3Select(pParse, pPrior, &destA);
  97194. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  97195. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97196. VdbeNoopComment((v, "End coroutine for left SELECT"));
  97197. /* Generate a coroutine to evaluate the SELECT statement on
  97198. ** the right - the "B" select
  97199. */
  97200. addrSelectB = sqlite3VdbeCurrentAddr(v);
  97201. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  97202. savedLimit = p->iLimit;
  97203. savedOffset = p->iOffset;
  97204. p->iLimit = regLimitB;
  97205. p->iOffset = 0;
  97206. explainSetInteger(iSub2, pParse->iNextSelectId);
  97207. sqlite3Select(pParse, p, &destB);
  97208. p->iLimit = savedLimit;
  97209. p->iOffset = savedOffset;
  97210. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  97211. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97212. VdbeNoopComment((v, "End coroutine for right SELECT"));
  97213. /* Generate a subroutine that outputs the current row of the A
  97214. ** select as the next output row of the compound select.
  97215. */
  97216. VdbeNoopComment((v, "Output routine for A"));
  97217. addrOutA = generateOutputSubroutine(pParse,
  97218. p, &destA, pDest, regOutA,
  97219. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  97220. /* Generate a subroutine that outputs the current row of the B
  97221. ** select as the next output row of the compound select.
  97222. */
  97223. if( op==TK_ALL || op==TK_UNION ){
  97224. VdbeNoopComment((v, "Output routine for B"));
  97225. addrOutB = generateOutputSubroutine(pParse,
  97226. p, &destB, pDest, regOutB,
  97227. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  97228. }
  97229. /* Generate a subroutine to run when the results from select A
  97230. ** are exhausted and only data in select B remains.
  97231. */
  97232. VdbeNoopComment((v, "eof-A subroutine"));
  97233. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  97234. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  97235. }else{
  97236. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  97237. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  97238. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97239. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  97240. p->nSelectRow += pPrior->nSelectRow;
  97241. }
  97242. /* Generate a subroutine to run when the results from select B
  97243. ** are exhausted and only data in select A remains.
  97244. */
  97245. if( op==TK_INTERSECT ){
  97246. addrEofB = addrEofA;
  97247. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  97248. }else{
  97249. VdbeNoopComment((v, "eof-B subroutine"));
  97250. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  97251. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  97252. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97253. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  97254. }
  97255. /* Generate code to handle the case of A<B
  97256. */
  97257. VdbeNoopComment((v, "A-lt-B subroutine"));
  97258. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  97259. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97260. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97261. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97262. /* Generate code to handle the case of A==B
  97263. */
  97264. if( op==TK_ALL ){
  97265. addrAeqB = addrAltB;
  97266. }else if( op==TK_INTERSECT ){
  97267. addrAeqB = addrAltB;
  97268. addrAltB++;
  97269. }else{
  97270. VdbeNoopComment((v, "A-eq-B subroutine"));
  97271. addrAeqB =
  97272. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97273. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97274. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97275. }
  97276. /* Generate code to handle the case of A>B
  97277. */
  97278. VdbeNoopComment((v, "A-gt-B subroutine"));
  97279. addrAgtB = sqlite3VdbeCurrentAddr(v);
  97280. if( op==TK_ALL || op==TK_UNION ){
  97281. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  97282. }
  97283. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97284. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  97285. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97286. /* This code runs once to initialize everything.
  97287. */
  97288. sqlite3VdbeJumpHere(v, j1);
  97289. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  97290. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  97291. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  97292. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  97293. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97294. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  97295. /* Implement the main merge loop
  97296. */
  97297. sqlite3VdbeResolveLabel(v, labelCmpr);
  97298. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  97299. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  97300. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  97301. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  97302. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  97303. /* Jump to the this point in order to terminate the query.
  97304. */
  97305. sqlite3VdbeResolveLabel(v, labelEnd);
  97306. /* Set the number of output columns
  97307. */
  97308. if( pDest->eDest==SRT_Output ){
  97309. Select *pFirst = pPrior;
  97310. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  97311. generateColumnNames(pParse, 0, pFirst->pEList);
  97312. }
  97313. /* Reassembly the compound query so that it will be freed correctly
  97314. ** by the calling function */
  97315. if( p->pPrior ){
  97316. sqlite3SelectDelete(db, p->pPrior);
  97317. }
  97318. p->pPrior = pPrior;
  97319. /*** TBD: Insert subroutine calls to close cursors on incomplete
  97320. **** subqueries ****/
  97321. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  97322. return SQLITE_OK;
  97323. }
  97324. #endif
  97325. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  97326. /* Forward Declarations */
  97327. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  97328. static void substSelect(sqlite3*, Select *, int, ExprList *);
  97329. /*
  97330. ** Scan through the expression pExpr. Replace every reference to
  97331. ** a column in table number iTable with a copy of the iColumn-th
  97332. ** entry in pEList. (But leave references to the ROWID column
  97333. ** unchanged.)
  97334. **
  97335. ** This routine is part of the flattening procedure. A subquery
  97336. ** whose result set is defined by pEList appears as entry in the
  97337. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  97338. ** FORM clause entry is iTable. This routine make the necessary
  97339. ** changes to pExpr so that it refers directly to the source table
  97340. ** of the subquery rather the result set of the subquery.
  97341. */
  97342. static Expr *substExpr(
  97343. sqlite3 *db, /* Report malloc errors to this connection */
  97344. Expr *pExpr, /* Expr in which substitution occurs */
  97345. int iTable, /* Table to be substituted */
  97346. ExprList *pEList /* Substitute expressions */
  97347. ){
  97348. if( pExpr==0 ) return 0;
  97349. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  97350. if( pExpr->iColumn<0 ){
  97351. pExpr->op = TK_NULL;
  97352. }else{
  97353. Expr *pNew;
  97354. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  97355. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  97356. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  97357. sqlite3ExprDelete(db, pExpr);
  97358. pExpr = pNew;
  97359. }
  97360. }else{
  97361. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  97362. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  97363. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  97364. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  97365. }else{
  97366. substExprList(db, pExpr->x.pList, iTable, pEList);
  97367. }
  97368. }
  97369. return pExpr;
  97370. }
  97371. static void substExprList(
  97372. sqlite3 *db, /* Report malloc errors here */
  97373. ExprList *pList, /* List to scan and in which to make substitutes */
  97374. int iTable, /* Table to be substituted */
  97375. ExprList *pEList /* Substitute values */
  97376. ){
  97377. int i;
  97378. if( pList==0 ) return;
  97379. for(i=0; i<pList->nExpr; i++){
  97380. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  97381. }
  97382. }
  97383. static void substSelect(
  97384. sqlite3 *db, /* Report malloc errors here */
  97385. Select *p, /* SELECT statement in which to make substitutions */
  97386. int iTable, /* Table to be replaced */
  97387. ExprList *pEList /* Substitute values */
  97388. ){
  97389. SrcList *pSrc;
  97390. struct SrcList_item *pItem;
  97391. int i;
  97392. if( !p ) return;
  97393. substExprList(db, p->pEList, iTable, pEList);
  97394. substExprList(db, p->pGroupBy, iTable, pEList);
  97395. substExprList(db, p->pOrderBy, iTable, pEList);
  97396. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  97397. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  97398. substSelect(db, p->pPrior, iTable, pEList);
  97399. pSrc = p->pSrc;
  97400. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  97401. if( ALWAYS(pSrc) ){
  97402. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  97403. substSelect(db, pItem->pSelect, iTable, pEList);
  97404. }
  97405. }
  97406. }
  97407. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  97408. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  97409. /*
  97410. ** This routine attempts to flatten subqueries as a performance optimization.
  97411. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  97412. **
  97413. ** To understand the concept of flattening, consider the following
  97414. ** query:
  97415. **
  97416. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  97417. **
  97418. ** The default way of implementing this query is to execute the
  97419. ** subquery first and store the results in a temporary table, then
  97420. ** run the outer query on that temporary table. This requires two
  97421. ** passes over the data. Furthermore, because the temporary table
  97422. ** has no indices, the WHERE clause on the outer query cannot be
  97423. ** optimized.
  97424. **
  97425. ** This routine attempts to rewrite queries such as the above into
  97426. ** a single flat select, like this:
  97427. **
  97428. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  97429. **
  97430. ** The code generated for this simpification gives the same result
  97431. ** but only has to scan the data once. And because indices might
  97432. ** exist on the table t1, a complete scan of the data might be
  97433. ** avoided.
  97434. **
  97435. ** Flattening is only attempted if all of the following are true:
  97436. **
  97437. ** (1) The subquery and the outer query do not both use aggregates.
  97438. **
  97439. ** (2) The subquery is not an aggregate or the outer query is not a join.
  97440. **
  97441. ** (3) The subquery is not the right operand of a left outer join
  97442. ** (Originally ticket #306. Strengthened by ticket #3300)
  97443. **
  97444. ** (4) The subquery is not DISTINCT.
  97445. **
  97446. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  97447. ** sub-queries that were excluded from this optimization. Restriction
  97448. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  97449. **
  97450. ** (6) The subquery does not use aggregates or the outer query is not
  97451. ** DISTINCT.
  97452. **
  97453. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  97454. ** A FROM clause, consider adding a FROM close with the special
  97455. ** table sqlite_once that consists of a single row containing a
  97456. ** single NULL.
  97457. **
  97458. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  97459. **
  97460. ** (9) The subquery does not use LIMIT or the outer query does not use
  97461. ** aggregates.
  97462. **
  97463. ** (10) The subquery does not use aggregates or the outer query does not
  97464. ** use LIMIT.
  97465. **
  97466. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  97467. **
  97468. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  97469. ** a separate restriction deriving from ticket #350.
  97470. **
  97471. ** (13) The subquery and outer query do not both use LIMIT.
  97472. **
  97473. ** (14) The subquery does not use OFFSET.
  97474. **
  97475. ** (15) The outer query is not part of a compound select or the
  97476. ** subquery does not have a LIMIT clause.
  97477. ** (See ticket #2339 and ticket [02a8e81d44]).
  97478. **
  97479. ** (16) The outer query is not an aggregate or the subquery does
  97480. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  97481. ** until we introduced the group_concat() function.
  97482. **
  97483. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  97484. ** compound clause made up entirely of non-aggregate queries, and
  97485. ** the parent query:
  97486. **
  97487. ** * is not itself part of a compound select,
  97488. ** * is not an aggregate or DISTINCT query, and
  97489. ** * is not a join
  97490. **
  97491. ** The parent and sub-query may contain WHERE clauses. Subject to
  97492. ** rules (11), (13) and (14), they may also contain ORDER BY,
  97493. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  97494. ** operator other than UNION ALL because all the other compound
  97495. ** operators have an implied DISTINCT which is disallowed by
  97496. ** restriction (4).
  97497. **
  97498. ** Also, each component of the sub-query must return the same number
  97499. ** of result columns. This is actually a requirement for any compound
  97500. ** SELECT statement, but all the code here does is make sure that no
  97501. ** such (illegal) sub-query is flattened. The caller will detect the
  97502. ** syntax error and return a detailed message.
  97503. **
  97504. ** (18) If the sub-query is a compound select, then all terms of the
  97505. ** ORDER by clause of the parent must be simple references to
  97506. ** columns of the sub-query.
  97507. **
  97508. ** (19) The subquery does not use LIMIT or the outer query does not
  97509. ** have a WHERE clause.
  97510. **
  97511. ** (20) If the sub-query is a compound select, then it must not use
  97512. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  97513. ** somewhat by saying that the terms of the ORDER BY clause must
  97514. ** appear as unmodified result columns in the outer query. But we
  97515. ** have other optimizations in mind to deal with that case.
  97516. **
  97517. ** (21) The subquery does not use LIMIT or the outer query is not
  97518. ** DISTINCT. (See ticket [752e1646fc]).
  97519. **
  97520. ** In this routine, the "p" parameter is a pointer to the outer query.
  97521. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  97522. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  97523. **
  97524. ** If flattening is not attempted, this routine is a no-op and returns 0.
  97525. ** If flattening is attempted this routine returns 1.
  97526. **
  97527. ** All of the expression analysis must occur on both the outer query and
  97528. ** the subquery before this routine runs.
  97529. */
  97530. static int flattenSubquery(
  97531. Parse *pParse, /* Parsing context */
  97532. Select *p, /* The parent or outer SELECT statement */
  97533. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  97534. int isAgg, /* True if outer SELECT uses aggregate functions */
  97535. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  97536. ){
  97537. const char *zSavedAuthContext = pParse->zAuthContext;
  97538. Select *pParent;
  97539. Select *pSub; /* The inner query or "subquery" */
  97540. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  97541. SrcList *pSrc; /* The FROM clause of the outer query */
  97542. SrcList *pSubSrc; /* The FROM clause of the subquery */
  97543. ExprList *pList; /* The result set of the outer query */
  97544. int iParent; /* VDBE cursor number of the pSub result set temp table */
  97545. int i; /* Loop counter */
  97546. Expr *pWhere; /* The WHERE clause */
  97547. struct SrcList_item *pSubitem; /* The subquery */
  97548. sqlite3 *db = pParse->db;
  97549. /* Check to see if flattening is permitted. Return 0 if not.
  97550. */
  97551. assert( p!=0 );
  97552. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  97553. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  97554. pSrc = p->pSrc;
  97555. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  97556. pSubitem = &pSrc->a[iFrom];
  97557. iParent = pSubitem->iCursor;
  97558. pSub = pSubitem->pSelect;
  97559. assert( pSub!=0 );
  97560. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  97561. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  97562. pSubSrc = pSub->pSrc;
  97563. assert( pSubSrc );
  97564. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  97565. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  97566. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  97567. ** became arbitrary expressions, we were forced to add restrictions (13)
  97568. ** and (14). */
  97569. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  97570. if( pSub->pOffset ) return 0; /* Restriction (14) */
  97571. if( p->pRightmost && pSub->pLimit ){
  97572. return 0; /* Restriction (15) */
  97573. }
  97574. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  97575. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  97576. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  97577. return 0; /* Restrictions (8)(9) */
  97578. }
  97579. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  97580. return 0; /* Restriction (6) */
  97581. }
  97582. if( p->pOrderBy && pSub->pOrderBy ){
  97583. return 0; /* Restriction (11) */
  97584. }
  97585. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  97586. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  97587. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  97588. return 0; /* Restriction (21) */
  97589. }
  97590. /* OBSOLETE COMMENT 1:
  97591. ** Restriction 3: If the subquery is a join, make sure the subquery is
  97592. ** not used as the right operand of an outer join. Examples of why this
  97593. ** is not allowed:
  97594. **
  97595. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  97596. **
  97597. ** If we flatten the above, we would get
  97598. **
  97599. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  97600. **
  97601. ** which is not at all the same thing.
  97602. **
  97603. ** OBSOLETE COMMENT 2:
  97604. ** Restriction 12: If the subquery is the right operand of a left outer
  97605. ** join, make sure the subquery has no WHERE clause.
  97606. ** An examples of why this is not allowed:
  97607. **
  97608. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  97609. **
  97610. ** If we flatten the above, we would get
  97611. **
  97612. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  97613. **
  97614. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  97615. ** effectively converts the OUTER JOIN into an INNER JOIN.
  97616. **
  97617. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  97618. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  97619. ** is fraught with danger. Best to avoid the whole thing. If the
  97620. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  97621. */
  97622. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  97623. return 0;
  97624. }
  97625. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  97626. ** use only the UNION ALL operator. And none of the simple select queries
  97627. ** that make up the compound SELECT are allowed to be aggregate or distinct
  97628. ** queries.
  97629. */
  97630. if( pSub->pPrior ){
  97631. if( pSub->pOrderBy ){
  97632. return 0; /* Restriction 20 */
  97633. }
  97634. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  97635. return 0;
  97636. }
  97637. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  97638. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  97639. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  97640. assert( pSub->pSrc!=0 );
  97641. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  97642. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  97643. || pSub1->pSrc->nSrc<1
  97644. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  97645. ){
  97646. return 0;
  97647. }
  97648. testcase( pSub1->pSrc->nSrc>1 );
  97649. }
  97650. /* Restriction 18. */
  97651. if( p->pOrderBy ){
  97652. int ii;
  97653. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  97654. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  97655. }
  97656. }
  97657. }
  97658. /***** If we reach this point, flattening is permitted. *****/
  97659. /* Authorize the subquery */
  97660. pParse->zAuthContext = pSubitem->zName;
  97661. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  97662. testcase( i==SQLITE_DENY );
  97663. pParse->zAuthContext = zSavedAuthContext;
  97664. /* If the sub-query is a compound SELECT statement, then (by restrictions
  97665. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  97666. ** be of the form:
  97667. **
  97668. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  97669. **
  97670. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  97671. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  97672. ** OFFSET clauses and joins them to the left-hand-side of the original
  97673. ** using UNION ALL operators. In this case N is the number of simple
  97674. ** select statements in the compound sub-query.
  97675. **
  97676. ** Example:
  97677. **
  97678. ** SELECT a+1 FROM (
  97679. ** SELECT x FROM tab
  97680. ** UNION ALL
  97681. ** SELECT y FROM tab
  97682. ** UNION ALL
  97683. ** SELECT abs(z*2) FROM tab2
  97684. ** ) WHERE a!=5 ORDER BY 1
  97685. **
  97686. ** Transformed into:
  97687. **
  97688. ** SELECT x+1 FROM tab WHERE x+1!=5
  97689. ** UNION ALL
  97690. ** SELECT y+1 FROM tab WHERE y+1!=5
  97691. ** UNION ALL
  97692. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  97693. ** ORDER BY 1
  97694. **
  97695. ** We call this the "compound-subquery flattening".
  97696. */
  97697. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  97698. Select *pNew;
  97699. ExprList *pOrderBy = p->pOrderBy;
  97700. Expr *pLimit = p->pLimit;
  97701. Expr *pOffset = p->pOffset;
  97702. Select *pPrior = p->pPrior;
  97703. p->pOrderBy = 0;
  97704. p->pSrc = 0;
  97705. p->pPrior = 0;
  97706. p->pLimit = 0;
  97707. p->pOffset = 0;
  97708. pNew = sqlite3SelectDup(db, p, 0);
  97709. p->pOffset = pOffset;
  97710. p->pLimit = pLimit;
  97711. p->pOrderBy = pOrderBy;
  97712. p->pSrc = pSrc;
  97713. p->op = TK_ALL;
  97714. p->pRightmost = 0;
  97715. if( pNew==0 ){
  97716. pNew = pPrior;
  97717. }else{
  97718. pNew->pPrior = pPrior;
  97719. pNew->pRightmost = 0;
  97720. }
  97721. p->pPrior = pNew;
  97722. if( db->mallocFailed ) return 1;
  97723. }
  97724. /* Begin flattening the iFrom-th entry of the FROM clause
  97725. ** in the outer query.
  97726. */
  97727. pSub = pSub1 = pSubitem->pSelect;
  97728. /* Delete the transient table structure associated with the
  97729. ** subquery
  97730. */
  97731. sqlite3DbFree(db, pSubitem->zDatabase);
  97732. sqlite3DbFree(db, pSubitem->zName);
  97733. sqlite3DbFree(db, pSubitem->zAlias);
  97734. pSubitem->zDatabase = 0;
  97735. pSubitem->zName = 0;
  97736. pSubitem->zAlias = 0;
  97737. pSubitem->pSelect = 0;
  97738. /* Defer deleting the Table object associated with the
  97739. ** subquery until code generation is
  97740. ** complete, since there may still exist Expr.pTab entries that
  97741. ** refer to the subquery even after flattening. Ticket #3346.
  97742. **
  97743. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  97744. */
  97745. if( ALWAYS(pSubitem->pTab!=0) ){
  97746. Table *pTabToDel = pSubitem->pTab;
  97747. if( pTabToDel->nRef==1 ){
  97748. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97749. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  97750. pToplevel->pZombieTab = pTabToDel;
  97751. }else{
  97752. pTabToDel->nRef--;
  97753. }
  97754. pSubitem->pTab = 0;
  97755. }
  97756. /* The following loop runs once for each term in a compound-subquery
  97757. ** flattening (as described above). If we are doing a different kind
  97758. ** of flattening - a flattening other than a compound-subquery flattening -
  97759. ** then this loop only runs once.
  97760. **
  97761. ** This loop moves all of the FROM elements of the subquery into the
  97762. ** the FROM clause of the outer query. Before doing this, remember
  97763. ** the cursor number for the original outer query FROM element in
  97764. ** iParent. The iParent cursor will never be used. Subsequent code
  97765. ** will scan expressions looking for iParent references and replace
  97766. ** those references with expressions that resolve to the subquery FROM
  97767. ** elements we are now copying in.
  97768. */
  97769. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  97770. int nSubSrc;
  97771. u8 jointype = 0;
  97772. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  97773. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  97774. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  97775. if( pSrc ){
  97776. assert( pParent==p ); /* First time through the loop */
  97777. jointype = pSubitem->jointype;
  97778. }else{
  97779. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  97780. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  97781. if( pSrc==0 ){
  97782. assert( db->mallocFailed );
  97783. break;
  97784. }
  97785. }
  97786. /* The subquery uses a single slot of the FROM clause of the outer
  97787. ** query. If the subquery has more than one element in its FROM clause,
  97788. ** then expand the outer query to make space for it to hold all elements
  97789. ** of the subquery.
  97790. **
  97791. ** Example:
  97792. **
  97793. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  97794. **
  97795. ** The outer query has 3 slots in its FROM clause. One slot of the
  97796. ** outer query (the middle slot) is used by the subquery. The next
  97797. ** block of code will expand the out query to 4 slots. The middle
  97798. ** slot is expanded to two slots in order to make space for the
  97799. ** two elements in the FROM clause of the subquery.
  97800. */
  97801. if( nSubSrc>1 ){
  97802. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  97803. if( db->mallocFailed ){
  97804. break;
  97805. }
  97806. }
  97807. /* Transfer the FROM clause terms from the subquery into the
  97808. ** outer query.
  97809. */
  97810. for(i=0; i<nSubSrc; i++){
  97811. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  97812. pSrc->a[i+iFrom] = pSubSrc->a[i];
  97813. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  97814. }
  97815. pSrc->a[iFrom].jointype = jointype;
  97816. /* Now begin substituting subquery result set expressions for
  97817. ** references to the iParent in the outer query.
  97818. **
  97819. ** Example:
  97820. **
  97821. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  97822. ** \ \_____________ subquery __________/ /
  97823. ** \_____________________ outer query ______________________________/
  97824. **
  97825. ** We look at every expression in the outer query and every place we see
  97826. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  97827. */
  97828. pList = pParent->pEList;
  97829. for(i=0; i<pList->nExpr; i++){
  97830. if( pList->a[i].zName==0 ){
  97831. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  97832. sqlite3Dequote(zName);
  97833. pList->a[i].zName = zName;
  97834. }
  97835. }
  97836. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  97837. if( isAgg ){
  97838. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  97839. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  97840. }
  97841. if( pSub->pOrderBy ){
  97842. assert( pParent->pOrderBy==0 );
  97843. pParent->pOrderBy = pSub->pOrderBy;
  97844. pSub->pOrderBy = 0;
  97845. }else if( pParent->pOrderBy ){
  97846. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  97847. }
  97848. if( pSub->pWhere ){
  97849. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  97850. }else{
  97851. pWhere = 0;
  97852. }
  97853. if( subqueryIsAgg ){
  97854. assert( pParent->pHaving==0 );
  97855. pParent->pHaving = pParent->pWhere;
  97856. pParent->pWhere = pWhere;
  97857. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  97858. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  97859. sqlite3ExprDup(db, pSub->pHaving, 0));
  97860. assert( pParent->pGroupBy==0 );
  97861. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  97862. }else{
  97863. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  97864. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  97865. }
  97866. /* The flattened query is distinct if either the inner or the
  97867. ** outer query is distinct.
  97868. */
  97869. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  97870. /*
  97871. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  97872. **
  97873. ** One is tempted to try to add a and b to combine the limits. But this
  97874. ** does not work if either limit is negative.
  97875. */
  97876. if( pSub->pLimit ){
  97877. pParent->pLimit = pSub->pLimit;
  97878. pSub->pLimit = 0;
  97879. }
  97880. }
  97881. /* Finially, delete what is left of the subquery and return
  97882. ** success.
  97883. */
  97884. sqlite3SelectDelete(db, pSub1);
  97885. return 1;
  97886. }
  97887. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  97888. /*
  97889. ** Based on the contents of the AggInfo structure indicated by the first
  97890. ** argument, this function checks if the following are true:
  97891. **
  97892. ** * the query contains just a single aggregate function,
  97893. ** * the aggregate function is either min() or max(), and
  97894. ** * the argument to the aggregate function is a column value.
  97895. **
  97896. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  97897. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  97898. ** list of arguments passed to the aggregate before returning.
  97899. **
  97900. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  97901. ** WHERE_ORDERBY_NORMAL is returned.
  97902. */
  97903. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  97904. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  97905. *ppMinMax = 0;
  97906. if( pAggInfo->nFunc==1 ){
  97907. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  97908. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  97909. assert( pExpr->op==TK_AGG_FUNCTION );
  97910. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  97911. const char *zFunc = pExpr->u.zToken;
  97912. if( sqlite3StrICmp(zFunc, "min")==0 ){
  97913. eRet = WHERE_ORDERBY_MIN;
  97914. *ppMinMax = pEList;
  97915. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  97916. eRet = WHERE_ORDERBY_MAX;
  97917. *ppMinMax = pEList;
  97918. }
  97919. }
  97920. }
  97921. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  97922. return eRet;
  97923. }
  97924. /*
  97925. ** The select statement passed as the first argument is an aggregate query.
  97926. ** The second argment is the associated aggregate-info object. This
  97927. ** function tests if the SELECT is of the form:
  97928. **
  97929. ** SELECT count(*) FROM <tbl>
  97930. **
  97931. ** where table is a database table, not a sub-select or view. If the query
  97932. ** does match this pattern, then a pointer to the Table object representing
  97933. ** <tbl> is returned. Otherwise, 0 is returned.
  97934. */
  97935. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  97936. Table *pTab;
  97937. Expr *pExpr;
  97938. assert( !p->pGroupBy );
  97939. if( p->pWhere || p->pEList->nExpr!=1
  97940. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  97941. ){
  97942. return 0;
  97943. }
  97944. pTab = p->pSrc->a[0].pTab;
  97945. pExpr = p->pEList->a[0].pExpr;
  97946. assert( pTab && !pTab->pSelect && pExpr );
  97947. if( IsVirtual(pTab) ) return 0;
  97948. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  97949. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  97950. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  97951. if( pExpr->flags&EP_Distinct ) return 0;
  97952. return pTab;
  97953. }
  97954. /*
  97955. ** If the source-list item passed as an argument was augmented with an
  97956. ** INDEXED BY clause, then try to locate the specified index. If there
  97957. ** was such a clause and the named index cannot be found, return
  97958. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  97959. ** pFrom->pIndex and return SQLITE_OK.
  97960. */
  97961. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  97962. if( pFrom->pTab && pFrom->zIndex ){
  97963. Table *pTab = pFrom->pTab;
  97964. char *zIndex = pFrom->zIndex;
  97965. Index *pIdx;
  97966. for(pIdx=pTab->pIndex;
  97967. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  97968. pIdx=pIdx->pNext
  97969. );
  97970. if( !pIdx ){
  97971. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  97972. pParse->checkSchema = 1;
  97973. return SQLITE_ERROR;
  97974. }
  97975. pFrom->pIndex = pIdx;
  97976. }
  97977. return SQLITE_OK;
  97978. }
  97979. /*
  97980. ** Detect compound SELECT statements that use an ORDER BY clause with
  97981. ** an alternative collating sequence.
  97982. **
  97983. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  97984. **
  97985. ** These are rewritten as a subquery:
  97986. **
  97987. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  97988. ** ORDER BY ... COLLATE ...
  97989. **
  97990. ** This transformation is necessary because the multiSelectOrderBy() routine
  97991. ** above that generates the code for a compound SELECT with an ORDER BY clause
  97992. ** uses a merge algorithm that requires the same collating sequence on the
  97993. ** result columns as on the ORDER BY clause. See ticket
  97994. ** http://www.sqlite.org/src/info/6709574d2a
  97995. **
  97996. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  97997. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  97998. ** there are COLLATE terms in the ORDER BY.
  97999. */
  98000. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  98001. int i;
  98002. Select *pNew;
  98003. Select *pX;
  98004. sqlite3 *db;
  98005. struct ExprList_item *a;
  98006. SrcList *pNewSrc;
  98007. Parse *pParse;
  98008. Token dummy;
  98009. if( p->pPrior==0 ) return WRC_Continue;
  98010. if( p->pOrderBy==0 ) return WRC_Continue;
  98011. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  98012. if( pX==0 ) return WRC_Continue;
  98013. a = p->pOrderBy->a;
  98014. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  98015. if( a[i].pExpr->flags & EP_Collate ) break;
  98016. }
  98017. if( i<0 ) return WRC_Continue;
  98018. /* If we reach this point, that means the transformation is required. */
  98019. pParse = pWalker->pParse;
  98020. db = pParse->db;
  98021. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  98022. if( pNew==0 ) return WRC_Abort;
  98023. memset(&dummy, 0, sizeof(dummy));
  98024. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  98025. if( pNewSrc==0 ) return WRC_Abort;
  98026. *pNew = *p;
  98027. p->pSrc = pNewSrc;
  98028. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  98029. p->op = TK_SELECT;
  98030. p->pWhere = 0;
  98031. pNew->pGroupBy = 0;
  98032. pNew->pHaving = 0;
  98033. pNew->pOrderBy = 0;
  98034. p->pPrior = 0;
  98035. pNew->pLimit = 0;
  98036. pNew->pOffset = 0;
  98037. return WRC_Continue;
  98038. }
  98039. /*
  98040. ** This routine is a Walker callback for "expanding" a SELECT statement.
  98041. ** "Expanding" means to do the following:
  98042. **
  98043. ** (1) Make sure VDBE cursor numbers have been assigned to every
  98044. ** element of the FROM clause.
  98045. **
  98046. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  98047. ** defines FROM clause. When views appear in the FROM clause,
  98048. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  98049. ** that implements the view. A copy is made of the view's SELECT
  98050. ** statement so that we can freely modify or delete that statement
  98051. ** without worrying about messing up the presistent representation
  98052. ** of the view.
  98053. **
  98054. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  98055. ** on joins and the ON and USING clause of joins.
  98056. **
  98057. ** (4) Scan the list of columns in the result set (pEList) looking
  98058. ** for instances of the "*" operator or the TABLE.* operator.
  98059. ** If found, expand each "*" to be every column in every table
  98060. ** and TABLE.* to be every column in TABLE.
  98061. **
  98062. */
  98063. static int selectExpander(Walker *pWalker, Select *p){
  98064. Parse *pParse = pWalker->pParse;
  98065. int i, j, k;
  98066. SrcList *pTabList;
  98067. ExprList *pEList;
  98068. struct SrcList_item *pFrom;
  98069. sqlite3 *db = pParse->db;
  98070. Expr *pE, *pRight, *pExpr;
  98071. u16 selFlags = p->selFlags;
  98072. p->selFlags |= SF_Expanded;
  98073. if( db->mallocFailed ){
  98074. return WRC_Abort;
  98075. }
  98076. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  98077. return WRC_Prune;
  98078. }
  98079. pTabList = p->pSrc;
  98080. pEList = p->pEList;
  98081. /* Make sure cursor numbers have been assigned to all entries in
  98082. ** the FROM clause of the SELECT statement.
  98083. */
  98084. sqlite3SrcListAssignCursors(pParse, pTabList);
  98085. /* Look up every table named in the FROM clause of the select. If
  98086. ** an entry of the FROM clause is a subquery instead of a table or view,
  98087. ** then create a transient table structure to describe the subquery.
  98088. */
  98089. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98090. Table *pTab;
  98091. if( pFrom->pTab!=0 ){
  98092. /* This statement has already been prepared. There is no need
  98093. ** to go further. */
  98094. assert( i==0 );
  98095. return WRC_Prune;
  98096. }
  98097. if( pFrom->zName==0 ){
  98098. #ifndef SQLITE_OMIT_SUBQUERY
  98099. Select *pSel = pFrom->pSelect;
  98100. /* A sub-query in the FROM clause of a SELECT */
  98101. assert( pSel!=0 );
  98102. assert( pFrom->pTab==0 );
  98103. sqlite3WalkSelect(pWalker, pSel);
  98104. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  98105. if( pTab==0 ) return WRC_Abort;
  98106. pTab->nRef = 1;
  98107. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  98108. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  98109. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  98110. pTab->iPKey = -1;
  98111. pTab->nRowEst = 1048576;
  98112. pTab->tabFlags |= TF_Ephemeral;
  98113. #endif
  98114. }else{
  98115. /* An ordinary table or view name in the FROM clause */
  98116. assert( pFrom->pTab==0 );
  98117. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  98118. if( pTab==0 ) return WRC_Abort;
  98119. if( pTab->nRef==0xffff ){
  98120. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  98121. pTab->zName);
  98122. pFrom->pTab = 0;
  98123. return WRC_Abort;
  98124. }
  98125. pTab->nRef++;
  98126. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  98127. if( pTab->pSelect || IsVirtual(pTab) ){
  98128. /* We reach here if the named table is a really a view */
  98129. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  98130. assert( pFrom->pSelect==0 );
  98131. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  98132. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  98133. }
  98134. #endif
  98135. }
  98136. /* Locate the index named by the INDEXED BY clause, if any. */
  98137. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  98138. return WRC_Abort;
  98139. }
  98140. }
  98141. /* Process NATURAL keywords, and ON and USING clauses of joins.
  98142. */
  98143. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  98144. return WRC_Abort;
  98145. }
  98146. /* For every "*" that occurs in the column list, insert the names of
  98147. ** all columns in all tables. And for every TABLE.* insert the names
  98148. ** of all columns in TABLE. The parser inserted a special expression
  98149. ** with the TK_ALL operator for each "*" that it found in the column list.
  98150. ** The following code just has to locate the TK_ALL expressions and expand
  98151. ** each one to the list of all columns in all tables.
  98152. **
  98153. ** The first loop just checks to see if there are any "*" operators
  98154. ** that need expanding.
  98155. */
  98156. for(k=0; k<pEList->nExpr; k++){
  98157. pE = pEList->a[k].pExpr;
  98158. if( pE->op==TK_ALL ) break;
  98159. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  98160. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  98161. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  98162. }
  98163. if( k<pEList->nExpr ){
  98164. /*
  98165. ** If we get here it means the result set contains one or more "*"
  98166. ** operators that need to be expanded. Loop through each expression
  98167. ** in the result set and expand them one by one.
  98168. */
  98169. struct ExprList_item *a = pEList->a;
  98170. ExprList *pNew = 0;
  98171. int flags = pParse->db->flags;
  98172. int longNames = (flags & SQLITE_FullColNames)!=0
  98173. && (flags & SQLITE_ShortColNames)==0;
  98174. /* When processing FROM-clause subqueries, it is always the case
  98175. ** that full_column_names=OFF and short_column_names=ON. The
  98176. ** sqlite3ResultSetOfSelect() routine makes it so. */
  98177. assert( (p->selFlags & SF_NestedFrom)==0
  98178. || ((flags & SQLITE_FullColNames)==0 &&
  98179. (flags & SQLITE_ShortColNames)!=0) );
  98180. for(k=0; k<pEList->nExpr; k++){
  98181. pE = a[k].pExpr;
  98182. pRight = pE->pRight;
  98183. assert( pE->op!=TK_DOT || pRight!=0 );
  98184. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  98185. /* This particular expression does not need to be expanded.
  98186. */
  98187. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  98188. if( pNew ){
  98189. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  98190. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  98191. a[k].zName = 0;
  98192. a[k].zSpan = 0;
  98193. }
  98194. a[k].pExpr = 0;
  98195. }else{
  98196. /* This expression is a "*" or a "TABLE.*" and needs to be
  98197. ** expanded. */
  98198. int tableSeen = 0; /* Set to 1 when TABLE matches */
  98199. char *zTName = 0; /* text of name of TABLE */
  98200. if( pE->op==TK_DOT ){
  98201. assert( pE->pLeft!=0 );
  98202. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  98203. zTName = pE->pLeft->u.zToken;
  98204. }
  98205. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98206. Table *pTab = pFrom->pTab;
  98207. Select *pSub = pFrom->pSelect;
  98208. char *zTabName = pFrom->zAlias;
  98209. const char *zSchemaName = 0;
  98210. int iDb;
  98211. if( zTabName==0 ){
  98212. zTabName = pTab->zName;
  98213. }
  98214. if( db->mallocFailed ) break;
  98215. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  98216. pSub = 0;
  98217. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  98218. continue;
  98219. }
  98220. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98221. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  98222. }
  98223. for(j=0; j<pTab->nCol; j++){
  98224. char *zName = pTab->aCol[j].zName;
  98225. char *zColname; /* The computed column name */
  98226. char *zToFree; /* Malloced string that needs to be freed */
  98227. Token sColname; /* Computed column name as a token */
  98228. assert( zName );
  98229. if( zTName && pSub
  98230. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  98231. ){
  98232. continue;
  98233. }
  98234. /* If a column is marked as 'hidden' (currently only possible
  98235. ** for virtual tables), do not include it in the expanded
  98236. ** result-set list.
  98237. */
  98238. if( IsHiddenColumn(&pTab->aCol[j]) ){
  98239. assert(IsVirtual(pTab));
  98240. continue;
  98241. }
  98242. tableSeen = 1;
  98243. if( i>0 && zTName==0 ){
  98244. if( (pFrom->jointype & JT_NATURAL)!=0
  98245. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  98246. ){
  98247. /* In a NATURAL join, omit the join columns from the
  98248. ** table to the right of the join */
  98249. continue;
  98250. }
  98251. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  98252. /* In a join with a USING clause, omit columns in the
  98253. ** using clause from the table on the right. */
  98254. continue;
  98255. }
  98256. }
  98257. pRight = sqlite3Expr(db, TK_ID, zName);
  98258. zColname = zName;
  98259. zToFree = 0;
  98260. if( longNames || pTabList->nSrc>1 ){
  98261. Expr *pLeft;
  98262. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  98263. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  98264. if( zSchemaName ){
  98265. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  98266. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  98267. }
  98268. if( longNames ){
  98269. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  98270. zToFree = zColname;
  98271. }
  98272. }else{
  98273. pExpr = pRight;
  98274. }
  98275. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  98276. sColname.z = zColname;
  98277. sColname.n = sqlite3Strlen30(zColname);
  98278. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  98279. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  98280. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  98281. if( pSub ){
  98282. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  98283. testcase( pX->zSpan==0 );
  98284. }else{
  98285. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  98286. zSchemaName, zTabName, zColname);
  98287. testcase( pX->zSpan==0 );
  98288. }
  98289. pX->bSpanIsTab = 1;
  98290. }
  98291. sqlite3DbFree(db, zToFree);
  98292. }
  98293. }
  98294. if( !tableSeen ){
  98295. if( zTName ){
  98296. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  98297. }else{
  98298. sqlite3ErrorMsg(pParse, "no tables specified");
  98299. }
  98300. }
  98301. }
  98302. }
  98303. sqlite3ExprListDelete(db, pEList);
  98304. p->pEList = pNew;
  98305. }
  98306. #if SQLITE_MAX_COLUMN
  98307. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  98308. sqlite3ErrorMsg(pParse, "too many columns in result set");
  98309. }
  98310. #endif
  98311. return WRC_Continue;
  98312. }
  98313. /*
  98314. ** No-op routine for the parse-tree walker.
  98315. **
  98316. ** When this routine is the Walker.xExprCallback then expression trees
  98317. ** are walked without any actions being taken at each node. Presumably,
  98318. ** when this routine is used for Walker.xExprCallback then
  98319. ** Walker.xSelectCallback is set to do something useful for every
  98320. ** subquery in the parser tree.
  98321. */
  98322. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  98323. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  98324. return WRC_Continue;
  98325. }
  98326. /*
  98327. ** This routine "expands" a SELECT statement and all of its subqueries.
  98328. ** For additional information on what it means to "expand" a SELECT
  98329. ** statement, see the comment on the selectExpand worker callback above.
  98330. **
  98331. ** Expanding a SELECT statement is the first step in processing a
  98332. ** SELECT statement. The SELECT statement must be expanded before
  98333. ** name resolution is performed.
  98334. **
  98335. ** If anything goes wrong, an error message is written into pParse.
  98336. ** The calling function can detect the problem by looking at pParse->nErr
  98337. ** and/or pParse->db->mallocFailed.
  98338. */
  98339. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  98340. Walker w;
  98341. memset(&w, 0, sizeof(w));
  98342. w.xExprCallback = exprWalkNoop;
  98343. w.pParse = pParse;
  98344. if( pParse->hasCompound ){
  98345. w.xSelectCallback = convertCompoundSelectToSubquery;
  98346. sqlite3WalkSelect(&w, pSelect);
  98347. }
  98348. w.xSelectCallback = selectExpander;
  98349. sqlite3WalkSelect(&w, pSelect);
  98350. }
  98351. #ifndef SQLITE_OMIT_SUBQUERY
  98352. /*
  98353. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  98354. ** interface.
  98355. **
  98356. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  98357. ** information to the Table structure that represents the result set
  98358. ** of that subquery.
  98359. **
  98360. ** The Table structure that represents the result set was constructed
  98361. ** by selectExpander() but the type and collation information was omitted
  98362. ** at that point because identifiers had not yet been resolved. This
  98363. ** routine is called after identifier resolution.
  98364. */
  98365. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  98366. Parse *pParse;
  98367. int i;
  98368. SrcList *pTabList;
  98369. struct SrcList_item *pFrom;
  98370. assert( p->selFlags & SF_Resolved );
  98371. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  98372. p->selFlags |= SF_HasTypeInfo;
  98373. pParse = pWalker->pParse;
  98374. pTabList = p->pSrc;
  98375. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98376. Table *pTab = pFrom->pTab;
  98377. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  98378. /* A sub-query in the FROM clause of a SELECT */
  98379. Select *pSel = pFrom->pSelect;
  98380. assert( pSel );
  98381. while( pSel->pPrior ) pSel = pSel->pPrior;
  98382. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  98383. }
  98384. }
  98385. }
  98386. return WRC_Continue;
  98387. }
  98388. #endif
  98389. /*
  98390. ** This routine adds datatype and collating sequence information to
  98391. ** the Table structures of all FROM-clause subqueries in a
  98392. ** SELECT statement.
  98393. **
  98394. ** Use this routine after name resolution.
  98395. */
  98396. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  98397. #ifndef SQLITE_OMIT_SUBQUERY
  98398. Walker w;
  98399. memset(&w, 0, sizeof(w));
  98400. w.xSelectCallback = selectAddSubqueryTypeInfo;
  98401. w.xExprCallback = exprWalkNoop;
  98402. w.pParse = pParse;
  98403. w.bSelectDepthFirst = 1;
  98404. sqlite3WalkSelect(&w, pSelect);
  98405. #endif
  98406. }
  98407. /*
  98408. ** This routine sets up a SELECT statement for processing. The
  98409. ** following is accomplished:
  98410. **
  98411. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  98412. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  98413. ** * ON and USING clauses are shifted into WHERE statements
  98414. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  98415. ** * Identifiers in expression are matched to tables.
  98416. **
  98417. ** This routine acts recursively on all subqueries within the SELECT.
  98418. */
  98419. SQLITE_PRIVATE void sqlite3SelectPrep(
  98420. Parse *pParse, /* The parser context */
  98421. Select *p, /* The SELECT statement being coded. */
  98422. NameContext *pOuterNC /* Name context for container */
  98423. ){
  98424. sqlite3 *db;
  98425. if( NEVER(p==0) ) return;
  98426. db = pParse->db;
  98427. if( db->mallocFailed ) return;
  98428. if( p->selFlags & SF_HasTypeInfo ) return;
  98429. sqlite3SelectExpand(pParse, p);
  98430. if( pParse->nErr || db->mallocFailed ) return;
  98431. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  98432. if( pParse->nErr || db->mallocFailed ) return;
  98433. sqlite3SelectAddTypeInfo(pParse, p);
  98434. }
  98435. /*
  98436. ** Reset the aggregate accumulator.
  98437. **
  98438. ** The aggregate accumulator is a set of memory cells that hold
  98439. ** intermediate results while calculating an aggregate. This
  98440. ** routine generates code that stores NULLs in all of those memory
  98441. ** cells.
  98442. */
  98443. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  98444. Vdbe *v = pParse->pVdbe;
  98445. int i;
  98446. struct AggInfo_func *pFunc;
  98447. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  98448. return;
  98449. }
  98450. for(i=0; i<pAggInfo->nColumn; i++){
  98451. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  98452. }
  98453. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  98454. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  98455. if( pFunc->iDistinct>=0 ){
  98456. Expr *pE = pFunc->pExpr;
  98457. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  98458. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  98459. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  98460. "argument");
  98461. pFunc->iDistinct = -1;
  98462. }else{
  98463. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  98464. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  98465. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  98466. }
  98467. }
  98468. }
  98469. }
  98470. /*
  98471. ** Invoke the OP_AggFinalize opcode for every aggregate function
  98472. ** in the AggInfo structure.
  98473. */
  98474. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  98475. Vdbe *v = pParse->pVdbe;
  98476. int i;
  98477. struct AggInfo_func *pF;
  98478. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  98479. ExprList *pList = pF->pExpr->x.pList;
  98480. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  98481. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  98482. (void*)pF->pFunc, P4_FUNCDEF);
  98483. }
  98484. }
  98485. /*
  98486. ** Update the accumulator memory cells for an aggregate based on
  98487. ** the current cursor position.
  98488. */
  98489. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  98490. Vdbe *v = pParse->pVdbe;
  98491. int i;
  98492. int regHit = 0;
  98493. int addrHitTest = 0;
  98494. struct AggInfo_func *pF;
  98495. struct AggInfo_col *pC;
  98496. pAggInfo->directMode = 1;
  98497. sqlite3ExprCacheClear(pParse);
  98498. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  98499. int nArg;
  98500. int addrNext = 0;
  98501. int regAgg;
  98502. ExprList *pList = pF->pExpr->x.pList;
  98503. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  98504. if( pList ){
  98505. nArg = pList->nExpr;
  98506. regAgg = sqlite3GetTempRange(pParse, nArg);
  98507. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  98508. }else{
  98509. nArg = 0;
  98510. regAgg = 0;
  98511. }
  98512. if( pF->iDistinct>=0 ){
  98513. addrNext = sqlite3VdbeMakeLabel(v);
  98514. assert( nArg==1 );
  98515. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  98516. }
  98517. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  98518. CollSeq *pColl = 0;
  98519. struct ExprList_item *pItem;
  98520. int j;
  98521. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  98522. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  98523. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  98524. }
  98525. if( !pColl ){
  98526. pColl = pParse->db->pDfltColl;
  98527. }
  98528. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  98529. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  98530. }
  98531. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  98532. (void*)pF->pFunc, P4_FUNCDEF);
  98533. sqlite3VdbeChangeP5(v, (u8)nArg);
  98534. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  98535. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  98536. if( addrNext ){
  98537. sqlite3VdbeResolveLabel(v, addrNext);
  98538. sqlite3ExprCacheClear(pParse);
  98539. }
  98540. }
  98541. /* Before populating the accumulator registers, clear the column cache.
  98542. ** Otherwise, if any of the required column values are already present
  98543. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  98544. ** to pC->iMem. But by the time the value is used, the original register
  98545. ** may have been used, invalidating the underlying buffer holding the
  98546. ** text or blob value. See ticket [883034dcb5].
  98547. **
  98548. ** Another solution would be to change the OP_SCopy used to copy cached
  98549. ** values to an OP_Copy.
  98550. */
  98551. if( regHit ){
  98552. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  98553. }
  98554. sqlite3ExprCacheClear(pParse);
  98555. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  98556. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  98557. }
  98558. pAggInfo->directMode = 0;
  98559. sqlite3ExprCacheClear(pParse);
  98560. if( addrHitTest ){
  98561. sqlite3VdbeJumpHere(v, addrHitTest);
  98562. }
  98563. }
  98564. /*
  98565. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  98566. ** count(*) query ("SELECT count(*) FROM pTab").
  98567. */
  98568. #ifndef SQLITE_OMIT_EXPLAIN
  98569. static void explainSimpleCount(
  98570. Parse *pParse, /* Parse context */
  98571. Table *pTab, /* Table being queried */
  98572. Index *pIdx /* Index used to optimize scan, or NULL */
  98573. ){
  98574. if( pParse->explain==2 ){
  98575. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  98576. pTab->zName,
  98577. pIdx ? " USING COVERING INDEX " : "",
  98578. pIdx ? pIdx->zName : ""
  98579. );
  98580. sqlite3VdbeAddOp4(
  98581. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  98582. );
  98583. }
  98584. }
  98585. #else
  98586. # define explainSimpleCount(a,b,c)
  98587. #endif
  98588. /*
  98589. ** Generate code for the SELECT statement given in the p argument.
  98590. **
  98591. ** The results are distributed in various ways depending on the
  98592. ** contents of the SelectDest structure pointed to by argument pDest
  98593. ** as follows:
  98594. **
  98595. ** pDest->eDest Result
  98596. ** ------------ -------------------------------------------
  98597. ** SRT_Output Generate a row of output (using the OP_ResultRow
  98598. ** opcode) for each row in the result set.
  98599. **
  98600. ** SRT_Mem Only valid if the result is a single column.
  98601. ** Store the first column of the first result row
  98602. ** in register pDest->iSDParm then abandon the rest
  98603. ** of the query. This destination implies "LIMIT 1".
  98604. **
  98605. ** SRT_Set The result must be a single column. Store each
  98606. ** row of result as the key in table pDest->iSDParm.
  98607. ** Apply the affinity pDest->affSdst before storing
  98608. ** results. Used to implement "IN (SELECT ...)".
  98609. **
  98610. ** SRT_Union Store results as a key in a temporary table
  98611. ** identified by pDest->iSDParm.
  98612. **
  98613. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  98614. **
  98615. ** SRT_Table Store results in temporary table pDest->iSDParm.
  98616. ** This is like SRT_EphemTab except that the table
  98617. ** is assumed to already be open.
  98618. **
  98619. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  98620. ** the result there. The cursor is left open after
  98621. ** returning. This is like SRT_Table except that
  98622. ** this destination uses OP_OpenEphemeral to create
  98623. ** the table first.
  98624. **
  98625. ** SRT_Coroutine Generate a co-routine that returns a new row of
  98626. ** results each time it is invoked. The entry point
  98627. ** of the co-routine is stored in register pDest->iSDParm.
  98628. **
  98629. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  98630. ** set is not empty.
  98631. **
  98632. ** SRT_Discard Throw the results away. This is used by SELECT
  98633. ** statements within triggers whose only purpose is
  98634. ** the side-effects of functions.
  98635. **
  98636. ** This routine returns the number of errors. If any errors are
  98637. ** encountered, then an appropriate error message is left in
  98638. ** pParse->zErrMsg.
  98639. **
  98640. ** This routine does NOT free the Select structure passed in. The
  98641. ** calling function needs to do that.
  98642. */
  98643. SQLITE_PRIVATE int sqlite3Select(
  98644. Parse *pParse, /* The parser context */
  98645. Select *p, /* The SELECT statement being coded. */
  98646. SelectDest *pDest /* What to do with the query results */
  98647. ){
  98648. int i, j; /* Loop counters */
  98649. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  98650. Vdbe *v; /* The virtual machine under construction */
  98651. int isAgg; /* True for select lists like "count(*)" */
  98652. ExprList *pEList; /* List of columns to extract. */
  98653. SrcList *pTabList; /* List of tables to select from */
  98654. Expr *pWhere; /* The WHERE clause. May be NULL */
  98655. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  98656. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  98657. Expr *pHaving; /* The HAVING clause. May be NULL */
  98658. int rc = 1; /* Value to return from this function */
  98659. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  98660. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  98661. AggInfo sAggInfo; /* Information used by aggregate queries */
  98662. int iEnd; /* Address of the end of the query */
  98663. sqlite3 *db; /* The database connection */
  98664. #ifndef SQLITE_OMIT_EXPLAIN
  98665. int iRestoreSelectId = pParse->iSelectId;
  98666. pParse->iSelectId = pParse->iNextSelectId++;
  98667. #endif
  98668. db = pParse->db;
  98669. if( p==0 || db->mallocFailed || pParse->nErr ){
  98670. return 1;
  98671. }
  98672. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  98673. memset(&sAggInfo, 0, sizeof(sAggInfo));
  98674. if( IgnorableOrderby(pDest) ){
  98675. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  98676. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  98677. /* If ORDER BY makes no difference in the output then neither does
  98678. ** DISTINCT so it can be removed too. */
  98679. sqlite3ExprListDelete(db, p->pOrderBy);
  98680. p->pOrderBy = 0;
  98681. p->selFlags &= ~SF_Distinct;
  98682. }
  98683. sqlite3SelectPrep(pParse, p, 0);
  98684. pOrderBy = p->pOrderBy;
  98685. pTabList = p->pSrc;
  98686. pEList = p->pEList;
  98687. if( pParse->nErr || db->mallocFailed ){
  98688. goto select_end;
  98689. }
  98690. isAgg = (p->selFlags & SF_Aggregate)!=0;
  98691. assert( pEList!=0 );
  98692. /* Begin generating code.
  98693. */
  98694. v = sqlite3GetVdbe(pParse);
  98695. if( v==0 ) goto select_end;
  98696. /* If writing to memory or generating a set
  98697. ** only a single column may be output.
  98698. */
  98699. #ifndef SQLITE_OMIT_SUBQUERY
  98700. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  98701. goto select_end;
  98702. }
  98703. #endif
  98704. /* Generate code for all sub-queries in the FROM clause
  98705. */
  98706. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  98707. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  98708. struct SrcList_item *pItem = &pTabList->a[i];
  98709. SelectDest dest;
  98710. Select *pSub = pItem->pSelect;
  98711. int isAggSub;
  98712. if( pSub==0 ) continue;
  98713. /* Sometimes the code for a subquery will be generated more than
  98714. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  98715. ** for example. In that case, do not regenerate the code to manifest
  98716. ** a view or the co-routine to implement a view. The first instance
  98717. ** is sufficient, though the subroutine to manifest the view does need
  98718. ** to be invoked again. */
  98719. if( pItem->addrFillSub ){
  98720. if( pItem->viaCoroutine==0 ){
  98721. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  98722. }
  98723. continue;
  98724. }
  98725. /* Increment Parse.nHeight by the height of the largest expression
  98726. ** tree referred to by this, the parent select. The child select
  98727. ** may contain expression trees of at most
  98728. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  98729. ** more conservative than necessary, but much easier than enforcing
  98730. ** an exact limit.
  98731. */
  98732. pParse->nHeight += sqlite3SelectExprHeight(p);
  98733. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  98734. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  98735. /* This subquery can be absorbed into its parent. */
  98736. if( isAggSub ){
  98737. isAgg = 1;
  98738. p->selFlags |= SF_Aggregate;
  98739. }
  98740. i = -1;
  98741. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  98742. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  98743. ){
  98744. /* Implement a co-routine that will return a single row of the result
  98745. ** set on each invocation.
  98746. */
  98747. int addrTop;
  98748. int addrEof;
  98749. pItem->regReturn = ++pParse->nMem;
  98750. addrEof = ++pParse->nMem;
  98751. /* Before coding the OP_Goto to jump to the start of the main routine,
  98752. ** ensure that the jump to the verify-schema routine has already
  98753. ** been coded. Otherwise, the verify-schema would likely be coded as
  98754. ** part of the co-routine. If the main routine then accessed the
  98755. ** database before invoking the co-routine for the first time (for
  98756. ** example to initialize a LIMIT register from a sub-select), it would
  98757. ** be doing so without having verified the schema version and obtained
  98758. ** the required db locks. See ticket d6b36be38. */
  98759. sqlite3CodeVerifySchema(pParse, -1);
  98760. sqlite3VdbeAddOp0(v, OP_Goto);
  98761. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  98762. sqlite3VdbeChangeP5(v, 1);
  98763. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  98764. pItem->addrFillSub = addrTop;
  98765. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  98766. sqlite3VdbeChangeP5(v, 1);
  98767. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  98768. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  98769. sqlite3Select(pParse, pSub, &dest);
  98770. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  98771. pItem->viaCoroutine = 1;
  98772. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  98773. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  98774. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  98775. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  98776. VdbeComment((v, "end %s", pItem->pTab->zName));
  98777. sqlite3VdbeJumpHere(v, addrTop-1);
  98778. sqlite3ClearTempRegCache(pParse);
  98779. }else{
  98780. /* Generate a subroutine that will fill an ephemeral table with
  98781. ** the content of this subquery. pItem->addrFillSub will point
  98782. ** to the address of the generated subroutine. pItem->regReturn
  98783. ** is a register allocated to hold the subroutine return address
  98784. */
  98785. int topAddr;
  98786. int onceAddr = 0;
  98787. int retAddr;
  98788. assert( pItem->addrFillSub==0 );
  98789. pItem->regReturn = ++pParse->nMem;
  98790. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  98791. pItem->addrFillSub = topAddr+1;
  98792. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  98793. if( pItem->isCorrelated==0 ){
  98794. /* If the subquery is not correlated and if we are not inside of
  98795. ** a trigger, then we only need to compute the value of the subquery
  98796. ** once. */
  98797. onceAddr = sqlite3CodeOnce(pParse);
  98798. }
  98799. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  98800. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  98801. sqlite3Select(pParse, pSub, &dest);
  98802. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  98803. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  98804. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  98805. VdbeComment((v, "end %s", pItem->pTab->zName));
  98806. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  98807. sqlite3ClearTempRegCache(pParse);
  98808. }
  98809. if( /*pParse->nErr ||*/ db->mallocFailed ){
  98810. goto select_end;
  98811. }
  98812. pParse->nHeight -= sqlite3SelectExprHeight(p);
  98813. pTabList = p->pSrc;
  98814. if( !IgnorableOrderby(pDest) ){
  98815. pOrderBy = p->pOrderBy;
  98816. }
  98817. }
  98818. pEList = p->pEList;
  98819. #endif
  98820. pWhere = p->pWhere;
  98821. pGroupBy = p->pGroupBy;
  98822. pHaving = p->pHaving;
  98823. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  98824. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98825. /* If there is are a sequence of queries, do the earlier ones first.
  98826. */
  98827. if( p->pPrior ){
  98828. if( p->pRightmost==0 ){
  98829. Select *pLoop, *pRight = 0;
  98830. int cnt = 0;
  98831. int mxSelect;
  98832. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  98833. pLoop->pRightmost = p;
  98834. pLoop->pNext = pRight;
  98835. pRight = pLoop;
  98836. }
  98837. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  98838. if( mxSelect && cnt>mxSelect ){
  98839. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  98840. goto select_end;
  98841. }
  98842. }
  98843. rc = multiSelect(pParse, p, pDest);
  98844. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  98845. return rc;
  98846. }
  98847. #endif
  98848. /* If there is both a GROUP BY and an ORDER BY clause and they are
  98849. ** identical, then disable the ORDER BY clause since the GROUP BY
  98850. ** will cause elements to come out in the correct order. This is
  98851. ** an optimization - the correct answer should result regardless.
  98852. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  98853. ** to disable this optimization for testing purposes.
  98854. */
  98855. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  98856. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  98857. pOrderBy = 0;
  98858. }
  98859. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  98860. ** if the select-list is the same as the ORDER BY list, then this query
  98861. ** can be rewritten as a GROUP BY. In other words, this:
  98862. **
  98863. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  98864. **
  98865. ** is transformed to:
  98866. **
  98867. ** SELECT xyz FROM ... GROUP BY xyz
  98868. **
  98869. ** The second form is preferred as a single index (or temp-table) may be
  98870. ** used for both the ORDER BY and DISTINCT processing. As originally
  98871. ** written the query must use a temp-table for at least one of the ORDER
  98872. ** BY and DISTINCT, and an index or separate temp-table for the other.
  98873. */
  98874. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  98875. && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  98876. ){
  98877. p->selFlags &= ~SF_Distinct;
  98878. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  98879. pGroupBy = p->pGroupBy;
  98880. pOrderBy = 0;
  98881. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  98882. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  98883. ** original setting of the SF_Distinct flag, not the current setting */
  98884. assert( sDistinct.isTnct );
  98885. }
  98886. /* If there is an ORDER BY clause, then this sorting
  98887. ** index might end up being unused if the data can be
  98888. ** extracted in pre-sorted order. If that is the case, then the
  98889. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  98890. ** we figure out that the sorting index is not needed. The addrSortIndex
  98891. ** variable is used to facilitate that change.
  98892. */
  98893. if( pOrderBy ){
  98894. KeyInfo *pKeyInfo;
  98895. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  98896. pOrderBy->iECursor = pParse->nTab++;
  98897. p->addrOpenEphm[2] = addrSortIndex =
  98898. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  98899. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  98900. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  98901. }else{
  98902. addrSortIndex = -1;
  98903. }
  98904. /* If the output is destined for a temporary table, open that table.
  98905. */
  98906. if( pDest->eDest==SRT_EphemTab ){
  98907. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  98908. }
  98909. /* Set the limiter.
  98910. */
  98911. iEnd = sqlite3VdbeMakeLabel(v);
  98912. p->nSelectRow = LARGEST_INT64;
  98913. computeLimitRegisters(pParse, p, iEnd);
  98914. if( p->iLimit==0 && addrSortIndex>=0 ){
  98915. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  98916. p->selFlags |= SF_UseSorter;
  98917. }
  98918. /* Open a virtual index to use for the distinct set.
  98919. */
  98920. if( p->selFlags & SF_Distinct ){
  98921. sDistinct.tabTnct = pParse->nTab++;
  98922. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  98923. sDistinct.tabTnct, 0, 0,
  98924. (char*)keyInfoFromExprList(pParse, p->pEList),
  98925. P4_KEYINFO_HANDOFF);
  98926. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  98927. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  98928. }else{
  98929. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  98930. }
  98931. if( !isAgg && pGroupBy==0 ){
  98932. /* No aggregate functions and no GROUP BY clause */
  98933. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  98934. /* Begin the database scan. */
  98935. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
  98936. wctrlFlags, 0);
  98937. if( pWInfo==0 ) goto select_end;
  98938. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  98939. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  98940. }
  98941. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  98942. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  98943. }
  98944. if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
  98945. /* If sorting index that was created by a prior OP_OpenEphemeral
  98946. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  98947. ** into an OP_Noop.
  98948. */
  98949. if( addrSortIndex>=0 && pOrderBy==0 ){
  98950. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  98951. p->addrOpenEphm[2] = -1;
  98952. }
  98953. /* Use the standard inner loop. */
  98954. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  98955. sqlite3WhereContinueLabel(pWInfo),
  98956. sqlite3WhereBreakLabel(pWInfo));
  98957. /* End the database scan loop.
  98958. */
  98959. sqlite3WhereEnd(pWInfo);
  98960. }else{
  98961. /* This case when there exist aggregate functions or a GROUP BY clause
  98962. ** or both */
  98963. NameContext sNC; /* Name context for processing aggregate information */
  98964. int iAMem; /* First Mem address for storing current GROUP BY */
  98965. int iBMem; /* First Mem address for previous GROUP BY */
  98966. int iUseFlag; /* Mem address holding flag indicating that at least
  98967. ** one row of the input to the aggregator has been
  98968. ** processed */
  98969. int iAbortFlag; /* Mem address which causes query abort if positive */
  98970. int groupBySort; /* Rows come from source in GROUP BY order */
  98971. int addrEnd; /* End of processing for this SELECT */
  98972. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  98973. int sortOut = 0; /* Output register from the sorter */
  98974. /* Remove any and all aliases between the result set and the
  98975. ** GROUP BY clause.
  98976. */
  98977. if( pGroupBy ){
  98978. int k; /* Loop counter */
  98979. struct ExprList_item *pItem; /* For looping over expression in a list */
  98980. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  98981. pItem->iAlias = 0;
  98982. }
  98983. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  98984. pItem->iAlias = 0;
  98985. }
  98986. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  98987. }else{
  98988. p->nSelectRow = 1;
  98989. }
  98990. /* Create a label to jump to when we want to abort the query */
  98991. addrEnd = sqlite3VdbeMakeLabel(v);
  98992. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  98993. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  98994. ** SELECT statement.
  98995. */
  98996. memset(&sNC, 0, sizeof(sNC));
  98997. sNC.pParse = pParse;
  98998. sNC.pSrcList = pTabList;
  98999. sNC.pAggInfo = &sAggInfo;
  99000. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  99001. sAggInfo.pGroupBy = pGroupBy;
  99002. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  99003. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  99004. if( pHaving ){
  99005. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  99006. }
  99007. sAggInfo.nAccumulator = sAggInfo.nColumn;
  99008. for(i=0; i<sAggInfo.nFunc; i++){
  99009. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  99010. sNC.ncFlags |= NC_InAggFunc;
  99011. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  99012. sNC.ncFlags &= ~NC_InAggFunc;
  99013. }
  99014. if( db->mallocFailed ) goto select_end;
  99015. /* Processing for aggregates with GROUP BY is very different and
  99016. ** much more complex than aggregates without a GROUP BY.
  99017. */
  99018. if( pGroupBy ){
  99019. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  99020. int j1; /* A-vs-B comparision jump */
  99021. int addrOutputRow; /* Start of subroutine that outputs a result row */
  99022. int regOutputRow; /* Return address register for output subroutine */
  99023. int addrSetAbort; /* Set the abort flag and return */
  99024. int addrTopOfLoop; /* Top of the input loop */
  99025. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  99026. int addrReset; /* Subroutine for resetting the accumulator */
  99027. int regReset; /* Return address register for reset subroutine */
  99028. /* If there is a GROUP BY clause we might need a sorting index to
  99029. ** implement it. Allocate that sorting index now. If it turns out
  99030. ** that we do not need it after all, the OP_SorterOpen instruction
  99031. ** will be converted into a Noop.
  99032. */
  99033. sAggInfo.sortingIdx = pParse->nTab++;
  99034. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  99035. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  99036. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  99037. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  99038. /* Initialize memory locations used by GROUP BY aggregate processing
  99039. */
  99040. iUseFlag = ++pParse->nMem;
  99041. iAbortFlag = ++pParse->nMem;
  99042. regOutputRow = ++pParse->nMem;
  99043. addrOutputRow = sqlite3VdbeMakeLabel(v);
  99044. regReset = ++pParse->nMem;
  99045. addrReset = sqlite3VdbeMakeLabel(v);
  99046. iAMem = pParse->nMem + 1;
  99047. pParse->nMem += pGroupBy->nExpr;
  99048. iBMem = pParse->nMem + 1;
  99049. pParse->nMem += pGroupBy->nExpr;
  99050. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  99051. VdbeComment((v, "clear abort flag"));
  99052. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  99053. VdbeComment((v, "indicate accumulator empty"));
  99054. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  99055. /* Begin a loop that will extract all source rows in GROUP BY order.
  99056. ** This might involve two separate loops with an OP_Sort in between, or
  99057. ** it might be a single loop that uses an index to extract information
  99058. ** in the right order to begin with.
  99059. */
  99060. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  99061. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  99062. WHERE_GROUPBY, 0);
  99063. if( pWInfo==0 ) goto select_end;
  99064. if( sqlite3WhereIsOrdered(pWInfo) ){
  99065. /* The optimizer is able to deliver rows in group by order so
  99066. ** we do not have to sort. The OP_OpenEphemeral table will be
  99067. ** cancelled later because we still need to use the pKeyInfo
  99068. */
  99069. groupBySort = 0;
  99070. }else{
  99071. /* Rows are coming out in undetermined order. We have to push
  99072. ** each row into a sorting index, terminate the first loop,
  99073. ** then loop over the sorting index in order to get the output
  99074. ** in sorted order
  99075. */
  99076. int regBase;
  99077. int regRecord;
  99078. int nCol;
  99079. int nGroupBy;
  99080. explainTempTable(pParse,
  99081. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  99082. "DISTINCT" : "GROUP BY");
  99083. groupBySort = 1;
  99084. nGroupBy = pGroupBy->nExpr;
  99085. nCol = nGroupBy + 1;
  99086. j = nGroupBy+1;
  99087. for(i=0; i<sAggInfo.nColumn; i++){
  99088. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  99089. nCol++;
  99090. j++;
  99091. }
  99092. }
  99093. regBase = sqlite3GetTempRange(pParse, nCol);
  99094. sqlite3ExprCacheClear(pParse);
  99095. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  99096. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  99097. j = nGroupBy+1;
  99098. for(i=0; i<sAggInfo.nColumn; i++){
  99099. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  99100. if( pCol->iSorterColumn>=j ){
  99101. int r1 = j + regBase;
  99102. int r2;
  99103. r2 = sqlite3ExprCodeGetColumn(pParse,
  99104. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  99105. if( r1!=r2 ){
  99106. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  99107. }
  99108. j++;
  99109. }
  99110. }
  99111. regRecord = sqlite3GetTempReg(pParse);
  99112. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  99113. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  99114. sqlite3ReleaseTempReg(pParse, regRecord);
  99115. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  99116. sqlite3WhereEnd(pWInfo);
  99117. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  99118. sortOut = sqlite3GetTempReg(pParse);
  99119. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  99120. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  99121. VdbeComment((v, "GROUP BY sort"));
  99122. sAggInfo.useSortingIdx = 1;
  99123. sqlite3ExprCacheClear(pParse);
  99124. }
  99125. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  99126. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  99127. ** Then compare the current GROUP BY terms against the GROUP BY terms
  99128. ** from the previous row currently stored in a0, a1, a2...
  99129. */
  99130. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  99131. sqlite3ExprCacheClear(pParse);
  99132. if( groupBySort ){
  99133. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  99134. }
  99135. for(j=0; j<pGroupBy->nExpr; j++){
  99136. if( groupBySort ){
  99137. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  99138. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  99139. }else{
  99140. sAggInfo.directMode = 1;
  99141. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  99142. }
  99143. }
  99144. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  99145. (char*)pKeyInfo, P4_KEYINFO);
  99146. j1 = sqlite3VdbeCurrentAddr(v);
  99147. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  99148. /* Generate code that runs whenever the GROUP BY changes.
  99149. ** Changes in the GROUP BY are detected by the previous code
  99150. ** block. If there were no changes, this block is skipped.
  99151. **
  99152. ** This code copies current group by terms in b0,b1,b2,...
  99153. ** over to a0,a1,a2. It then calls the output subroutine
  99154. ** and resets the aggregate accumulator registers in preparation
  99155. ** for the next GROUP BY batch.
  99156. */
  99157. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  99158. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  99159. VdbeComment((v, "output one row"));
  99160. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  99161. VdbeComment((v, "check abort flag"));
  99162. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  99163. VdbeComment((v, "reset accumulator"));
  99164. /* Update the aggregate accumulators based on the content of
  99165. ** the current row
  99166. */
  99167. sqlite3VdbeJumpHere(v, j1);
  99168. updateAccumulator(pParse, &sAggInfo);
  99169. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  99170. VdbeComment((v, "indicate data in accumulator"));
  99171. /* End of the loop
  99172. */
  99173. if( groupBySort ){
  99174. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  99175. }else{
  99176. sqlite3WhereEnd(pWInfo);
  99177. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  99178. }
  99179. /* Output the final row of result
  99180. */
  99181. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  99182. VdbeComment((v, "output final row"));
  99183. /* Jump over the subroutines
  99184. */
  99185. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  99186. /* Generate a subroutine that outputs a single row of the result
  99187. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  99188. ** is less than or equal to zero, the subroutine is a no-op. If
  99189. ** the processing calls for the query to abort, this subroutine
  99190. ** increments the iAbortFlag memory location before returning in
  99191. ** order to signal the caller to abort.
  99192. */
  99193. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  99194. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  99195. VdbeComment((v, "set abort flag"));
  99196. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99197. sqlite3VdbeResolveLabel(v, addrOutputRow);
  99198. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  99199. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  99200. VdbeComment((v, "Groupby result generator entry point"));
  99201. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99202. finalizeAggFunctions(pParse, &sAggInfo);
  99203. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  99204. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  99205. &sDistinct, pDest,
  99206. addrOutputRow+1, addrSetAbort);
  99207. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99208. VdbeComment((v, "end groupby result generator"));
  99209. /* Generate a subroutine that will reset the group-by accumulator
  99210. */
  99211. sqlite3VdbeResolveLabel(v, addrReset);
  99212. resetAccumulator(pParse, &sAggInfo);
  99213. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  99214. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  99215. else {
  99216. ExprList *pDel = 0;
  99217. #ifndef SQLITE_OMIT_BTREECOUNT
  99218. Table *pTab;
  99219. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  99220. /* If isSimpleCount() returns a pointer to a Table structure, then
  99221. ** the SQL statement is of the form:
  99222. **
  99223. ** SELECT count(*) FROM <tbl>
  99224. **
  99225. ** where the Table structure returned represents table <tbl>.
  99226. **
  99227. ** This statement is so common that it is optimized specially. The
  99228. ** OP_Count instruction is executed either on the intkey table that
  99229. ** contains the data for table <tbl> or on one of its indexes. It
  99230. ** is better to execute the op on an index, as indexes are almost
  99231. ** always spread across less pages than their corresponding tables.
  99232. */
  99233. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  99234. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  99235. Index *pIdx; /* Iterator variable */
  99236. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  99237. Index *pBest = 0; /* Best index found so far */
  99238. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  99239. sqlite3CodeVerifySchema(pParse, iDb);
  99240. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  99241. /* Search for the index that has the lowest scan cost.
  99242. **
  99243. ** (2011-04-15) Do not do a full scan of an unordered index.
  99244. **
  99245. ** (2013-10-03) Do not count the entires in a partial index.
  99246. **
  99247. ** In practice the KeyInfo structure will not be used. It is only
  99248. ** passed to keep OP_OpenRead happy.
  99249. */
  99250. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99251. if( pIdx->bUnordered==0
  99252. && pIdx->szIdxRow<pTab->szTabRow
  99253. && pIdx->pPartIdxWhere==0
  99254. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  99255. ){
  99256. pBest = pIdx;
  99257. }
  99258. }
  99259. if( pBest ){
  99260. iRoot = pBest->tnum;
  99261. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  99262. }
  99263. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  99264. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  99265. if( pKeyInfo ){
  99266. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  99267. }
  99268. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  99269. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  99270. explainSimpleCount(pParse, pTab, pBest);
  99271. }else
  99272. #endif /* SQLITE_OMIT_BTREECOUNT */
  99273. {
  99274. /* Check if the query is of one of the following forms:
  99275. **
  99276. ** SELECT min(x) FROM ...
  99277. ** SELECT max(x) FROM ...
  99278. **
  99279. ** If it is, then ask the code in where.c to attempt to sort results
  99280. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  99281. ** If where.c is able to produce results sorted in this order, then
  99282. ** add vdbe code to break out of the processing loop after the
  99283. ** first iteration (since the first iteration of the loop is
  99284. ** guaranteed to operate on the row with the minimum or maximum
  99285. ** value of x, the only row required).
  99286. **
  99287. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  99288. ** modify behavior as follows:
  99289. **
  99290. ** + If the query is a "SELECT min(x)", then the loop coded by
  99291. ** where.c should not iterate over any values with a NULL value
  99292. ** for x.
  99293. **
  99294. ** + The optimizer code in where.c (the thing that decides which
  99295. ** index or indices to use) should place a different priority on
  99296. ** satisfying the 'ORDER BY' clause than it does in other cases.
  99297. ** Refer to code and comments in where.c for details.
  99298. */
  99299. ExprList *pMinMax = 0;
  99300. u8 flag = WHERE_ORDERBY_NORMAL;
  99301. assert( p->pGroupBy==0 );
  99302. assert( flag==0 );
  99303. if( p->pHaving==0 ){
  99304. flag = minMaxQuery(&sAggInfo, &pMinMax);
  99305. }
  99306. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  99307. if( flag ){
  99308. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  99309. pDel = pMinMax;
  99310. if( pMinMax && !db->mallocFailed ){
  99311. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  99312. pMinMax->a[0].pExpr->op = TK_COLUMN;
  99313. }
  99314. }
  99315. /* This case runs if the aggregate has no GROUP BY clause. The
  99316. ** processing is much simpler since there is only a single row
  99317. ** of output.
  99318. */
  99319. resetAccumulator(pParse, &sAggInfo);
  99320. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  99321. if( pWInfo==0 ){
  99322. sqlite3ExprListDelete(db, pDel);
  99323. goto select_end;
  99324. }
  99325. updateAccumulator(pParse, &sAggInfo);
  99326. assert( pMinMax==0 || pMinMax->nExpr==1 );
  99327. if( sqlite3WhereIsOrdered(pWInfo) ){
  99328. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  99329. VdbeComment((v, "%s() by index",
  99330. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  99331. }
  99332. sqlite3WhereEnd(pWInfo);
  99333. finalizeAggFunctions(pParse, &sAggInfo);
  99334. }
  99335. pOrderBy = 0;
  99336. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  99337. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  99338. pDest, addrEnd, addrEnd);
  99339. sqlite3ExprListDelete(db, pDel);
  99340. }
  99341. sqlite3VdbeResolveLabel(v, addrEnd);
  99342. } /* endif aggregate query */
  99343. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  99344. explainTempTable(pParse, "DISTINCT");
  99345. }
  99346. /* If there is an ORDER BY clause, then we need to sort the results
  99347. ** and send them to the callback one by one.
  99348. */
  99349. if( pOrderBy ){
  99350. explainTempTable(pParse, "ORDER BY");
  99351. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  99352. }
  99353. /* Jump here to skip this query
  99354. */
  99355. sqlite3VdbeResolveLabel(v, iEnd);
  99356. /* The SELECT was successfully coded. Set the return code to 0
  99357. ** to indicate no errors.
  99358. */
  99359. rc = 0;
  99360. /* Control jumps to here if an error is encountered above, or upon
  99361. ** successful coding of the SELECT.
  99362. */
  99363. select_end:
  99364. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  99365. /* Identify column names if results of the SELECT are to be output.
  99366. */
  99367. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  99368. generateColumnNames(pParse, pTabList, pEList);
  99369. }
  99370. sqlite3DbFree(db, sAggInfo.aCol);
  99371. sqlite3DbFree(db, sAggInfo.aFunc);
  99372. return rc;
  99373. }
  99374. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  99375. /*
  99376. ** Generate a human-readable description of a the Select object.
  99377. */
  99378. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  99379. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  99380. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  99381. if( p->selFlags & SF_Distinct ){
  99382. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  99383. }
  99384. if( p->selFlags & SF_Aggregate ){
  99385. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  99386. }
  99387. sqlite3ExplainNL(pVdbe);
  99388. sqlite3ExplainPrintf(pVdbe, " ");
  99389. }
  99390. sqlite3ExplainExprList(pVdbe, p->pEList);
  99391. sqlite3ExplainNL(pVdbe);
  99392. if( p->pSrc && p->pSrc->nSrc ){
  99393. int i;
  99394. sqlite3ExplainPrintf(pVdbe, "FROM ");
  99395. sqlite3ExplainPush(pVdbe);
  99396. for(i=0; i<p->pSrc->nSrc; i++){
  99397. struct SrcList_item *pItem = &p->pSrc->a[i];
  99398. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  99399. if( pItem->pSelect ){
  99400. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  99401. if( pItem->pTab ){
  99402. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  99403. }
  99404. }else if( pItem->zName ){
  99405. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  99406. }
  99407. if( pItem->zAlias ){
  99408. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  99409. }
  99410. if( pItem->jointype & JT_LEFT ){
  99411. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  99412. }
  99413. sqlite3ExplainNL(pVdbe);
  99414. }
  99415. sqlite3ExplainPop(pVdbe);
  99416. }
  99417. if( p->pWhere ){
  99418. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  99419. sqlite3ExplainExpr(pVdbe, p->pWhere);
  99420. sqlite3ExplainNL(pVdbe);
  99421. }
  99422. if( p->pGroupBy ){
  99423. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  99424. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  99425. sqlite3ExplainNL(pVdbe);
  99426. }
  99427. if( p->pHaving ){
  99428. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  99429. sqlite3ExplainExpr(pVdbe, p->pHaving);
  99430. sqlite3ExplainNL(pVdbe);
  99431. }
  99432. if( p->pOrderBy ){
  99433. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  99434. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  99435. sqlite3ExplainNL(pVdbe);
  99436. }
  99437. if( p->pLimit ){
  99438. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  99439. sqlite3ExplainExpr(pVdbe, p->pLimit);
  99440. sqlite3ExplainNL(pVdbe);
  99441. }
  99442. if( p->pOffset ){
  99443. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  99444. sqlite3ExplainExpr(pVdbe, p->pOffset);
  99445. sqlite3ExplainNL(pVdbe);
  99446. }
  99447. }
  99448. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  99449. if( p==0 ){
  99450. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  99451. return;
  99452. }
  99453. while( p->pPrior ){
  99454. p->pPrior->pNext = p;
  99455. p = p->pPrior;
  99456. }
  99457. sqlite3ExplainPush(pVdbe);
  99458. while( p ){
  99459. explainOneSelect(pVdbe, p);
  99460. p = p->pNext;
  99461. if( p==0 ) break;
  99462. sqlite3ExplainNL(pVdbe);
  99463. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  99464. }
  99465. sqlite3ExplainPrintf(pVdbe, "END");
  99466. sqlite3ExplainPop(pVdbe);
  99467. }
  99468. /* End of the structure debug printing code
  99469. *****************************************************************************/
  99470. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  99471. /************** End of select.c **********************************************/
  99472. /************** Begin file table.c *******************************************/
  99473. /*
  99474. ** 2001 September 15
  99475. **
  99476. ** The author disclaims copyright to this source code. In place of
  99477. ** a legal notice, here is a blessing:
  99478. **
  99479. ** May you do good and not evil.
  99480. ** May you find forgiveness for yourself and forgive others.
  99481. ** May you share freely, never taking more than you give.
  99482. **
  99483. *************************************************************************
  99484. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  99485. ** interface routines. These are just wrappers around the main
  99486. ** interface routine of sqlite3_exec().
  99487. **
  99488. ** These routines are in a separate files so that they will not be linked
  99489. ** if they are not used.
  99490. */
  99491. /* #include <stdlib.h> */
  99492. /* #include <string.h> */
  99493. #ifndef SQLITE_OMIT_GET_TABLE
  99494. /*
  99495. ** This structure is used to pass data from sqlite3_get_table() through
  99496. ** to the callback function is uses to build the result.
  99497. */
  99498. typedef struct TabResult {
  99499. char **azResult; /* Accumulated output */
  99500. char *zErrMsg; /* Error message text, if an error occurs */
  99501. int nAlloc; /* Slots allocated for azResult[] */
  99502. int nRow; /* Number of rows in the result */
  99503. int nColumn; /* Number of columns in the result */
  99504. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  99505. int rc; /* Return code from sqlite3_exec() */
  99506. } TabResult;
  99507. /*
  99508. ** This routine is called once for each row in the result table. Its job
  99509. ** is to fill in the TabResult structure appropriately, allocating new
  99510. ** memory as necessary.
  99511. */
  99512. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  99513. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  99514. int need; /* Slots needed in p->azResult[] */
  99515. int i; /* Loop counter */
  99516. char *z; /* A single column of result */
  99517. /* Make sure there is enough space in p->azResult to hold everything
  99518. ** we need to remember from this invocation of the callback.
  99519. */
  99520. if( p->nRow==0 && argv!=0 ){
  99521. need = nCol*2;
  99522. }else{
  99523. need = nCol;
  99524. }
  99525. if( p->nData + need > p->nAlloc ){
  99526. char **azNew;
  99527. p->nAlloc = p->nAlloc*2 + need;
  99528. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  99529. if( azNew==0 ) goto malloc_failed;
  99530. p->azResult = azNew;
  99531. }
  99532. /* If this is the first row, then generate an extra row containing
  99533. ** the names of all columns.
  99534. */
  99535. if( p->nRow==0 ){
  99536. p->nColumn = nCol;
  99537. for(i=0; i<nCol; i++){
  99538. z = sqlite3_mprintf("%s", colv[i]);
  99539. if( z==0 ) goto malloc_failed;
  99540. p->azResult[p->nData++] = z;
  99541. }
  99542. }else if( p->nColumn!=nCol ){
  99543. sqlite3_free(p->zErrMsg);
  99544. p->zErrMsg = sqlite3_mprintf(
  99545. "sqlite3_get_table() called with two or more incompatible queries"
  99546. );
  99547. p->rc = SQLITE_ERROR;
  99548. return 1;
  99549. }
  99550. /* Copy over the row data
  99551. */
  99552. if( argv!=0 ){
  99553. for(i=0; i<nCol; i++){
  99554. if( argv[i]==0 ){
  99555. z = 0;
  99556. }else{
  99557. int n = sqlite3Strlen30(argv[i])+1;
  99558. z = sqlite3_malloc( n );
  99559. if( z==0 ) goto malloc_failed;
  99560. memcpy(z, argv[i], n);
  99561. }
  99562. p->azResult[p->nData++] = z;
  99563. }
  99564. p->nRow++;
  99565. }
  99566. return 0;
  99567. malloc_failed:
  99568. p->rc = SQLITE_NOMEM;
  99569. return 1;
  99570. }
  99571. /*
  99572. ** Query the database. But instead of invoking a callback for each row,
  99573. ** malloc() for space to hold the result and return the entire results
  99574. ** at the conclusion of the call.
  99575. **
  99576. ** The result that is written to ***pazResult is held in memory obtained
  99577. ** from malloc(). But the caller cannot free this memory directly.
  99578. ** Instead, the entire table should be passed to sqlite3_free_table() when
  99579. ** the calling procedure is finished using it.
  99580. */
  99581. SQLITE_API int sqlite3_get_table(
  99582. sqlite3 *db, /* The database on which the SQL executes */
  99583. const char *zSql, /* The SQL to be executed */
  99584. char ***pazResult, /* Write the result table here */
  99585. int *pnRow, /* Write the number of rows in the result here */
  99586. int *pnColumn, /* Write the number of columns of result here */
  99587. char **pzErrMsg /* Write error messages here */
  99588. ){
  99589. int rc;
  99590. TabResult res;
  99591. *pazResult = 0;
  99592. if( pnColumn ) *pnColumn = 0;
  99593. if( pnRow ) *pnRow = 0;
  99594. if( pzErrMsg ) *pzErrMsg = 0;
  99595. res.zErrMsg = 0;
  99596. res.nRow = 0;
  99597. res.nColumn = 0;
  99598. res.nData = 1;
  99599. res.nAlloc = 20;
  99600. res.rc = SQLITE_OK;
  99601. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  99602. if( res.azResult==0 ){
  99603. db->errCode = SQLITE_NOMEM;
  99604. return SQLITE_NOMEM;
  99605. }
  99606. res.azResult[0] = 0;
  99607. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  99608. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  99609. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  99610. if( (rc&0xff)==SQLITE_ABORT ){
  99611. sqlite3_free_table(&res.azResult[1]);
  99612. if( res.zErrMsg ){
  99613. if( pzErrMsg ){
  99614. sqlite3_free(*pzErrMsg);
  99615. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  99616. }
  99617. sqlite3_free(res.zErrMsg);
  99618. }
  99619. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  99620. return res.rc;
  99621. }
  99622. sqlite3_free(res.zErrMsg);
  99623. if( rc!=SQLITE_OK ){
  99624. sqlite3_free_table(&res.azResult[1]);
  99625. return rc;
  99626. }
  99627. if( res.nAlloc>res.nData ){
  99628. char **azNew;
  99629. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  99630. if( azNew==0 ){
  99631. sqlite3_free_table(&res.azResult[1]);
  99632. db->errCode = SQLITE_NOMEM;
  99633. return SQLITE_NOMEM;
  99634. }
  99635. res.azResult = azNew;
  99636. }
  99637. *pazResult = &res.azResult[1];
  99638. if( pnColumn ) *pnColumn = res.nColumn;
  99639. if( pnRow ) *pnRow = res.nRow;
  99640. return rc;
  99641. }
  99642. /*
  99643. ** This routine frees the space the sqlite3_get_table() malloced.
  99644. */
  99645. SQLITE_API void sqlite3_free_table(
  99646. char **azResult /* Result returned from from sqlite3_get_table() */
  99647. ){
  99648. if( azResult ){
  99649. int i, n;
  99650. azResult--;
  99651. assert( azResult!=0 );
  99652. n = SQLITE_PTR_TO_INT(azResult[0]);
  99653. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  99654. sqlite3_free(azResult);
  99655. }
  99656. }
  99657. #endif /* SQLITE_OMIT_GET_TABLE */
  99658. /************** End of table.c ***********************************************/
  99659. /************** Begin file trigger.c *****************************************/
  99660. /*
  99661. **
  99662. ** The author disclaims copyright to this source code. In place of
  99663. ** a legal notice, here is a blessing:
  99664. **
  99665. ** May you do good and not evil.
  99666. ** May you find forgiveness for yourself and forgive others.
  99667. ** May you share freely, never taking more than you give.
  99668. **
  99669. *************************************************************************
  99670. ** This file contains the implementation for TRIGGERs
  99671. */
  99672. #ifndef SQLITE_OMIT_TRIGGER
  99673. /*
  99674. ** Delete a linked list of TriggerStep structures.
  99675. */
  99676. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  99677. while( pTriggerStep ){
  99678. TriggerStep * pTmp = pTriggerStep;
  99679. pTriggerStep = pTriggerStep->pNext;
  99680. sqlite3ExprDelete(db, pTmp->pWhere);
  99681. sqlite3ExprListDelete(db, pTmp->pExprList);
  99682. sqlite3SelectDelete(db, pTmp->pSelect);
  99683. sqlite3IdListDelete(db, pTmp->pIdList);
  99684. sqlite3DbFree(db, pTmp);
  99685. }
  99686. }
  99687. /*
  99688. ** Given table pTab, return a list of all the triggers attached to
  99689. ** the table. The list is connected by Trigger.pNext pointers.
  99690. **
  99691. ** All of the triggers on pTab that are in the same database as pTab
  99692. ** are already attached to pTab->pTrigger. But there might be additional
  99693. ** triggers on pTab in the TEMP schema. This routine prepends all
  99694. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  99695. ** and returns the combined list.
  99696. **
  99697. ** To state it another way: This routine returns a list of all triggers
  99698. ** that fire off of pTab. The list will include any TEMP triggers on
  99699. ** pTab as well as the triggers lised in pTab->pTrigger.
  99700. */
  99701. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  99702. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  99703. Trigger *pList = 0; /* List of triggers to return */
  99704. if( pParse->disableTriggers ){
  99705. return 0;
  99706. }
  99707. if( pTmpSchema!=pTab->pSchema ){
  99708. HashElem *p;
  99709. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  99710. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  99711. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  99712. if( pTrig->pTabSchema==pTab->pSchema
  99713. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  99714. ){
  99715. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  99716. pList = pTrig;
  99717. }
  99718. }
  99719. }
  99720. return (pList ? pList : pTab->pTrigger);
  99721. }
  99722. /*
  99723. ** This is called by the parser when it sees a CREATE TRIGGER statement
  99724. ** up to the point of the BEGIN before the trigger actions. A Trigger
  99725. ** structure is generated based on the information available and stored
  99726. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  99727. ** sqlite3FinishTrigger() function is called to complete the trigger
  99728. ** construction process.
  99729. */
  99730. SQLITE_PRIVATE void sqlite3BeginTrigger(
  99731. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  99732. Token *pName1, /* The name of the trigger */
  99733. Token *pName2, /* The name of the trigger */
  99734. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  99735. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  99736. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  99737. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  99738. Expr *pWhen, /* WHEN clause */
  99739. int isTemp, /* True if the TEMPORARY keyword is present */
  99740. int noErr /* Suppress errors if the trigger already exists */
  99741. ){
  99742. Trigger *pTrigger = 0; /* The new trigger */
  99743. Table *pTab; /* Table that the trigger fires off of */
  99744. char *zName = 0; /* Name of the trigger */
  99745. sqlite3 *db = pParse->db; /* The database connection */
  99746. int iDb; /* The database to store the trigger in */
  99747. Token *pName; /* The unqualified db name */
  99748. DbFixer sFix; /* State vector for the DB fixer */
  99749. int iTabDb; /* Index of the database holding pTab */
  99750. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  99751. assert( pName2!=0 );
  99752. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  99753. assert( op>0 && op<0xff );
  99754. if( isTemp ){
  99755. /* If TEMP was specified, then the trigger name may not be qualified. */
  99756. if( pName2->n>0 ){
  99757. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  99758. goto trigger_cleanup;
  99759. }
  99760. iDb = 1;
  99761. pName = pName1;
  99762. }else{
  99763. /* Figure out the db that the trigger will be created in */
  99764. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  99765. if( iDb<0 ){
  99766. goto trigger_cleanup;
  99767. }
  99768. }
  99769. if( !pTableName || db->mallocFailed ){
  99770. goto trigger_cleanup;
  99771. }
  99772. /* A long-standing parser bug is that this syntax was allowed:
  99773. **
  99774. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  99775. ** ^^^^^^^^
  99776. **
  99777. ** To maintain backwards compatibility, ignore the database
  99778. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  99779. */
  99780. if( db->init.busy && iDb!=1 ){
  99781. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  99782. pTableName->a[0].zDatabase = 0;
  99783. }
  99784. /* If the trigger name was unqualified, and the table is a temp table,
  99785. ** then set iDb to 1 to create the trigger in the temporary database.
  99786. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  99787. ** exist, the error is caught by the block below.
  99788. */
  99789. pTab = sqlite3SrcListLookup(pParse, pTableName);
  99790. if( db->init.busy==0 && pName2->n==0 && pTab
  99791. && pTab->pSchema==db->aDb[1].pSchema ){
  99792. iDb = 1;
  99793. }
  99794. /* Ensure the table name matches database name and that the table exists */
  99795. if( db->mallocFailed ) goto trigger_cleanup;
  99796. assert( pTableName->nSrc==1 );
  99797. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  99798. if( sqlite3FixSrcList(&sFix, pTableName) ){
  99799. goto trigger_cleanup;
  99800. }
  99801. pTab = sqlite3SrcListLookup(pParse, pTableName);
  99802. if( !pTab ){
  99803. /* The table does not exist. */
  99804. if( db->init.iDb==1 ){
  99805. /* Ticket #3810.
  99806. ** Normally, whenever a table is dropped, all associated triggers are
  99807. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  99808. ** and the table is dropped by a different database connection, the
  99809. ** trigger is not visible to the database connection that does the
  99810. ** drop so the trigger cannot be dropped. This results in an
  99811. ** "orphaned trigger" - a trigger whose associated table is missing.
  99812. */
  99813. db->init.orphanTrigger = 1;
  99814. }
  99815. goto trigger_cleanup;
  99816. }
  99817. if( IsVirtual(pTab) ){
  99818. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  99819. goto trigger_cleanup;
  99820. }
  99821. /* Check that the trigger name is not reserved and that no trigger of the
  99822. ** specified name exists */
  99823. zName = sqlite3NameFromToken(db, pName);
  99824. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  99825. goto trigger_cleanup;
  99826. }
  99827. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99828. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  99829. zName, sqlite3Strlen30(zName)) ){
  99830. if( !noErr ){
  99831. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  99832. }else{
  99833. assert( !db->init.busy );
  99834. sqlite3CodeVerifySchema(pParse, iDb);
  99835. }
  99836. goto trigger_cleanup;
  99837. }
  99838. /* Do not create a trigger on a system table */
  99839. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  99840. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  99841. pParse->nErr++;
  99842. goto trigger_cleanup;
  99843. }
  99844. /* INSTEAD of triggers are only for views and views only support INSTEAD
  99845. ** of triggers.
  99846. */
  99847. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  99848. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  99849. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  99850. goto trigger_cleanup;
  99851. }
  99852. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  99853. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  99854. " trigger on table: %S", pTableName, 0);
  99855. goto trigger_cleanup;
  99856. }
  99857. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99858. #ifndef SQLITE_OMIT_AUTHORIZATION
  99859. {
  99860. int code = SQLITE_CREATE_TRIGGER;
  99861. const char *zDb = db->aDb[iTabDb].zName;
  99862. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  99863. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  99864. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  99865. goto trigger_cleanup;
  99866. }
  99867. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  99868. goto trigger_cleanup;
  99869. }
  99870. }
  99871. #endif
  99872. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  99873. ** cannot appear on views. So we might as well translate every
  99874. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  99875. ** elsewhere.
  99876. */
  99877. if (tr_tm == TK_INSTEAD){
  99878. tr_tm = TK_BEFORE;
  99879. }
  99880. /* Build the Trigger object */
  99881. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  99882. if( pTrigger==0 ) goto trigger_cleanup;
  99883. pTrigger->zName = zName;
  99884. zName = 0;
  99885. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  99886. pTrigger->pSchema = db->aDb[iDb].pSchema;
  99887. pTrigger->pTabSchema = pTab->pSchema;
  99888. pTrigger->op = (u8)op;
  99889. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  99890. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  99891. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  99892. assert( pParse->pNewTrigger==0 );
  99893. pParse->pNewTrigger = pTrigger;
  99894. trigger_cleanup:
  99895. sqlite3DbFree(db, zName);
  99896. sqlite3SrcListDelete(db, pTableName);
  99897. sqlite3IdListDelete(db, pColumns);
  99898. sqlite3ExprDelete(db, pWhen);
  99899. if( !pParse->pNewTrigger ){
  99900. sqlite3DeleteTrigger(db, pTrigger);
  99901. }else{
  99902. assert( pParse->pNewTrigger==pTrigger );
  99903. }
  99904. }
  99905. /*
  99906. ** This routine is called after all of the trigger actions have been parsed
  99907. ** in order to complete the process of building the trigger.
  99908. */
  99909. SQLITE_PRIVATE void sqlite3FinishTrigger(
  99910. Parse *pParse, /* Parser context */
  99911. TriggerStep *pStepList, /* The triggered program */
  99912. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  99913. ){
  99914. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  99915. char *zName; /* Name of trigger */
  99916. sqlite3 *db = pParse->db; /* The database */
  99917. DbFixer sFix; /* Fixer object */
  99918. int iDb; /* Database containing the trigger */
  99919. Token nameToken; /* Trigger name for error reporting */
  99920. pParse->pNewTrigger = 0;
  99921. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  99922. zName = pTrig->zName;
  99923. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  99924. pTrig->step_list = pStepList;
  99925. while( pStepList ){
  99926. pStepList->pTrig = pTrig;
  99927. pStepList = pStepList->pNext;
  99928. }
  99929. nameToken.z = pTrig->zName;
  99930. nameToken.n = sqlite3Strlen30(nameToken.z);
  99931. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  99932. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  99933. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  99934. ){
  99935. goto triggerfinish_cleanup;
  99936. }
  99937. /* if we are not initializing,
  99938. ** build the sqlite_master entry
  99939. */
  99940. if( !db->init.busy ){
  99941. Vdbe *v;
  99942. char *z;
  99943. /* Make an entry in the sqlite_master table */
  99944. v = sqlite3GetVdbe(pParse);
  99945. if( v==0 ) goto triggerfinish_cleanup;
  99946. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99947. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  99948. sqlite3NestedParse(pParse,
  99949. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  99950. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  99951. pTrig->table, z);
  99952. sqlite3DbFree(db, z);
  99953. sqlite3ChangeCookie(pParse, iDb);
  99954. sqlite3VdbeAddParseSchemaOp(v, iDb,
  99955. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  99956. }
  99957. if( db->init.busy ){
  99958. Trigger *pLink = pTrig;
  99959. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  99960. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99961. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  99962. if( pTrig ){
  99963. db->mallocFailed = 1;
  99964. }else if( pLink->pSchema==pLink->pTabSchema ){
  99965. Table *pTab;
  99966. int n = sqlite3Strlen30(pLink->table);
  99967. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  99968. assert( pTab!=0 );
  99969. pLink->pNext = pTab->pTrigger;
  99970. pTab->pTrigger = pLink;
  99971. }
  99972. }
  99973. triggerfinish_cleanup:
  99974. sqlite3DeleteTrigger(db, pTrig);
  99975. assert( !pParse->pNewTrigger );
  99976. sqlite3DeleteTriggerStep(db, pStepList);
  99977. }
  99978. /*
  99979. ** Turn a SELECT statement (that the pSelect parameter points to) into
  99980. ** a trigger step. Return a pointer to a TriggerStep structure.
  99981. **
  99982. ** The parser calls this routine when it finds a SELECT statement in
  99983. ** body of a TRIGGER.
  99984. */
  99985. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  99986. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  99987. if( pTriggerStep==0 ) {
  99988. sqlite3SelectDelete(db, pSelect);
  99989. return 0;
  99990. }
  99991. pTriggerStep->op = TK_SELECT;
  99992. pTriggerStep->pSelect = pSelect;
  99993. pTriggerStep->orconf = OE_Default;
  99994. return pTriggerStep;
  99995. }
  99996. /*
  99997. ** Allocate space to hold a new trigger step. The allocated space
  99998. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  99999. **
  100000. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  100001. */
  100002. static TriggerStep *triggerStepAllocate(
  100003. sqlite3 *db, /* Database connection */
  100004. u8 op, /* Trigger opcode */
  100005. Token *pName /* The target name */
  100006. ){
  100007. TriggerStep *pTriggerStep;
  100008. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  100009. if( pTriggerStep ){
  100010. char *z = (char*)&pTriggerStep[1];
  100011. memcpy(z, pName->z, pName->n);
  100012. pTriggerStep->target.z = z;
  100013. pTriggerStep->target.n = pName->n;
  100014. pTriggerStep->op = op;
  100015. }
  100016. return pTriggerStep;
  100017. }
  100018. /*
  100019. ** Build a trigger step out of an INSERT statement. Return a pointer
  100020. ** to the new trigger step.
  100021. **
  100022. ** The parser calls this routine when it sees an INSERT inside the
  100023. ** body of a trigger.
  100024. */
  100025. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  100026. sqlite3 *db, /* The database connection */
  100027. Token *pTableName, /* Name of the table into which we insert */
  100028. IdList *pColumn, /* List of columns in pTableName to insert into */
  100029. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  100030. Select *pSelect, /* A SELECT statement that supplies values */
  100031. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  100032. ){
  100033. TriggerStep *pTriggerStep;
  100034. assert(pEList == 0 || pSelect == 0);
  100035. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  100036. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  100037. if( pTriggerStep ){
  100038. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  100039. pTriggerStep->pIdList = pColumn;
  100040. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  100041. pTriggerStep->orconf = orconf;
  100042. }else{
  100043. sqlite3IdListDelete(db, pColumn);
  100044. }
  100045. sqlite3ExprListDelete(db, pEList);
  100046. sqlite3SelectDelete(db, pSelect);
  100047. return pTriggerStep;
  100048. }
  100049. /*
  100050. ** Construct a trigger step that implements an UPDATE statement and return
  100051. ** a pointer to that trigger step. The parser calls this routine when it
  100052. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  100053. */
  100054. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  100055. sqlite3 *db, /* The database connection */
  100056. Token *pTableName, /* Name of the table to be updated */
  100057. ExprList *pEList, /* The SET clause: list of column and new values */
  100058. Expr *pWhere, /* The WHERE clause */
  100059. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  100060. ){
  100061. TriggerStep *pTriggerStep;
  100062. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  100063. if( pTriggerStep ){
  100064. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  100065. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  100066. pTriggerStep->orconf = orconf;
  100067. }
  100068. sqlite3ExprListDelete(db, pEList);
  100069. sqlite3ExprDelete(db, pWhere);
  100070. return pTriggerStep;
  100071. }
  100072. /*
  100073. ** Construct a trigger step that implements a DELETE statement and return
  100074. ** a pointer to that trigger step. The parser calls this routine when it
  100075. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  100076. */
  100077. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  100078. sqlite3 *db, /* Database connection */
  100079. Token *pTableName, /* The table from which rows are deleted */
  100080. Expr *pWhere /* The WHERE clause */
  100081. ){
  100082. TriggerStep *pTriggerStep;
  100083. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  100084. if( pTriggerStep ){
  100085. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  100086. pTriggerStep->orconf = OE_Default;
  100087. }
  100088. sqlite3ExprDelete(db, pWhere);
  100089. return pTriggerStep;
  100090. }
  100091. /*
  100092. ** Recursively delete a Trigger structure
  100093. */
  100094. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  100095. if( pTrigger==0 ) return;
  100096. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  100097. sqlite3DbFree(db, pTrigger->zName);
  100098. sqlite3DbFree(db, pTrigger->table);
  100099. sqlite3ExprDelete(db, pTrigger->pWhen);
  100100. sqlite3IdListDelete(db, pTrigger->pColumns);
  100101. sqlite3DbFree(db, pTrigger);
  100102. }
  100103. /*
  100104. ** This function is called to drop a trigger from the database schema.
  100105. **
  100106. ** This may be called directly from the parser and therefore identifies
  100107. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  100108. ** same job as this routine except it takes a pointer to the trigger
  100109. ** instead of the trigger name.
  100110. **/
  100111. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  100112. Trigger *pTrigger = 0;
  100113. int i;
  100114. const char *zDb;
  100115. const char *zName;
  100116. int nName;
  100117. sqlite3 *db = pParse->db;
  100118. if( db->mallocFailed ) goto drop_trigger_cleanup;
  100119. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100120. goto drop_trigger_cleanup;
  100121. }
  100122. assert( pName->nSrc==1 );
  100123. zDb = pName->a[0].zDatabase;
  100124. zName = pName->a[0].zName;
  100125. nName = sqlite3Strlen30(zName);
  100126. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  100127. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  100128. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  100129. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  100130. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  100131. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  100132. if( pTrigger ) break;
  100133. }
  100134. if( !pTrigger ){
  100135. if( !noErr ){
  100136. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  100137. }else{
  100138. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  100139. }
  100140. pParse->checkSchema = 1;
  100141. goto drop_trigger_cleanup;
  100142. }
  100143. sqlite3DropTriggerPtr(pParse, pTrigger);
  100144. drop_trigger_cleanup:
  100145. sqlite3SrcListDelete(db, pName);
  100146. }
  100147. /*
  100148. ** Return a pointer to the Table structure for the table that a trigger
  100149. ** is set on.
  100150. */
  100151. static Table *tableOfTrigger(Trigger *pTrigger){
  100152. int n = sqlite3Strlen30(pTrigger->table);
  100153. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  100154. }
  100155. /*
  100156. ** Drop a trigger given a pointer to that trigger.
  100157. */
  100158. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  100159. Table *pTable;
  100160. Vdbe *v;
  100161. sqlite3 *db = pParse->db;
  100162. int iDb;
  100163. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  100164. assert( iDb>=0 && iDb<db->nDb );
  100165. pTable = tableOfTrigger(pTrigger);
  100166. assert( pTable );
  100167. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  100168. #ifndef SQLITE_OMIT_AUTHORIZATION
  100169. {
  100170. int code = SQLITE_DROP_TRIGGER;
  100171. const char *zDb = db->aDb[iDb].zName;
  100172. const char *zTab = SCHEMA_TABLE(iDb);
  100173. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  100174. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  100175. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  100176. return;
  100177. }
  100178. }
  100179. #endif
  100180. /* Generate code to destroy the database record of the trigger.
  100181. */
  100182. assert( pTable!=0 );
  100183. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  100184. int base;
  100185. static const VdbeOpList dropTrigger[] = {
  100186. { OP_Rewind, 0, ADDR(9), 0},
  100187. { OP_String8, 0, 1, 0}, /* 1 */
  100188. { OP_Column, 0, 1, 2},
  100189. { OP_Ne, 2, ADDR(8), 1},
  100190. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  100191. { OP_Column, 0, 0, 2},
  100192. { OP_Ne, 2, ADDR(8), 1},
  100193. { OP_Delete, 0, 0, 0},
  100194. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  100195. };
  100196. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100197. sqlite3OpenMasterTable(pParse, iDb);
  100198. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  100199. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  100200. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  100201. sqlite3ChangeCookie(pParse, iDb);
  100202. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  100203. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  100204. if( pParse->nMem<3 ){
  100205. pParse->nMem = 3;
  100206. }
  100207. }
  100208. }
  100209. /*
  100210. ** Remove a trigger from the hash tables of the sqlite* pointer.
  100211. */
  100212. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  100213. Trigger *pTrigger;
  100214. Hash *pHash;
  100215. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100216. pHash = &(db->aDb[iDb].pSchema->trigHash);
  100217. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  100218. if( ALWAYS(pTrigger) ){
  100219. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  100220. Table *pTab = tableOfTrigger(pTrigger);
  100221. Trigger **pp;
  100222. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  100223. *pp = (*pp)->pNext;
  100224. }
  100225. sqlite3DeleteTrigger(db, pTrigger);
  100226. db->flags |= SQLITE_InternChanges;
  100227. }
  100228. }
  100229. /*
  100230. ** pEList is the SET clause of an UPDATE statement. Each entry
  100231. ** in pEList is of the format <id>=<expr>. If any of the entries
  100232. ** in pEList have an <id> which matches an identifier in pIdList,
  100233. ** then return TRUE. If pIdList==NULL, then it is considered a
  100234. ** wildcard that matches anything. Likewise if pEList==NULL then
  100235. ** it matches anything so always return true. Return false only
  100236. ** if there is no match.
  100237. */
  100238. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  100239. int e;
  100240. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  100241. for(e=0; e<pEList->nExpr; e++){
  100242. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  100243. }
  100244. return 0;
  100245. }
  100246. /*
  100247. ** Return a list of all triggers on table pTab if there exists at least
  100248. ** one trigger that must be fired when an operation of type 'op' is
  100249. ** performed on the table, and, if that operation is an UPDATE, if at
  100250. ** least one of the columns in pChanges is being modified.
  100251. */
  100252. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  100253. Parse *pParse, /* Parse context */
  100254. Table *pTab, /* The table the contains the triggers */
  100255. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  100256. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  100257. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100258. ){
  100259. int mask = 0;
  100260. Trigger *pList = 0;
  100261. Trigger *p;
  100262. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  100263. pList = sqlite3TriggerList(pParse, pTab);
  100264. }
  100265. assert( pList==0 || IsVirtual(pTab)==0 );
  100266. for(p=pList; p; p=p->pNext){
  100267. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  100268. mask |= p->tr_tm;
  100269. }
  100270. }
  100271. if( pMask ){
  100272. *pMask = mask;
  100273. }
  100274. return (mask ? pList : 0);
  100275. }
  100276. /*
  100277. ** Convert the pStep->target token into a SrcList and return a pointer
  100278. ** to that SrcList.
  100279. **
  100280. ** This routine adds a specific database name, if needed, to the target when
  100281. ** forming the SrcList. This prevents a trigger in one database from
  100282. ** referring to a target in another database. An exception is when the
  100283. ** trigger is in TEMP in which case it can refer to any other database it
  100284. ** wants.
  100285. */
  100286. static SrcList *targetSrcList(
  100287. Parse *pParse, /* The parsing context */
  100288. TriggerStep *pStep /* The trigger containing the target token */
  100289. ){
  100290. int iDb; /* Index of the database to use */
  100291. SrcList *pSrc; /* SrcList to be returned */
  100292. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  100293. if( pSrc ){
  100294. assert( pSrc->nSrc>0 );
  100295. assert( pSrc->a!=0 );
  100296. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  100297. if( iDb==0 || iDb>=2 ){
  100298. sqlite3 *db = pParse->db;
  100299. assert( iDb<pParse->db->nDb );
  100300. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  100301. }
  100302. }
  100303. return pSrc;
  100304. }
  100305. /*
  100306. ** Generate VDBE code for the statements inside the body of a single
  100307. ** trigger.
  100308. */
  100309. static int codeTriggerProgram(
  100310. Parse *pParse, /* The parser context */
  100311. TriggerStep *pStepList, /* List of statements inside the trigger body */
  100312. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  100313. ){
  100314. TriggerStep *pStep;
  100315. Vdbe *v = pParse->pVdbe;
  100316. sqlite3 *db = pParse->db;
  100317. assert( pParse->pTriggerTab && pParse->pToplevel );
  100318. assert( pStepList );
  100319. assert( v!=0 );
  100320. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  100321. /* Figure out the ON CONFLICT policy that will be used for this step
  100322. ** of the trigger program. If the statement that caused this trigger
  100323. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  100324. ** the ON CONFLICT policy that was specified as part of the trigger
  100325. ** step statement. Example:
  100326. **
  100327. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  100328. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  100329. ** END;
  100330. **
  100331. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  100332. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  100333. */
  100334. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  100335. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  100336. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  100337. ** that it is not safe to refactor constants (this happens after the
  100338. ** start of the first loop in the SQL statement is coded - at that
  100339. ** point code may be conditionally executed, so it is no longer safe to
  100340. ** initialize constant register values). */
  100341. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  100342. pParse->cookieGoto = 0;
  100343. switch( pStep->op ){
  100344. case TK_UPDATE: {
  100345. sqlite3Update(pParse,
  100346. targetSrcList(pParse, pStep),
  100347. sqlite3ExprListDup(db, pStep->pExprList, 0),
  100348. sqlite3ExprDup(db, pStep->pWhere, 0),
  100349. pParse->eOrconf
  100350. );
  100351. break;
  100352. }
  100353. case TK_INSERT: {
  100354. sqlite3Insert(pParse,
  100355. targetSrcList(pParse, pStep),
  100356. sqlite3ExprListDup(db, pStep->pExprList, 0),
  100357. sqlite3SelectDup(db, pStep->pSelect, 0),
  100358. sqlite3IdListDup(db, pStep->pIdList),
  100359. pParse->eOrconf
  100360. );
  100361. break;
  100362. }
  100363. case TK_DELETE: {
  100364. sqlite3DeleteFrom(pParse,
  100365. targetSrcList(pParse, pStep),
  100366. sqlite3ExprDup(db, pStep->pWhere, 0)
  100367. );
  100368. break;
  100369. }
  100370. default: assert( pStep->op==TK_SELECT ); {
  100371. SelectDest sDest;
  100372. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  100373. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  100374. sqlite3Select(pParse, pSelect, &sDest);
  100375. sqlite3SelectDelete(db, pSelect);
  100376. break;
  100377. }
  100378. }
  100379. if( pStep->op!=TK_SELECT ){
  100380. sqlite3VdbeAddOp0(v, OP_ResetCount);
  100381. }
  100382. }
  100383. return 0;
  100384. }
  100385. #ifdef SQLITE_DEBUG
  100386. /*
  100387. ** This function is used to add VdbeComment() annotations to a VDBE
  100388. ** program. It is not used in production code, only for debugging.
  100389. */
  100390. static const char *onErrorText(int onError){
  100391. switch( onError ){
  100392. case OE_Abort: return "abort";
  100393. case OE_Rollback: return "rollback";
  100394. case OE_Fail: return "fail";
  100395. case OE_Replace: return "replace";
  100396. case OE_Ignore: return "ignore";
  100397. case OE_Default: return "default";
  100398. }
  100399. return "n/a";
  100400. }
  100401. #endif
  100402. /*
  100403. ** Parse context structure pFrom has just been used to create a sub-vdbe
  100404. ** (trigger program). If an error has occurred, transfer error information
  100405. ** from pFrom to pTo.
  100406. */
  100407. static void transferParseError(Parse *pTo, Parse *pFrom){
  100408. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  100409. assert( pTo->zErrMsg==0 || pTo->nErr );
  100410. if( pTo->nErr==0 ){
  100411. pTo->zErrMsg = pFrom->zErrMsg;
  100412. pTo->nErr = pFrom->nErr;
  100413. }else{
  100414. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  100415. }
  100416. }
  100417. /*
  100418. ** Create and populate a new TriggerPrg object with a sub-program
  100419. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  100420. */
  100421. static TriggerPrg *codeRowTrigger(
  100422. Parse *pParse, /* Current parse context */
  100423. Trigger *pTrigger, /* Trigger to code */
  100424. Table *pTab, /* The table pTrigger is attached to */
  100425. int orconf /* ON CONFLICT policy to code trigger program with */
  100426. ){
  100427. Parse *pTop = sqlite3ParseToplevel(pParse);
  100428. sqlite3 *db = pParse->db; /* Database handle */
  100429. TriggerPrg *pPrg; /* Value to return */
  100430. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  100431. Vdbe *v; /* Temporary VM */
  100432. NameContext sNC; /* Name context for sub-vdbe */
  100433. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  100434. Parse *pSubParse; /* Parse context for sub-vdbe */
  100435. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  100436. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  100437. assert( pTop->pVdbe );
  100438. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  100439. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  100440. ** list of the top-level Parse object sooner rather than later. */
  100441. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  100442. if( !pPrg ) return 0;
  100443. pPrg->pNext = pTop->pTriggerPrg;
  100444. pTop->pTriggerPrg = pPrg;
  100445. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  100446. if( !pProgram ) return 0;
  100447. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  100448. pPrg->pTrigger = pTrigger;
  100449. pPrg->orconf = orconf;
  100450. pPrg->aColmask[0] = 0xffffffff;
  100451. pPrg->aColmask[1] = 0xffffffff;
  100452. /* Allocate and populate a new Parse context to use for coding the
  100453. ** trigger sub-program. */
  100454. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  100455. if( !pSubParse ) return 0;
  100456. memset(&sNC, 0, sizeof(sNC));
  100457. sNC.pParse = pSubParse;
  100458. pSubParse->db = db;
  100459. pSubParse->pTriggerTab = pTab;
  100460. pSubParse->pToplevel = pTop;
  100461. pSubParse->zAuthContext = pTrigger->zName;
  100462. pSubParse->eTriggerOp = pTrigger->op;
  100463. pSubParse->nQueryLoop = pParse->nQueryLoop;
  100464. v = sqlite3GetVdbe(pSubParse);
  100465. if( v ){
  100466. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  100467. pTrigger->zName, onErrorText(orconf),
  100468. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  100469. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  100470. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  100471. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  100472. pTab->zName
  100473. ));
  100474. #ifndef SQLITE_OMIT_TRACE
  100475. sqlite3VdbeChangeP4(v, -1,
  100476. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  100477. );
  100478. #endif
  100479. /* If one was specified, code the WHEN clause. If it evaluates to false
  100480. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  100481. ** OP_Halt inserted at the end of the program. */
  100482. if( pTrigger->pWhen ){
  100483. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  100484. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  100485. && db->mallocFailed==0
  100486. ){
  100487. iEndTrigger = sqlite3VdbeMakeLabel(v);
  100488. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  100489. }
  100490. sqlite3ExprDelete(db, pWhen);
  100491. }
  100492. /* Code the trigger program into the sub-vdbe. */
  100493. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  100494. /* Insert an OP_Halt at the end of the sub-program. */
  100495. if( iEndTrigger ){
  100496. sqlite3VdbeResolveLabel(v, iEndTrigger);
  100497. }
  100498. sqlite3VdbeAddOp0(v, OP_Halt);
  100499. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  100500. transferParseError(pParse, pSubParse);
  100501. if( db->mallocFailed==0 ){
  100502. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  100503. }
  100504. pProgram->nMem = pSubParse->nMem;
  100505. pProgram->nCsr = pSubParse->nTab;
  100506. pProgram->nOnce = pSubParse->nOnce;
  100507. pProgram->token = (void *)pTrigger;
  100508. pPrg->aColmask[0] = pSubParse->oldmask;
  100509. pPrg->aColmask[1] = pSubParse->newmask;
  100510. sqlite3VdbeDelete(v);
  100511. }
  100512. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  100513. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  100514. sqlite3StackFree(db, pSubParse);
  100515. return pPrg;
  100516. }
  100517. /*
  100518. ** Return a pointer to a TriggerPrg object containing the sub-program for
  100519. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  100520. ** TriggerPrg object exists, a new object is allocated and populated before
  100521. ** being returned.
  100522. */
  100523. static TriggerPrg *getRowTrigger(
  100524. Parse *pParse, /* Current parse context */
  100525. Trigger *pTrigger, /* Trigger to code */
  100526. Table *pTab, /* The table trigger pTrigger is attached to */
  100527. int orconf /* ON CONFLICT algorithm. */
  100528. ){
  100529. Parse *pRoot = sqlite3ParseToplevel(pParse);
  100530. TriggerPrg *pPrg;
  100531. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  100532. /* It may be that this trigger has already been coded (or is in the
  100533. ** process of being coded). If this is the case, then an entry with
  100534. ** a matching TriggerPrg.pTrigger field will be present somewhere
  100535. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  100536. for(pPrg=pRoot->pTriggerPrg;
  100537. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  100538. pPrg=pPrg->pNext
  100539. );
  100540. /* If an existing TriggerPrg could not be located, create a new one. */
  100541. if( !pPrg ){
  100542. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  100543. }
  100544. return pPrg;
  100545. }
  100546. /*
  100547. ** Generate code for the trigger program associated with trigger p on
  100548. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  100549. ** function are the same as those described in the header function for
  100550. ** sqlite3CodeRowTrigger()
  100551. */
  100552. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  100553. Parse *pParse, /* Parse context */
  100554. Trigger *p, /* Trigger to code */
  100555. Table *pTab, /* The table to code triggers from */
  100556. int reg, /* Reg array containing OLD.* and NEW.* values */
  100557. int orconf, /* ON CONFLICT policy */
  100558. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  100559. ){
  100560. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  100561. TriggerPrg *pPrg;
  100562. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  100563. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  100564. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  100565. ** is a pointer to the sub-vdbe containing the trigger program. */
  100566. if( pPrg ){
  100567. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  100568. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  100569. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  100570. VdbeComment(
  100571. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  100572. /* Set the P5 operand of the OP_Program instruction to non-zero if
  100573. ** recursive invocation of this trigger program is disallowed. Recursive
  100574. ** invocation is disallowed if (a) the sub-program is really a trigger,
  100575. ** not a foreign key action, and (b) the flag to enable recursive triggers
  100576. ** is clear. */
  100577. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  100578. }
  100579. }
  100580. /*
  100581. ** This is called to code the required FOR EACH ROW triggers for an operation
  100582. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  100583. ** is given by the op parameter. The tr_tm parameter determines whether the
  100584. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  100585. ** parameter pChanges is passed the list of columns being modified.
  100586. **
  100587. ** If there are no triggers that fire at the specified time for the specified
  100588. ** operation on pTab, this function is a no-op.
  100589. **
  100590. ** The reg argument is the address of the first in an array of registers
  100591. ** that contain the values substituted for the new.* and old.* references
  100592. ** in the trigger program. If N is the number of columns in table pTab
  100593. ** (a copy of pTab->nCol), then registers are populated as follows:
  100594. **
  100595. ** Register Contains
  100596. ** ------------------------------------------------------
  100597. ** reg+0 OLD.rowid
  100598. ** reg+1 OLD.* value of left-most column of pTab
  100599. ** ... ...
  100600. ** reg+N OLD.* value of right-most column of pTab
  100601. ** reg+N+1 NEW.rowid
  100602. ** reg+N+2 OLD.* value of left-most column of pTab
  100603. ** ... ...
  100604. ** reg+N+N+1 NEW.* value of right-most column of pTab
  100605. **
  100606. ** For ON DELETE triggers, the registers containing the NEW.* values will
  100607. ** never be accessed by the trigger program, so they are not allocated or
  100608. ** populated by the caller (there is no data to populate them with anyway).
  100609. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  100610. ** are never accessed, and so are not allocated by the caller. So, for an
  100611. ** ON INSERT trigger, the value passed to this function as parameter reg
  100612. ** is not a readable register, although registers (reg+N) through
  100613. ** (reg+N+N+1) are.
  100614. **
  100615. ** Parameter orconf is the default conflict resolution algorithm for the
  100616. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  100617. ** is the instruction that control should jump to if a trigger program
  100618. ** raises an IGNORE exception.
  100619. */
  100620. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  100621. Parse *pParse, /* Parse context */
  100622. Trigger *pTrigger, /* List of triggers on table pTab */
  100623. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  100624. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  100625. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  100626. Table *pTab, /* The table to code triggers from */
  100627. int reg, /* The first in an array of registers (see above) */
  100628. int orconf, /* ON CONFLICT policy */
  100629. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  100630. ){
  100631. Trigger *p; /* Used to iterate through pTrigger list */
  100632. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  100633. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  100634. assert( (op==TK_UPDATE)==(pChanges!=0) );
  100635. for(p=pTrigger; p; p=p->pNext){
  100636. /* Sanity checking: The schema for the trigger and for the table are
  100637. ** always defined. The trigger must be in the same schema as the table
  100638. ** or else it must be a TEMP trigger. */
  100639. assert( p->pSchema!=0 );
  100640. assert( p->pTabSchema!=0 );
  100641. assert( p->pSchema==p->pTabSchema
  100642. || p->pSchema==pParse->db->aDb[1].pSchema );
  100643. /* Determine whether we should code this trigger */
  100644. if( p->op==op
  100645. && p->tr_tm==tr_tm
  100646. && checkColumnOverlap(p->pColumns, pChanges)
  100647. ){
  100648. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  100649. }
  100650. }
  100651. }
  100652. /*
  100653. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  100654. ** This function returns a 32-bit bitmask indicating which columns of the
  100655. ** old.* or new.* tables actually are used by triggers. This information
  100656. ** may be used by the caller, for example, to avoid having to load the entire
  100657. ** old.* record into memory when executing an UPDATE or DELETE command.
  100658. **
  100659. ** Bit 0 of the returned mask is set if the left-most column of the
  100660. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  100661. ** the second leftmost column value is required, and so on. If there
  100662. ** are more than 32 columns in the table, and at least one of the columns
  100663. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  100664. **
  100665. ** It is not possible to determine if the old.rowid or new.rowid column is
  100666. ** accessed by triggers. The caller must always assume that it is.
  100667. **
  100668. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  100669. ** applies to the old.* table. If 1, the new.* table.
  100670. **
  100671. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  100672. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  100673. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  100674. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  100675. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  100676. */
  100677. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  100678. Parse *pParse, /* Parse context */
  100679. Trigger *pTrigger, /* List of triggers on table pTab */
  100680. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  100681. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  100682. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100683. Table *pTab, /* The table to code triggers from */
  100684. int orconf /* Default ON CONFLICT policy for trigger steps */
  100685. ){
  100686. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  100687. u32 mask = 0;
  100688. Trigger *p;
  100689. assert( isNew==1 || isNew==0 );
  100690. for(p=pTrigger; p; p=p->pNext){
  100691. if( p->op==op && (tr_tm&p->tr_tm)
  100692. && checkColumnOverlap(p->pColumns,pChanges)
  100693. ){
  100694. TriggerPrg *pPrg;
  100695. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  100696. if( pPrg ){
  100697. mask |= pPrg->aColmask[isNew];
  100698. }
  100699. }
  100700. }
  100701. return mask;
  100702. }
  100703. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  100704. /************** End of trigger.c *********************************************/
  100705. /************** Begin file update.c ******************************************/
  100706. /*
  100707. ** 2001 September 15
  100708. **
  100709. ** The author disclaims copyright to this source code. In place of
  100710. ** a legal notice, here is a blessing:
  100711. **
  100712. ** May you do good and not evil.
  100713. ** May you find forgiveness for yourself and forgive others.
  100714. ** May you share freely, never taking more than you give.
  100715. **
  100716. *************************************************************************
  100717. ** This file contains C code routines that are called by the parser
  100718. ** to handle UPDATE statements.
  100719. */
  100720. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100721. /* Forward declaration */
  100722. static void updateVirtualTable(
  100723. Parse *pParse, /* The parsing context */
  100724. SrcList *pSrc, /* The virtual table to be modified */
  100725. Table *pTab, /* The virtual table */
  100726. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  100727. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  100728. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  100729. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  100730. int onError /* ON CONFLICT strategy */
  100731. );
  100732. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  100733. /*
  100734. ** The most recently coded instruction was an OP_Column to retrieve the
  100735. ** i-th column of table pTab. This routine sets the P4 parameter of the
  100736. ** OP_Column to the default value, if any.
  100737. **
  100738. ** The default value of a column is specified by a DEFAULT clause in the
  100739. ** column definition. This was either supplied by the user when the table
  100740. ** was created, or added later to the table definition by an ALTER TABLE
  100741. ** command. If the latter, then the row-records in the table btree on disk
  100742. ** may not contain a value for the column and the default value, taken
  100743. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  100744. ** If the former, then all row-records are guaranteed to include a value
  100745. ** for the column and the P4 value is not required.
  100746. **
  100747. ** Column definitions created by an ALTER TABLE command may only have
  100748. ** literal default values specified: a number, null or a string. (If a more
  100749. ** complicated default expression value was provided, it is evaluated
  100750. ** when the ALTER TABLE is executed and one of the literal values written
  100751. ** into the sqlite_master table.)
  100752. **
  100753. ** Therefore, the P4 parameter is only required if the default value for
  100754. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  100755. ** function is capable of transforming these types of expressions into
  100756. ** sqlite3_value objects.
  100757. **
  100758. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  100759. ** on register iReg. This is used when an equivalent integer value is
  100760. ** stored in place of an 8-byte floating point value in order to save
  100761. ** space.
  100762. */
  100763. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  100764. assert( pTab!=0 );
  100765. if( !pTab->pSelect ){
  100766. sqlite3_value *pValue = 0;
  100767. u8 enc = ENC(sqlite3VdbeDb(v));
  100768. Column *pCol = &pTab->aCol[i];
  100769. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  100770. assert( i<pTab->nCol );
  100771. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  100772. pCol->affinity, &pValue);
  100773. if( pValue ){
  100774. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  100775. }
  100776. #ifndef SQLITE_OMIT_FLOATING_POINT
  100777. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  100778. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  100779. }
  100780. #endif
  100781. }
  100782. }
  100783. /*
  100784. ** Process an UPDATE statement.
  100785. **
  100786. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  100787. ** \_______/ \________/ \______/ \________________/
  100788. * onError pTabList pChanges pWhere
  100789. */
  100790. SQLITE_PRIVATE void sqlite3Update(
  100791. Parse *pParse, /* The parser context */
  100792. SrcList *pTabList, /* The table in which we should change things */
  100793. ExprList *pChanges, /* Things to be changed */
  100794. Expr *pWhere, /* The WHERE clause. May be null */
  100795. int onError /* How to handle constraint errors */
  100796. ){
  100797. int i, j; /* Loop counters */
  100798. Table *pTab; /* The table to be updated */
  100799. int addr = 0; /* VDBE instruction address of the start of the loop */
  100800. WhereInfo *pWInfo; /* Information about the WHERE clause */
  100801. Vdbe *v; /* The virtual database engine */
  100802. Index *pIdx; /* For looping over indices */
  100803. int nIdx; /* Number of indices that need updating */
  100804. int iCur; /* VDBE Cursor number of pTab */
  100805. sqlite3 *db; /* The database structure */
  100806. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  100807. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  100808. ** an expression for the i-th column of the table.
  100809. ** aXRef[i]==-1 if the i-th column is not changed. */
  100810. int chngRowid; /* True if the record number is being changed */
  100811. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  100812. int openAll = 0; /* True if all indices need to be opened */
  100813. AuthContext sContext; /* The authorization context */
  100814. NameContext sNC; /* The name-context to resolve expressions in */
  100815. int iDb; /* Database containing the table being updated */
  100816. int okOnePass; /* True for one-pass algorithm without the FIFO */
  100817. int hasFK; /* True if foreign key processing is required */
  100818. #ifndef SQLITE_OMIT_TRIGGER
  100819. int isView; /* True when updating a view (INSTEAD OF trigger) */
  100820. Trigger *pTrigger; /* List of triggers on pTab, if required */
  100821. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100822. #endif
  100823. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  100824. /* Register Allocations */
  100825. int regRowCount = 0; /* A count of rows changed */
  100826. int regOldRowid; /* The old rowid */
  100827. int regNewRowid; /* The new rowid */
  100828. int regNew; /* Content of the NEW.* table in triggers */
  100829. int regOld = 0; /* Content of OLD.* table in triggers */
  100830. int regRowSet = 0; /* Rowset of rows to be updated */
  100831. memset(&sContext, 0, sizeof(sContext));
  100832. db = pParse->db;
  100833. if( pParse->nErr || db->mallocFailed ){
  100834. goto update_cleanup;
  100835. }
  100836. assert( pTabList->nSrc==1 );
  100837. /* Locate the table which we want to update.
  100838. */
  100839. pTab = sqlite3SrcListLookup(pParse, pTabList);
  100840. if( pTab==0 ) goto update_cleanup;
  100841. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  100842. /* Figure out if we have any triggers and if the table being
  100843. ** updated is a view.
  100844. */
  100845. #ifndef SQLITE_OMIT_TRIGGER
  100846. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  100847. isView = pTab->pSelect!=0;
  100848. assert( pTrigger || tmask==0 );
  100849. #else
  100850. # define pTrigger 0
  100851. # define isView 0
  100852. # define tmask 0
  100853. #endif
  100854. #ifdef SQLITE_OMIT_VIEW
  100855. # undef isView
  100856. # define isView 0
  100857. #endif
  100858. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  100859. goto update_cleanup;
  100860. }
  100861. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  100862. goto update_cleanup;
  100863. }
  100864. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  100865. if( aXRef==0 ) goto update_cleanup;
  100866. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  100867. /* Allocate a cursors for the main database table and for all indices.
  100868. ** The index cursors might not be used, but if they are used they
  100869. ** need to occur right after the database cursor. So go ahead and
  100870. ** allocate enough space, just in case.
  100871. */
  100872. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  100873. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  100874. pParse->nTab++;
  100875. }
  100876. /* Initialize the name-context */
  100877. memset(&sNC, 0, sizeof(sNC));
  100878. sNC.pParse = pParse;
  100879. sNC.pSrcList = pTabList;
  100880. /* Resolve the column names in all the expressions of the
  100881. ** of the UPDATE statement. Also find the column index
  100882. ** for each column to be updated in the pChanges array. For each
  100883. ** column to be updated, make sure we have authorization to change
  100884. ** that column.
  100885. */
  100886. chngRowid = 0;
  100887. for(i=0; i<pChanges->nExpr; i++){
  100888. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  100889. goto update_cleanup;
  100890. }
  100891. for(j=0; j<pTab->nCol; j++){
  100892. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  100893. if( j==pTab->iPKey ){
  100894. chngRowid = 1;
  100895. pRowidExpr = pChanges->a[i].pExpr;
  100896. }
  100897. aXRef[j] = i;
  100898. break;
  100899. }
  100900. }
  100901. if( j>=pTab->nCol ){
  100902. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  100903. j = -1;
  100904. chngRowid = 1;
  100905. pRowidExpr = pChanges->a[i].pExpr;
  100906. }else{
  100907. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  100908. pParse->checkSchema = 1;
  100909. goto update_cleanup;
  100910. }
  100911. }
  100912. #ifndef SQLITE_OMIT_AUTHORIZATION
  100913. {
  100914. int rc;
  100915. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  100916. j<0 ? "ROWID" : pTab->aCol[j].zName,
  100917. db->aDb[iDb].zName);
  100918. if( rc==SQLITE_DENY ){
  100919. goto update_cleanup;
  100920. }else if( rc==SQLITE_IGNORE ){
  100921. aXRef[j] = -1;
  100922. }
  100923. }
  100924. #endif
  100925. }
  100926. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  100927. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  100928. ** array for each index associated with table being updated. Fill in
  100929. ** the value with a register number for indices that are to be used
  100930. ** and with zero for unused indices.
  100931. */
  100932. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  100933. if( nIdx>0 ){
  100934. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  100935. if( aRegIdx==0 ) goto update_cleanup;
  100936. }
  100937. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  100938. int reg;
  100939. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  100940. reg = ++pParse->nMem;
  100941. }else{
  100942. reg = 0;
  100943. for(i=0; i<pIdx->nColumn; i++){
  100944. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  100945. reg = ++pParse->nMem;
  100946. break;
  100947. }
  100948. }
  100949. }
  100950. aRegIdx[j] = reg;
  100951. }
  100952. /* Begin generating code. */
  100953. v = sqlite3GetVdbe(pParse);
  100954. if( v==0 ) goto update_cleanup;
  100955. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  100956. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100957. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100958. /* Virtual tables must be handled separately */
  100959. if( IsVirtual(pTab) ){
  100960. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  100961. pWhere, onError);
  100962. pWhere = 0;
  100963. pTabList = 0;
  100964. goto update_cleanup;
  100965. }
  100966. #endif
  100967. /* Allocate required registers. */
  100968. regRowSet = ++pParse->nMem;
  100969. regOldRowid = regNewRowid = ++pParse->nMem;
  100970. if( pTrigger || hasFK ){
  100971. regOld = pParse->nMem + 1;
  100972. pParse->nMem += pTab->nCol;
  100973. }
  100974. if( chngRowid || pTrigger || hasFK ){
  100975. regNewRowid = ++pParse->nMem;
  100976. }
  100977. regNew = pParse->nMem + 1;
  100978. pParse->nMem += pTab->nCol;
  100979. /* Start the view context. */
  100980. if( isView ){
  100981. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  100982. }
  100983. /* If we are trying to update a view, realize that view into
  100984. ** a ephemeral table.
  100985. */
  100986. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  100987. if( isView ){
  100988. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  100989. }
  100990. #endif
  100991. /* Resolve the column names in all the expressions in the
  100992. ** WHERE clause.
  100993. */
  100994. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  100995. goto update_cleanup;
  100996. }
  100997. /* Begin the database scan
  100998. */
  100999. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  101000. pWInfo = sqlite3WhereBegin(
  101001. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  101002. );
  101003. if( pWInfo==0 ) goto update_cleanup;
  101004. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  101005. /* Remember the rowid of every item to be updated.
  101006. */
  101007. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  101008. if( !okOnePass ){
  101009. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  101010. }
  101011. /* End the database scan loop.
  101012. */
  101013. sqlite3WhereEnd(pWInfo);
  101014. /* Initialize the count of updated rows
  101015. */
  101016. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  101017. regRowCount = ++pParse->nMem;
  101018. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  101019. }
  101020. if( !isView ){
  101021. /*
  101022. ** Open every index that needs updating. Note that if any
  101023. ** index could potentially invoke a REPLACE conflict resolution
  101024. ** action, then we need to open all indices because we might need
  101025. ** to be deleting some records.
  101026. */
  101027. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  101028. if( onError==OE_Replace ){
  101029. openAll = 1;
  101030. }else{
  101031. openAll = 0;
  101032. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101033. if( pIdx->onError==OE_Replace ){
  101034. openAll = 1;
  101035. break;
  101036. }
  101037. }
  101038. }
  101039. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  101040. assert( aRegIdx );
  101041. if( openAll || aRegIdx[i]>0 ){
  101042. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  101043. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  101044. (char*)pKey, P4_KEYINFO_HANDOFF);
  101045. assert( pParse->nTab>iCur+i+1 );
  101046. }
  101047. }
  101048. }
  101049. /* Top of the update loop */
  101050. if( okOnePass ){
  101051. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  101052. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  101053. sqlite3VdbeJumpHere(v, a1);
  101054. }else{
  101055. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  101056. }
  101057. /* Make cursor iCur point to the record that is being updated. If
  101058. ** this record does not exist for some reason (deleted by a trigger,
  101059. ** for example, then jump to the next iteration of the RowSet loop. */
  101060. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  101061. /* If the record number will change, set register regNewRowid to
  101062. ** contain the new value. If the record number is not being modified,
  101063. ** then regNewRowid is the same register as regOldRowid, which is
  101064. ** already populated. */
  101065. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  101066. if( chngRowid ){
  101067. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  101068. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  101069. }
  101070. /* If there are triggers on this table, populate an array of registers
  101071. ** with the required old.* column data. */
  101072. if( hasFK || pTrigger ){
  101073. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  101074. oldmask |= sqlite3TriggerColmask(pParse,
  101075. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  101076. );
  101077. for(i=0; i<pTab->nCol; i++){
  101078. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  101079. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  101080. }else{
  101081. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  101082. }
  101083. }
  101084. if( chngRowid==0 ){
  101085. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  101086. }
  101087. }
  101088. /* Populate the array of registers beginning at regNew with the new
  101089. ** row data. This array is used to check constaints, create the new
  101090. ** table and index records, and as the values for any new.* references
  101091. ** made by triggers.
  101092. **
  101093. ** If there are one or more BEFORE triggers, then do not populate the
  101094. ** registers associated with columns that are (a) not modified by
  101095. ** this UPDATE statement and (b) not accessed by new.* references. The
  101096. ** values for registers not modified by the UPDATE must be reloaded from
  101097. ** the database after the BEFORE triggers are fired anyway (as the trigger
  101098. ** may have modified them). So not loading those that are not going to
  101099. ** be used eliminates some redundant opcodes.
  101100. */
  101101. newmask = sqlite3TriggerColmask(
  101102. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  101103. );
  101104. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  101105. for(i=0; i<pTab->nCol; i++){
  101106. if( i==pTab->iPKey ){
  101107. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  101108. }else{
  101109. j = aXRef[i];
  101110. if( j>=0 ){
  101111. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  101112. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  101113. /* This branch loads the value of a column that will not be changed
  101114. ** into a register. This is done if there are no BEFORE triggers, or
  101115. ** if there are one or more BEFORE triggers that use this value via
  101116. ** a new.* reference in a trigger program.
  101117. */
  101118. testcase( i==31 );
  101119. testcase( i==32 );
  101120. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  101121. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  101122. }
  101123. }
  101124. }
  101125. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  101126. ** verified. One could argue that this is wrong.
  101127. */
  101128. if( tmask&TRIGGER_BEFORE ){
  101129. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  101130. sqlite3TableAffinityStr(v, pTab);
  101131. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  101132. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  101133. /* The row-trigger may have deleted the row being updated. In this
  101134. ** case, jump to the next row. No updates or AFTER triggers are
  101135. ** required. This behavior - what happens when the row being updated
  101136. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  101137. ** documentation.
  101138. */
  101139. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  101140. /* If it did not delete it, the row-trigger may still have modified
  101141. ** some of the columns of the row being updated. Load the values for
  101142. ** all columns not modified by the update statement into their
  101143. ** registers in case this has happened.
  101144. */
  101145. for(i=0; i<pTab->nCol; i++){
  101146. if( aXRef[i]<0 && i!=pTab->iPKey ){
  101147. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  101148. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  101149. }
  101150. }
  101151. }
  101152. if( !isView ){
  101153. int j1; /* Address of jump instruction */
  101154. /* Do constraint checks. */
  101155. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  101156. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  101157. /* Do FK constraint checks. */
  101158. if( hasFK ){
  101159. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  101160. }
  101161. /* Delete the index entries associated with the current record. */
  101162. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  101163. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  101164. /* If changing the record number, delete the old record. */
  101165. if( hasFK || chngRowid ){
  101166. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  101167. }
  101168. sqlite3VdbeJumpHere(v, j1);
  101169. if( hasFK ){
  101170. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  101171. }
  101172. /* Insert the new index entries and the new record. */
  101173. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  101174. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  101175. ** handle rows (possibly in other tables) that refer via a foreign key
  101176. ** to the row just updated. */
  101177. if( hasFK ){
  101178. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  101179. }
  101180. }
  101181. /* Increment the row counter
  101182. */
  101183. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  101184. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  101185. }
  101186. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  101187. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  101188. /* Repeat the above with the next record to be updated, until
  101189. ** all record selected by the WHERE clause have been updated.
  101190. */
  101191. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  101192. sqlite3VdbeJumpHere(v, addr);
  101193. /* Close all tables */
  101194. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  101195. assert( aRegIdx );
  101196. if( openAll || aRegIdx[i]>0 ){
  101197. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  101198. }
  101199. }
  101200. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  101201. /* Update the sqlite_sequence table by storing the content of the
  101202. ** maximum rowid counter values recorded while inserting into
  101203. ** autoincrement tables.
  101204. */
  101205. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  101206. sqlite3AutoincrementEnd(pParse);
  101207. }
  101208. /*
  101209. ** Return the number of rows that were changed. If this routine is
  101210. ** generating code because of a call to sqlite3NestedParse(), do not
  101211. ** invoke the callback function.
  101212. */
  101213. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  101214. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  101215. sqlite3VdbeSetNumCols(v, 1);
  101216. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  101217. }
  101218. update_cleanup:
  101219. sqlite3AuthContextPop(&sContext);
  101220. sqlite3DbFree(db, aRegIdx);
  101221. sqlite3DbFree(db, aXRef);
  101222. sqlite3SrcListDelete(db, pTabList);
  101223. sqlite3ExprListDelete(db, pChanges);
  101224. sqlite3ExprDelete(db, pWhere);
  101225. return;
  101226. }
  101227. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  101228. ** thely may interfere with compilation of other functions in this file
  101229. ** (or in another file, if this file becomes part of the amalgamation). */
  101230. #ifdef isView
  101231. #undef isView
  101232. #endif
  101233. #ifdef pTrigger
  101234. #undef pTrigger
  101235. #endif
  101236. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101237. /*
  101238. ** Generate code for an UPDATE of a virtual table.
  101239. **
  101240. ** The strategy is that we create an ephemerial table that contains
  101241. ** for each row to be changed:
  101242. **
  101243. ** (A) The original rowid of that row.
  101244. ** (B) The revised rowid for the row. (note1)
  101245. ** (C) The content of every column in the row.
  101246. **
  101247. ** Then we loop over this ephemeral table and for each row in
  101248. ** the ephermeral table call VUpdate.
  101249. **
  101250. ** When finished, drop the ephemeral table.
  101251. **
  101252. ** (note1) Actually, if we know in advance that (A) is always the same
  101253. ** as (B) we only store (A), then duplicate (A) when pulling
  101254. ** it out of the ephemeral table before calling VUpdate.
  101255. */
  101256. static void updateVirtualTable(
  101257. Parse *pParse, /* The parsing context */
  101258. SrcList *pSrc, /* The virtual table to be modified */
  101259. Table *pTab, /* The virtual table */
  101260. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  101261. Expr *pRowid, /* Expression used to recompute the rowid */
  101262. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  101263. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  101264. int onError /* ON CONFLICT strategy */
  101265. ){
  101266. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  101267. ExprList *pEList = 0; /* The result set of the SELECT statement */
  101268. Select *pSelect = 0; /* The SELECT statement */
  101269. Expr *pExpr; /* Temporary expression */
  101270. int ephemTab; /* Table holding the result of the SELECT */
  101271. int i; /* Loop counter */
  101272. int addr; /* Address of top of loop */
  101273. int iReg; /* First register in set passed to OP_VUpdate */
  101274. sqlite3 *db = pParse->db; /* Database connection */
  101275. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  101276. SelectDest dest;
  101277. /* Construct the SELECT statement that will find the new values for
  101278. ** all updated rows.
  101279. */
  101280. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  101281. if( pRowid ){
  101282. pEList = sqlite3ExprListAppend(pParse, pEList,
  101283. sqlite3ExprDup(db, pRowid, 0));
  101284. }
  101285. assert( pTab->iPKey<0 );
  101286. for(i=0; i<pTab->nCol; i++){
  101287. if( aXRef[i]>=0 ){
  101288. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  101289. }else{
  101290. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  101291. }
  101292. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  101293. }
  101294. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  101295. /* Create the ephemeral table into which the update results will
  101296. ** be stored.
  101297. */
  101298. assert( v );
  101299. ephemTab = pParse->nTab++;
  101300. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  101301. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  101302. /* fill the ephemeral table
  101303. */
  101304. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  101305. sqlite3Select(pParse, pSelect, &dest);
  101306. /* Generate code to scan the ephemeral table and call VUpdate. */
  101307. iReg = ++pParse->nMem;
  101308. pParse->nMem += pTab->nCol+1;
  101309. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  101310. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  101311. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  101312. for(i=0; i<pTab->nCol; i++){
  101313. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  101314. }
  101315. sqlite3VtabMakeWritable(pParse, pTab);
  101316. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  101317. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  101318. sqlite3MayAbort(pParse);
  101319. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  101320. sqlite3VdbeJumpHere(v, addr);
  101321. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  101322. /* Cleanup */
  101323. sqlite3SelectDelete(db, pSelect);
  101324. }
  101325. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  101326. /************** End of update.c **********************************************/
  101327. /************** Begin file vacuum.c ******************************************/
  101328. /*
  101329. ** 2003 April 6
  101330. **
  101331. ** The author disclaims copyright to this source code. In place of
  101332. ** a legal notice, here is a blessing:
  101333. **
  101334. ** May you do good and not evil.
  101335. ** May you find forgiveness for yourself and forgive others.
  101336. ** May you share freely, never taking more than you give.
  101337. **
  101338. *************************************************************************
  101339. ** This file contains code used to implement the VACUUM command.
  101340. **
  101341. ** Most of the code in this file may be omitted by defining the
  101342. ** SQLITE_OMIT_VACUUM macro.
  101343. */
  101344. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  101345. /*
  101346. ** Finalize a prepared statement. If there was an error, store the
  101347. ** text of the error message in *pzErrMsg. Return the result code.
  101348. */
  101349. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  101350. int rc;
  101351. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  101352. if( rc ){
  101353. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  101354. }
  101355. return rc;
  101356. }
  101357. /*
  101358. ** Execute zSql on database db. Return an error code.
  101359. */
  101360. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  101361. sqlite3_stmt *pStmt;
  101362. VVA_ONLY( int rc; )
  101363. if( !zSql ){
  101364. return SQLITE_NOMEM;
  101365. }
  101366. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  101367. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  101368. return sqlite3_errcode(db);
  101369. }
  101370. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  101371. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  101372. return vacuumFinalize(db, pStmt, pzErrMsg);
  101373. }
  101374. /*
  101375. ** Execute zSql on database db. The statement returns exactly
  101376. ** one column. Execute this as SQL on the same database.
  101377. */
  101378. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  101379. sqlite3_stmt *pStmt;
  101380. int rc;
  101381. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  101382. if( rc!=SQLITE_OK ) return rc;
  101383. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  101384. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  101385. if( rc!=SQLITE_OK ){
  101386. vacuumFinalize(db, pStmt, pzErrMsg);
  101387. return rc;
  101388. }
  101389. }
  101390. return vacuumFinalize(db, pStmt, pzErrMsg);
  101391. }
  101392. /*
  101393. ** The VACUUM command is used to clean up the database,
  101394. ** collapse free space, etc. It is modelled after the VACUUM command
  101395. ** in PostgreSQL. The VACUUM command works as follows:
  101396. **
  101397. ** (1) Create a new transient database file
  101398. ** (2) Copy all content from the database being vacuumed into
  101399. ** the new transient database file
  101400. ** (3) Copy content from the transient database back into the
  101401. ** original database.
  101402. **
  101403. ** The transient database requires temporary disk space approximately
  101404. ** equal to the size of the original database. The copy operation of
  101405. ** step (3) requires additional temporary disk space approximately equal
  101406. ** to the size of the original database for the rollback journal.
  101407. ** Hence, temporary disk space that is approximately 2x the size of the
  101408. ** orginal database is required. Every page of the database is written
  101409. ** approximately 3 times: Once for step (2) and twice for step (3).
  101410. ** Two writes per page are required in step (3) because the original
  101411. ** database content must be written into the rollback journal prior to
  101412. ** overwriting the database with the vacuumed content.
  101413. **
  101414. ** Only 1x temporary space and only 1x writes would be required if
  101415. ** the copy of step (3) were replace by deleting the original database
  101416. ** and renaming the transient database as the original. But that will
  101417. ** not work if other processes are attached to the original database.
  101418. ** And a power loss in between deleting the original and renaming the
  101419. ** transient would cause the database file to appear to be deleted
  101420. ** following reboot.
  101421. */
  101422. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  101423. Vdbe *v = sqlite3GetVdbe(pParse);
  101424. if( v ){
  101425. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  101426. sqlite3VdbeUsesBtree(v, 0);
  101427. }
  101428. return;
  101429. }
  101430. /*
  101431. ** This routine implements the OP_Vacuum opcode of the VDBE.
  101432. */
  101433. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  101434. int rc = SQLITE_OK; /* Return code from service routines */
  101435. Btree *pMain; /* The database being vacuumed */
  101436. Btree *pTemp; /* The temporary database we vacuum into */
  101437. char *zSql = 0; /* SQL statements */
  101438. int saved_flags; /* Saved value of the db->flags */
  101439. int saved_nChange; /* Saved value of db->nChange */
  101440. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  101441. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  101442. Db *pDb = 0; /* Database to detach at end of vacuum */
  101443. int isMemDb; /* True if vacuuming a :memory: database */
  101444. int nRes; /* Bytes of reserved space at the end of each page */
  101445. int nDb; /* Number of attached databases */
  101446. if( !db->autoCommit ){
  101447. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  101448. return SQLITE_ERROR;
  101449. }
  101450. if( db->nVdbeActive>1 ){
  101451. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  101452. return SQLITE_ERROR;
  101453. }
  101454. /* Save the current value of the database flags so that it can be
  101455. ** restored before returning. Then set the writable-schema flag, and
  101456. ** disable CHECK and foreign key constraints. */
  101457. saved_flags = db->flags;
  101458. saved_nChange = db->nChange;
  101459. saved_nTotalChange = db->nTotalChange;
  101460. saved_xTrace = db->xTrace;
  101461. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  101462. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  101463. db->xTrace = 0;
  101464. pMain = db->aDb[0].pBt;
  101465. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  101466. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  101467. ** can be set to 'off' for this file, as it is not recovered if a crash
  101468. ** occurs anyway. The integrity of the database is maintained by a
  101469. ** (possibly synchronous) transaction opened on the main database before
  101470. ** sqlite3BtreeCopyFile() is called.
  101471. **
  101472. ** An optimisation would be to use a non-journaled pager.
  101473. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  101474. ** that actually made the VACUUM run slower. Very little journalling
  101475. ** actually occurs when doing a vacuum since the vacuum_db is initially
  101476. ** empty. Only the journal header is written. Apparently it takes more
  101477. ** time to parse and run the PRAGMA to turn journalling off than it does
  101478. ** to write the journal header file.
  101479. */
  101480. nDb = db->nDb;
  101481. if( sqlite3TempInMemory(db) ){
  101482. zSql = "ATTACH ':memory:' AS vacuum_db;";
  101483. }else{
  101484. zSql = "ATTACH '' AS vacuum_db;";
  101485. }
  101486. rc = execSql(db, pzErrMsg, zSql);
  101487. if( db->nDb>nDb ){
  101488. pDb = &db->aDb[db->nDb-1];
  101489. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  101490. }
  101491. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101492. pTemp = db->aDb[db->nDb-1].pBt;
  101493. /* The call to execSql() to attach the temp database has left the file
  101494. ** locked (as there was more than one active statement when the transaction
  101495. ** to read the schema was concluded. Unlock it here so that this doesn't
  101496. ** cause problems for the call to BtreeSetPageSize() below. */
  101497. sqlite3BtreeCommit(pTemp);
  101498. nRes = sqlite3BtreeGetReserve(pMain);
  101499. /* A VACUUM cannot change the pagesize of an encrypted database. */
  101500. #ifdef SQLITE_HAS_CODEC
  101501. if( db->nextPagesize ){
  101502. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  101503. int nKey;
  101504. char *zKey;
  101505. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  101506. if( nKey ) db->nextPagesize = 0;
  101507. }
  101508. #endif
  101509. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  101510. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101511. /* Begin a transaction and take an exclusive lock on the main database
  101512. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  101513. ** to ensure that we do not try to change the page-size on a WAL database.
  101514. */
  101515. rc = execSql(db, pzErrMsg, "BEGIN;");
  101516. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101517. rc = sqlite3BtreeBeginTrans(pMain, 2);
  101518. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101519. /* Do not attempt to change the page size for a WAL database */
  101520. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  101521. ==PAGER_JOURNALMODE_WAL ){
  101522. db->nextPagesize = 0;
  101523. }
  101524. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  101525. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  101526. || NEVER(db->mallocFailed)
  101527. ){
  101528. rc = SQLITE_NOMEM;
  101529. goto end_of_vacuum;
  101530. }
  101531. #ifndef SQLITE_OMIT_AUTOVACUUM
  101532. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  101533. sqlite3BtreeGetAutoVacuum(pMain));
  101534. #endif
  101535. /* Query the schema of the main database. Create a mirror schema
  101536. ** in the temporary database.
  101537. */
  101538. rc = execExecSql(db, pzErrMsg,
  101539. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  101540. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  101541. " AND rootpage>0"
  101542. );
  101543. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101544. rc = execExecSql(db, pzErrMsg,
  101545. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  101546. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  101547. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101548. rc = execExecSql(db, pzErrMsg,
  101549. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  101550. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  101551. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101552. /* Loop through the tables in the main database. For each, do
  101553. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  101554. ** the contents to the temporary database.
  101555. */
  101556. rc = execExecSql(db, pzErrMsg,
  101557. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  101558. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  101559. "FROM main.sqlite_master "
  101560. "WHERE type = 'table' AND name!='sqlite_sequence' "
  101561. " AND rootpage>0"
  101562. );
  101563. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101564. /* Copy over the sequence table
  101565. */
  101566. rc = execExecSql(db, pzErrMsg,
  101567. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  101568. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  101569. );
  101570. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101571. rc = execExecSql(db, pzErrMsg,
  101572. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  101573. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  101574. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  101575. );
  101576. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101577. /* Copy the triggers, views, and virtual tables from the main database
  101578. ** over to the temporary database. None of these objects has any
  101579. ** associated storage, so all we have to do is copy their entries
  101580. ** from the SQLITE_MASTER table.
  101581. */
  101582. rc = execSql(db, pzErrMsg,
  101583. "INSERT INTO vacuum_db.sqlite_master "
  101584. " SELECT type, name, tbl_name, rootpage, sql"
  101585. " FROM main.sqlite_master"
  101586. " WHERE type='view' OR type='trigger'"
  101587. " OR (type='table' AND rootpage=0)"
  101588. );
  101589. if( rc ) goto end_of_vacuum;
  101590. /* At this point, there is a write transaction open on both the
  101591. ** vacuum database and the main database. Assuming no error occurs,
  101592. ** both transactions are closed by this block - the main database
  101593. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  101594. ** call to sqlite3BtreeCommit().
  101595. */
  101596. {
  101597. u32 meta;
  101598. int i;
  101599. /* This array determines which meta meta values are preserved in the
  101600. ** vacuum. Even entries are the meta value number and odd entries
  101601. ** are an increment to apply to the meta value after the vacuum.
  101602. ** The increment is used to increase the schema cookie so that other
  101603. ** connections to the same database will know to reread the schema.
  101604. */
  101605. static const unsigned char aCopy[] = {
  101606. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  101607. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  101608. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  101609. BTREE_USER_VERSION, 0, /* Preserve the user version */
  101610. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  101611. };
  101612. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  101613. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  101614. /* Copy Btree meta values */
  101615. for(i=0; i<ArraySize(aCopy); i+=2){
  101616. /* GetMeta() and UpdateMeta() cannot fail in this context because
  101617. ** we already have page 1 loaded into cache and marked dirty. */
  101618. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  101619. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  101620. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  101621. }
  101622. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  101623. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101624. rc = sqlite3BtreeCommit(pTemp);
  101625. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101626. #ifndef SQLITE_OMIT_AUTOVACUUM
  101627. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  101628. #endif
  101629. }
  101630. assert( rc==SQLITE_OK );
  101631. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  101632. end_of_vacuum:
  101633. /* Restore the original value of db->flags */
  101634. db->flags = saved_flags;
  101635. db->nChange = saved_nChange;
  101636. db->nTotalChange = saved_nTotalChange;
  101637. db->xTrace = saved_xTrace;
  101638. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  101639. /* Currently there is an SQL level transaction open on the vacuum
  101640. ** database. No locks are held on any other files (since the main file
  101641. ** was committed at the btree level). So it safe to end the transaction
  101642. ** by manually setting the autoCommit flag to true and detaching the
  101643. ** vacuum database. The vacuum_db journal file is deleted when the pager
  101644. ** is closed by the DETACH.
  101645. */
  101646. db->autoCommit = 1;
  101647. if( pDb ){
  101648. sqlite3BtreeClose(pDb->pBt);
  101649. pDb->pBt = 0;
  101650. pDb->pSchema = 0;
  101651. }
  101652. /* This both clears the schemas and reduces the size of the db->aDb[]
  101653. ** array. */
  101654. sqlite3ResetAllSchemasOfConnection(db);
  101655. return rc;
  101656. }
  101657. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  101658. /************** End of vacuum.c **********************************************/
  101659. /************** Begin file vtab.c ********************************************/
  101660. /*
  101661. ** 2006 June 10
  101662. **
  101663. ** The author disclaims copyright to this source code. In place of
  101664. ** a legal notice, here is a blessing:
  101665. **
  101666. ** May you do good and not evil.
  101667. ** May you find forgiveness for yourself and forgive others.
  101668. ** May you share freely, never taking more than you give.
  101669. **
  101670. *************************************************************************
  101671. ** This file contains code used to help implement virtual tables.
  101672. */
  101673. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101674. /*
  101675. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  101676. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  101677. ** this struct allocated on the stack. It is used by the implementation of
  101678. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  101679. ** are invoked only from within xCreate and xConnect methods.
  101680. */
  101681. struct VtabCtx {
  101682. VTable *pVTable; /* The virtual table being constructed */
  101683. Table *pTab; /* The Table object to which the virtual table belongs */
  101684. };
  101685. /*
  101686. ** The actual function that does the work of creating a new module.
  101687. ** This function implements the sqlite3_create_module() and
  101688. ** sqlite3_create_module_v2() interfaces.
  101689. */
  101690. static int createModule(
  101691. sqlite3 *db, /* Database in which module is registered */
  101692. const char *zName, /* Name assigned to this module */
  101693. const sqlite3_module *pModule, /* The definition of the module */
  101694. void *pAux, /* Context pointer for xCreate/xConnect */
  101695. void (*xDestroy)(void *) /* Module destructor function */
  101696. ){
  101697. int rc = SQLITE_OK;
  101698. int nName;
  101699. sqlite3_mutex_enter(db->mutex);
  101700. nName = sqlite3Strlen30(zName);
  101701. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  101702. rc = SQLITE_MISUSE_BKPT;
  101703. }else{
  101704. Module *pMod;
  101705. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  101706. if( pMod ){
  101707. Module *pDel;
  101708. char *zCopy = (char *)(&pMod[1]);
  101709. memcpy(zCopy, zName, nName+1);
  101710. pMod->zName = zCopy;
  101711. pMod->pModule = pModule;
  101712. pMod->pAux = pAux;
  101713. pMod->xDestroy = xDestroy;
  101714. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  101715. assert( pDel==0 || pDel==pMod );
  101716. if( pDel ){
  101717. db->mallocFailed = 1;
  101718. sqlite3DbFree(db, pDel);
  101719. }
  101720. }
  101721. }
  101722. rc = sqlite3ApiExit(db, rc);
  101723. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  101724. sqlite3_mutex_leave(db->mutex);
  101725. return rc;
  101726. }
  101727. /*
  101728. ** External API function used to create a new virtual-table module.
  101729. */
  101730. SQLITE_API int sqlite3_create_module(
  101731. sqlite3 *db, /* Database in which module is registered */
  101732. const char *zName, /* Name assigned to this module */
  101733. const sqlite3_module *pModule, /* The definition of the module */
  101734. void *pAux /* Context pointer for xCreate/xConnect */
  101735. ){
  101736. return createModule(db, zName, pModule, pAux, 0);
  101737. }
  101738. /*
  101739. ** External API function used to create a new virtual-table module.
  101740. */
  101741. SQLITE_API int sqlite3_create_module_v2(
  101742. sqlite3 *db, /* Database in which module is registered */
  101743. const char *zName, /* Name assigned to this module */
  101744. const sqlite3_module *pModule, /* The definition of the module */
  101745. void *pAux, /* Context pointer for xCreate/xConnect */
  101746. void (*xDestroy)(void *) /* Module destructor function */
  101747. ){
  101748. return createModule(db, zName, pModule, pAux, xDestroy);
  101749. }
  101750. /*
  101751. ** Lock the virtual table so that it cannot be disconnected.
  101752. ** Locks nest. Every lock should have a corresponding unlock.
  101753. ** If an unlock is omitted, resources leaks will occur.
  101754. **
  101755. ** If a disconnect is attempted while a virtual table is locked,
  101756. ** the disconnect is deferred until all locks have been removed.
  101757. */
  101758. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  101759. pVTab->nRef++;
  101760. }
  101761. /*
  101762. ** pTab is a pointer to a Table structure representing a virtual-table.
  101763. ** Return a pointer to the VTable object used by connection db to access
  101764. ** this virtual-table, if one has been created, or NULL otherwise.
  101765. */
  101766. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  101767. VTable *pVtab;
  101768. assert( IsVirtual(pTab) );
  101769. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  101770. return pVtab;
  101771. }
  101772. /*
  101773. ** Decrement the ref-count on a virtual table object. When the ref-count
  101774. ** reaches zero, call the xDisconnect() method to delete the object.
  101775. */
  101776. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  101777. sqlite3 *db = pVTab->db;
  101778. assert( db );
  101779. assert( pVTab->nRef>0 );
  101780. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  101781. pVTab->nRef--;
  101782. if( pVTab->nRef==0 ){
  101783. sqlite3_vtab *p = pVTab->pVtab;
  101784. if( p ){
  101785. p->pModule->xDisconnect(p);
  101786. }
  101787. sqlite3DbFree(db, pVTab);
  101788. }
  101789. }
  101790. /*
  101791. ** Table p is a virtual table. This function moves all elements in the
  101792. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  101793. ** database connections to be disconnected at the next opportunity.
  101794. ** Except, if argument db is not NULL, then the entry associated with
  101795. ** connection db is left in the p->pVTable list.
  101796. */
  101797. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  101798. VTable *pRet = 0;
  101799. VTable *pVTable = p->pVTable;
  101800. p->pVTable = 0;
  101801. /* Assert that the mutex (if any) associated with the BtShared database
  101802. ** that contains table p is held by the caller. See header comments
  101803. ** above function sqlite3VtabUnlockList() for an explanation of why
  101804. ** this makes it safe to access the sqlite3.pDisconnect list of any
  101805. ** database connection that may have an entry in the p->pVTable list.
  101806. */
  101807. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  101808. while( pVTable ){
  101809. sqlite3 *db2 = pVTable->db;
  101810. VTable *pNext = pVTable->pNext;
  101811. assert( db2 );
  101812. if( db2==db ){
  101813. pRet = pVTable;
  101814. p->pVTable = pRet;
  101815. pRet->pNext = 0;
  101816. }else{
  101817. pVTable->pNext = db2->pDisconnect;
  101818. db2->pDisconnect = pVTable;
  101819. }
  101820. pVTable = pNext;
  101821. }
  101822. assert( !db || pRet );
  101823. return pRet;
  101824. }
  101825. /*
  101826. ** Table *p is a virtual table. This function removes the VTable object
  101827. ** for table *p associated with database connection db from the linked
  101828. ** list in p->pVTab. It also decrements the VTable ref count. This is
  101829. ** used when closing database connection db to free all of its VTable
  101830. ** objects without disturbing the rest of the Schema object (which may
  101831. ** be being used by other shared-cache connections).
  101832. */
  101833. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  101834. VTable **ppVTab;
  101835. assert( IsVirtual(p) );
  101836. assert( sqlite3BtreeHoldsAllMutexes(db) );
  101837. assert( sqlite3_mutex_held(db->mutex) );
  101838. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  101839. if( (*ppVTab)->db==db ){
  101840. VTable *pVTab = *ppVTab;
  101841. *ppVTab = pVTab->pNext;
  101842. sqlite3VtabUnlock(pVTab);
  101843. break;
  101844. }
  101845. }
  101846. }
  101847. /*
  101848. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  101849. **
  101850. ** This function may only be called when the mutexes associated with all
  101851. ** shared b-tree databases opened using connection db are held by the
  101852. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  101853. ** sqlite3.pDisconnect list is accessed only as follows:
  101854. **
  101855. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  101856. ** associated with the database handle itself must be held.
  101857. **
  101858. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  101859. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  101860. ** associated with the database the virtual table is stored in is held
  101861. ** or, if the virtual table is stored in a non-sharable database, then
  101862. ** the database handle mutex is held.
  101863. **
  101864. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  101865. ** by multiple threads. It is thread-safe.
  101866. */
  101867. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  101868. VTable *p = db->pDisconnect;
  101869. db->pDisconnect = 0;
  101870. assert( sqlite3BtreeHoldsAllMutexes(db) );
  101871. assert( sqlite3_mutex_held(db->mutex) );
  101872. if( p ){
  101873. sqlite3ExpirePreparedStatements(db);
  101874. do {
  101875. VTable *pNext = p->pNext;
  101876. sqlite3VtabUnlock(p);
  101877. p = pNext;
  101878. }while( p );
  101879. }
  101880. }
  101881. /*
  101882. ** Clear any and all virtual-table information from the Table record.
  101883. ** This routine is called, for example, just before deleting the Table
  101884. ** record.
  101885. **
  101886. ** Since it is a virtual-table, the Table structure contains a pointer
  101887. ** to the head of a linked list of VTable structures. Each VTable
  101888. ** structure is associated with a single sqlite3* user of the schema.
  101889. ** The reference count of the VTable structure associated with database
  101890. ** connection db is decremented immediately (which may lead to the
  101891. ** structure being xDisconnected and free). Any other VTable structures
  101892. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  101893. ** database connection.
  101894. */
  101895. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  101896. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  101897. if( p->azModuleArg ){
  101898. int i;
  101899. for(i=0; i<p->nModuleArg; i++){
  101900. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  101901. }
  101902. sqlite3DbFree(db, p->azModuleArg);
  101903. }
  101904. }
  101905. /*
  101906. ** Add a new module argument to pTable->azModuleArg[].
  101907. ** The string is not copied - the pointer is stored. The
  101908. ** string will be freed automatically when the table is
  101909. ** deleted.
  101910. */
  101911. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  101912. int i = pTable->nModuleArg++;
  101913. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  101914. char **azModuleArg;
  101915. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  101916. if( azModuleArg==0 ){
  101917. int j;
  101918. for(j=0; j<i; j++){
  101919. sqlite3DbFree(db, pTable->azModuleArg[j]);
  101920. }
  101921. sqlite3DbFree(db, zArg);
  101922. sqlite3DbFree(db, pTable->azModuleArg);
  101923. pTable->nModuleArg = 0;
  101924. }else{
  101925. azModuleArg[i] = zArg;
  101926. azModuleArg[i+1] = 0;
  101927. }
  101928. pTable->azModuleArg = azModuleArg;
  101929. }
  101930. /*
  101931. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  101932. ** statement. The module name has been parsed, but the optional list
  101933. ** of parameters that follow the module name are still pending.
  101934. */
  101935. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  101936. Parse *pParse, /* Parsing context */
  101937. Token *pName1, /* Name of new table, or database name */
  101938. Token *pName2, /* Name of new table or NULL */
  101939. Token *pModuleName, /* Name of the module for the virtual table */
  101940. int ifNotExists /* No error if the table already exists */
  101941. ){
  101942. int iDb; /* The database the table is being created in */
  101943. Table *pTable; /* The new virtual table */
  101944. sqlite3 *db; /* Database connection */
  101945. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  101946. pTable = pParse->pNewTable;
  101947. if( pTable==0 ) return;
  101948. assert( 0==pTable->pIndex );
  101949. db = pParse->db;
  101950. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  101951. assert( iDb>=0 );
  101952. pTable->tabFlags |= TF_Virtual;
  101953. pTable->nModuleArg = 0;
  101954. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  101955. addModuleArgument(db, pTable, 0);
  101956. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  101957. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  101958. #ifndef SQLITE_OMIT_AUTHORIZATION
  101959. /* Creating a virtual table invokes the authorization callback twice.
  101960. ** The first invocation, to obtain permission to INSERT a row into the
  101961. ** sqlite_master table, has already been made by sqlite3StartTable().
  101962. ** The second call, to obtain permission to create the table, is made now.
  101963. */
  101964. if( pTable->azModuleArg ){
  101965. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  101966. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  101967. }
  101968. #endif
  101969. }
  101970. /*
  101971. ** This routine takes the module argument that has been accumulating
  101972. ** in pParse->zArg[] and appends it to the list of arguments on the
  101973. ** virtual table currently under construction in pParse->pTable.
  101974. */
  101975. static void addArgumentToVtab(Parse *pParse){
  101976. if( pParse->sArg.z && pParse->pNewTable ){
  101977. const char *z = (const char*)pParse->sArg.z;
  101978. int n = pParse->sArg.n;
  101979. sqlite3 *db = pParse->db;
  101980. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  101981. }
  101982. }
  101983. /*
  101984. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  101985. ** has been completely parsed.
  101986. */
  101987. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  101988. Table *pTab = pParse->pNewTable; /* The table being constructed */
  101989. sqlite3 *db = pParse->db; /* The database connection */
  101990. if( pTab==0 ) return;
  101991. addArgumentToVtab(pParse);
  101992. pParse->sArg.z = 0;
  101993. if( pTab->nModuleArg<1 ) return;
  101994. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  101995. ** first time (in other words if the virtual table is actually being
  101996. ** created now instead of just being read out of sqlite_master) then
  101997. ** do additional initialization work and store the statement text
  101998. ** in the sqlite_master table.
  101999. */
  102000. if( !db->init.busy ){
  102001. char *zStmt;
  102002. char *zWhere;
  102003. int iDb;
  102004. Vdbe *v;
  102005. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  102006. if( pEnd ){
  102007. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  102008. }
  102009. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  102010. /* A slot for the record has already been allocated in the
  102011. ** SQLITE_MASTER table. We just need to update that slot with all
  102012. ** the information we've collected.
  102013. **
  102014. ** The VM register number pParse->regRowid holds the rowid of an
  102015. ** entry in the sqlite_master table tht was created for this vtab
  102016. ** by sqlite3StartTable().
  102017. */
  102018. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102019. sqlite3NestedParse(pParse,
  102020. "UPDATE %Q.%s "
  102021. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  102022. "WHERE rowid=#%d",
  102023. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  102024. pTab->zName,
  102025. pTab->zName,
  102026. zStmt,
  102027. pParse->regRowid
  102028. );
  102029. sqlite3DbFree(db, zStmt);
  102030. v = sqlite3GetVdbe(pParse);
  102031. sqlite3ChangeCookie(pParse, iDb);
  102032. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  102033. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  102034. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  102035. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  102036. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  102037. }
  102038. /* If we are rereading the sqlite_master table create the in-memory
  102039. ** record of the table. The xConnect() method is not called until
  102040. ** the first time the virtual table is used in an SQL statement. This
  102041. ** allows a schema that contains virtual tables to be loaded before
  102042. ** the required virtual table implementations are registered. */
  102043. else {
  102044. Table *pOld;
  102045. Schema *pSchema = pTab->pSchema;
  102046. const char *zName = pTab->zName;
  102047. int nName = sqlite3Strlen30(zName);
  102048. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  102049. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  102050. if( pOld ){
  102051. db->mallocFailed = 1;
  102052. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  102053. return;
  102054. }
  102055. pParse->pNewTable = 0;
  102056. }
  102057. }
  102058. /*
  102059. ** The parser calls this routine when it sees the first token
  102060. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  102061. */
  102062. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  102063. addArgumentToVtab(pParse);
  102064. pParse->sArg.z = 0;
  102065. pParse->sArg.n = 0;
  102066. }
  102067. /*
  102068. ** The parser calls this routine for each token after the first token
  102069. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  102070. */
  102071. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  102072. Token *pArg = &pParse->sArg;
  102073. if( pArg->z==0 ){
  102074. pArg->z = p->z;
  102075. pArg->n = p->n;
  102076. }else{
  102077. assert(pArg->z < p->z);
  102078. pArg->n = (int)(&p->z[p->n] - pArg->z);
  102079. }
  102080. }
  102081. /*
  102082. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  102083. ** pointer to the function to invoke is passed as the fourth parameter
  102084. ** to this procedure.
  102085. */
  102086. static int vtabCallConstructor(
  102087. sqlite3 *db,
  102088. Table *pTab,
  102089. Module *pMod,
  102090. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  102091. char **pzErr
  102092. ){
  102093. VtabCtx sCtx, *pPriorCtx;
  102094. VTable *pVTable;
  102095. int rc;
  102096. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  102097. int nArg = pTab->nModuleArg;
  102098. char *zErr = 0;
  102099. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  102100. int iDb;
  102101. if( !zModuleName ){
  102102. return SQLITE_NOMEM;
  102103. }
  102104. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  102105. if( !pVTable ){
  102106. sqlite3DbFree(db, zModuleName);
  102107. return SQLITE_NOMEM;
  102108. }
  102109. pVTable->db = db;
  102110. pVTable->pMod = pMod;
  102111. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102112. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  102113. /* Invoke the virtual table constructor */
  102114. assert( &db->pVtabCtx );
  102115. assert( xConstruct );
  102116. sCtx.pTab = pTab;
  102117. sCtx.pVTable = pVTable;
  102118. pPriorCtx = db->pVtabCtx;
  102119. db->pVtabCtx = &sCtx;
  102120. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  102121. db->pVtabCtx = pPriorCtx;
  102122. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  102123. if( SQLITE_OK!=rc ){
  102124. if( zErr==0 ){
  102125. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  102126. }else {
  102127. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  102128. sqlite3_free(zErr);
  102129. }
  102130. sqlite3DbFree(db, pVTable);
  102131. }else if( ALWAYS(pVTable->pVtab) ){
  102132. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  102133. ** the sqlite3_vtab object if successful. */
  102134. pVTable->pVtab->pModule = pMod->pModule;
  102135. pVTable->nRef = 1;
  102136. if( sCtx.pTab ){
  102137. const char *zFormat = "vtable constructor did not declare schema: %s";
  102138. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  102139. sqlite3VtabUnlock(pVTable);
  102140. rc = SQLITE_ERROR;
  102141. }else{
  102142. int iCol;
  102143. /* If everything went according to plan, link the new VTable structure
  102144. ** into the linked list headed by pTab->pVTable. Then loop through the
  102145. ** columns of the table to see if any of them contain the token "hidden".
  102146. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  102147. ** the type string. */
  102148. pVTable->pNext = pTab->pVTable;
  102149. pTab->pVTable = pVTable;
  102150. for(iCol=0; iCol<pTab->nCol; iCol++){
  102151. char *zType = pTab->aCol[iCol].zType;
  102152. int nType;
  102153. int i = 0;
  102154. if( !zType ) continue;
  102155. nType = sqlite3Strlen30(zType);
  102156. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  102157. for(i=0; i<nType; i++){
  102158. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  102159. && (zType[i+7]=='\0' || zType[i+7]==' ')
  102160. ){
  102161. i++;
  102162. break;
  102163. }
  102164. }
  102165. }
  102166. if( i<nType ){
  102167. int j;
  102168. int nDel = 6 + (zType[i+6] ? 1 : 0);
  102169. for(j=i; (j+nDel)<=nType; j++){
  102170. zType[j] = zType[j+nDel];
  102171. }
  102172. if( zType[i]=='\0' && i>0 ){
  102173. assert(zType[i-1]==' ');
  102174. zType[i-1] = '\0';
  102175. }
  102176. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  102177. }
  102178. }
  102179. }
  102180. }
  102181. sqlite3DbFree(db, zModuleName);
  102182. return rc;
  102183. }
  102184. /*
  102185. ** This function is invoked by the parser to call the xConnect() method
  102186. ** of the virtual table pTab. If an error occurs, an error code is returned
  102187. ** and an error left in pParse.
  102188. **
  102189. ** This call is a no-op if table pTab is not a virtual table.
  102190. */
  102191. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  102192. sqlite3 *db = pParse->db;
  102193. const char *zMod;
  102194. Module *pMod;
  102195. int rc;
  102196. assert( pTab );
  102197. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  102198. return SQLITE_OK;
  102199. }
  102200. /* Locate the required virtual table module */
  102201. zMod = pTab->azModuleArg[0];
  102202. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  102203. if( !pMod ){
  102204. const char *zModule = pTab->azModuleArg[0];
  102205. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  102206. rc = SQLITE_ERROR;
  102207. }else{
  102208. char *zErr = 0;
  102209. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  102210. if( rc!=SQLITE_OK ){
  102211. sqlite3ErrorMsg(pParse, "%s", zErr);
  102212. }
  102213. sqlite3DbFree(db, zErr);
  102214. }
  102215. return rc;
  102216. }
  102217. /*
  102218. ** Grow the db->aVTrans[] array so that there is room for at least one
  102219. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  102220. */
  102221. static int growVTrans(sqlite3 *db){
  102222. const int ARRAY_INCR = 5;
  102223. /* Grow the sqlite3.aVTrans array if required */
  102224. if( (db->nVTrans%ARRAY_INCR)==0 ){
  102225. VTable **aVTrans;
  102226. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  102227. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  102228. if( !aVTrans ){
  102229. return SQLITE_NOMEM;
  102230. }
  102231. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  102232. db->aVTrans = aVTrans;
  102233. }
  102234. return SQLITE_OK;
  102235. }
  102236. /*
  102237. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  102238. ** have already been reserved using growVTrans().
  102239. */
  102240. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  102241. /* Add pVtab to the end of sqlite3.aVTrans */
  102242. db->aVTrans[db->nVTrans++] = pVTab;
  102243. sqlite3VtabLock(pVTab);
  102244. }
  102245. /*
  102246. ** This function is invoked by the vdbe to call the xCreate method
  102247. ** of the virtual table named zTab in database iDb.
  102248. **
  102249. ** If an error occurs, *pzErr is set to point an an English language
  102250. ** description of the error and an SQLITE_XXX error code is returned.
  102251. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  102252. */
  102253. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  102254. int rc = SQLITE_OK;
  102255. Table *pTab;
  102256. Module *pMod;
  102257. const char *zMod;
  102258. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  102259. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  102260. /* Locate the required virtual table module */
  102261. zMod = pTab->azModuleArg[0];
  102262. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  102263. /* If the module has been registered and includes a Create method,
  102264. ** invoke it now. If the module has not been registered, return an
  102265. ** error. Otherwise, do nothing.
  102266. */
  102267. if( !pMod ){
  102268. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  102269. rc = SQLITE_ERROR;
  102270. }else{
  102271. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  102272. }
  102273. /* Justification of ALWAYS(): The xConstructor method is required to
  102274. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  102275. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  102276. rc = growVTrans(db);
  102277. if( rc==SQLITE_OK ){
  102278. addToVTrans(db, sqlite3GetVTable(db, pTab));
  102279. }
  102280. }
  102281. return rc;
  102282. }
  102283. /*
  102284. ** This function is used to set the schema of a virtual table. It is only
  102285. ** valid to call this function from within the xCreate() or xConnect() of a
  102286. ** virtual table module.
  102287. */
  102288. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  102289. Parse *pParse;
  102290. int rc = SQLITE_OK;
  102291. Table *pTab;
  102292. char *zErr = 0;
  102293. sqlite3_mutex_enter(db->mutex);
  102294. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  102295. sqlite3Error(db, SQLITE_MISUSE, 0);
  102296. sqlite3_mutex_leave(db->mutex);
  102297. return SQLITE_MISUSE_BKPT;
  102298. }
  102299. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  102300. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  102301. if( pParse==0 ){
  102302. rc = SQLITE_NOMEM;
  102303. }else{
  102304. pParse->declareVtab = 1;
  102305. pParse->db = db;
  102306. pParse->nQueryLoop = 1;
  102307. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  102308. && pParse->pNewTable
  102309. && !db->mallocFailed
  102310. && !pParse->pNewTable->pSelect
  102311. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  102312. ){
  102313. if( !pTab->aCol ){
  102314. pTab->aCol = pParse->pNewTable->aCol;
  102315. pTab->nCol = pParse->pNewTable->nCol;
  102316. pParse->pNewTable->nCol = 0;
  102317. pParse->pNewTable->aCol = 0;
  102318. }
  102319. db->pVtabCtx->pTab = 0;
  102320. }else{
  102321. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  102322. sqlite3DbFree(db, zErr);
  102323. rc = SQLITE_ERROR;
  102324. }
  102325. pParse->declareVtab = 0;
  102326. if( pParse->pVdbe ){
  102327. sqlite3VdbeFinalize(pParse->pVdbe);
  102328. }
  102329. sqlite3DeleteTable(db, pParse->pNewTable);
  102330. sqlite3StackFree(db, pParse);
  102331. }
  102332. assert( (rc&0xff)==rc );
  102333. rc = sqlite3ApiExit(db, rc);
  102334. sqlite3_mutex_leave(db->mutex);
  102335. return rc;
  102336. }
  102337. /*
  102338. ** This function is invoked by the vdbe to call the xDestroy method
  102339. ** of the virtual table named zTab in database iDb. This occurs
  102340. ** when a DROP TABLE is mentioned.
  102341. **
  102342. ** This call is a no-op if zTab is not a virtual table.
  102343. */
  102344. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  102345. int rc = SQLITE_OK;
  102346. Table *pTab;
  102347. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  102348. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  102349. VTable *p = vtabDisconnectAll(db, pTab);
  102350. assert( rc==SQLITE_OK );
  102351. rc = p->pMod->pModule->xDestroy(p->pVtab);
  102352. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  102353. if( rc==SQLITE_OK ){
  102354. assert( pTab->pVTable==p && p->pNext==0 );
  102355. p->pVtab = 0;
  102356. pTab->pVTable = 0;
  102357. sqlite3VtabUnlock(p);
  102358. }
  102359. }
  102360. return rc;
  102361. }
  102362. /*
  102363. ** This function invokes either the xRollback or xCommit method
  102364. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  102365. ** called is identified by the second argument, "offset", which is
  102366. ** the offset of the method to call in the sqlite3_module structure.
  102367. **
  102368. ** The array is cleared after invoking the callbacks.
  102369. */
  102370. static void callFinaliser(sqlite3 *db, int offset){
  102371. int i;
  102372. if( db->aVTrans ){
  102373. for(i=0; i<db->nVTrans; i++){
  102374. VTable *pVTab = db->aVTrans[i];
  102375. sqlite3_vtab *p = pVTab->pVtab;
  102376. if( p ){
  102377. int (*x)(sqlite3_vtab *);
  102378. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  102379. if( x ) x(p);
  102380. }
  102381. pVTab->iSavepoint = 0;
  102382. sqlite3VtabUnlock(pVTab);
  102383. }
  102384. sqlite3DbFree(db, db->aVTrans);
  102385. db->nVTrans = 0;
  102386. db->aVTrans = 0;
  102387. }
  102388. }
  102389. /*
  102390. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  102391. ** array. Return the error code for the first error that occurs, or
  102392. ** SQLITE_OK if all xSync operations are successful.
  102393. **
  102394. ** If an error message is available, leave it in p->zErrMsg.
  102395. */
  102396. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  102397. int i;
  102398. int rc = SQLITE_OK;
  102399. VTable **aVTrans = db->aVTrans;
  102400. db->aVTrans = 0;
  102401. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  102402. int (*x)(sqlite3_vtab *);
  102403. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  102404. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  102405. rc = x(pVtab);
  102406. sqlite3VtabImportErrmsg(p, pVtab);
  102407. }
  102408. }
  102409. db->aVTrans = aVTrans;
  102410. return rc;
  102411. }
  102412. /*
  102413. ** Invoke the xRollback method of all virtual tables in the
  102414. ** sqlite3.aVTrans array. Then clear the array itself.
  102415. */
  102416. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  102417. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  102418. return SQLITE_OK;
  102419. }
  102420. /*
  102421. ** Invoke the xCommit method of all virtual tables in the
  102422. ** sqlite3.aVTrans array. Then clear the array itself.
  102423. */
  102424. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  102425. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  102426. return SQLITE_OK;
  102427. }
  102428. /*
  102429. ** If the virtual table pVtab supports the transaction interface
  102430. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  102431. ** not currently open, invoke the xBegin method now.
  102432. **
  102433. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  102434. ** in the sqlite3.aVTrans array.
  102435. */
  102436. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  102437. int rc = SQLITE_OK;
  102438. const sqlite3_module *pModule;
  102439. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  102440. ** than zero, then this function is being called from within a
  102441. ** virtual module xSync() callback. It is illegal to write to
  102442. ** virtual module tables in this case, so return SQLITE_LOCKED.
  102443. */
  102444. if( sqlite3VtabInSync(db) ){
  102445. return SQLITE_LOCKED;
  102446. }
  102447. if( !pVTab ){
  102448. return SQLITE_OK;
  102449. }
  102450. pModule = pVTab->pVtab->pModule;
  102451. if( pModule->xBegin ){
  102452. int i;
  102453. /* If pVtab is already in the aVTrans array, return early */
  102454. for(i=0; i<db->nVTrans; i++){
  102455. if( db->aVTrans[i]==pVTab ){
  102456. return SQLITE_OK;
  102457. }
  102458. }
  102459. /* Invoke the xBegin method. If successful, add the vtab to the
  102460. ** sqlite3.aVTrans[] array. */
  102461. rc = growVTrans(db);
  102462. if( rc==SQLITE_OK ){
  102463. rc = pModule->xBegin(pVTab->pVtab);
  102464. if( rc==SQLITE_OK ){
  102465. addToVTrans(db, pVTab);
  102466. }
  102467. }
  102468. }
  102469. return rc;
  102470. }
  102471. /*
  102472. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  102473. ** virtual tables that currently have an open transaction. Pass iSavepoint
  102474. ** as the second argument to the virtual table method invoked.
  102475. **
  102476. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  102477. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  102478. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  102479. ** an open transaction is invoked.
  102480. **
  102481. ** If any virtual table method returns an error code other than SQLITE_OK,
  102482. ** processing is abandoned and the error returned to the caller of this
  102483. ** function immediately. If all calls to virtual table methods are successful,
  102484. ** SQLITE_OK is returned.
  102485. */
  102486. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  102487. int rc = SQLITE_OK;
  102488. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  102489. assert( iSavepoint>=0 );
  102490. if( db->aVTrans ){
  102491. int i;
  102492. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  102493. VTable *pVTab = db->aVTrans[i];
  102494. const sqlite3_module *pMod = pVTab->pMod->pModule;
  102495. if( pVTab->pVtab && pMod->iVersion>=2 ){
  102496. int (*xMethod)(sqlite3_vtab *, int);
  102497. switch( op ){
  102498. case SAVEPOINT_BEGIN:
  102499. xMethod = pMod->xSavepoint;
  102500. pVTab->iSavepoint = iSavepoint+1;
  102501. break;
  102502. case SAVEPOINT_ROLLBACK:
  102503. xMethod = pMod->xRollbackTo;
  102504. break;
  102505. default:
  102506. xMethod = pMod->xRelease;
  102507. break;
  102508. }
  102509. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  102510. rc = xMethod(pVTab->pVtab, iSavepoint);
  102511. }
  102512. }
  102513. }
  102514. }
  102515. return rc;
  102516. }
  102517. /*
  102518. ** The first parameter (pDef) is a function implementation. The
  102519. ** second parameter (pExpr) is the first argument to this function.
  102520. ** If pExpr is a column in a virtual table, then let the virtual
  102521. ** table implementation have an opportunity to overload the function.
  102522. **
  102523. ** This routine is used to allow virtual table implementations to
  102524. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  102525. **
  102526. ** Return either the pDef argument (indicating no change) or a
  102527. ** new FuncDef structure that is marked as ephemeral using the
  102528. ** SQLITE_FUNC_EPHEM flag.
  102529. */
  102530. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  102531. sqlite3 *db, /* Database connection for reporting malloc problems */
  102532. FuncDef *pDef, /* Function to possibly overload */
  102533. int nArg, /* Number of arguments to the function */
  102534. Expr *pExpr /* First argument to the function */
  102535. ){
  102536. Table *pTab;
  102537. sqlite3_vtab *pVtab;
  102538. sqlite3_module *pMod;
  102539. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  102540. void *pArg = 0;
  102541. FuncDef *pNew;
  102542. int rc = 0;
  102543. char *zLowerName;
  102544. unsigned char *z;
  102545. /* Check to see the left operand is a column in a virtual table */
  102546. if( NEVER(pExpr==0) ) return pDef;
  102547. if( pExpr->op!=TK_COLUMN ) return pDef;
  102548. pTab = pExpr->pTab;
  102549. if( NEVER(pTab==0) ) return pDef;
  102550. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  102551. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  102552. assert( pVtab!=0 );
  102553. assert( pVtab->pModule!=0 );
  102554. pMod = (sqlite3_module *)pVtab->pModule;
  102555. if( pMod->xFindFunction==0 ) return pDef;
  102556. /* Call the xFindFunction method on the virtual table implementation
  102557. ** to see if the implementation wants to overload this function
  102558. */
  102559. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  102560. if( zLowerName ){
  102561. for(z=(unsigned char*)zLowerName; *z; z++){
  102562. *z = sqlite3UpperToLower[*z];
  102563. }
  102564. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  102565. sqlite3DbFree(db, zLowerName);
  102566. }
  102567. if( rc==0 ){
  102568. return pDef;
  102569. }
  102570. /* Create a new ephemeral function definition for the overloaded
  102571. ** function */
  102572. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  102573. + sqlite3Strlen30(pDef->zName) + 1);
  102574. if( pNew==0 ){
  102575. return pDef;
  102576. }
  102577. *pNew = *pDef;
  102578. pNew->zName = (char *)&pNew[1];
  102579. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  102580. pNew->xFunc = xFunc;
  102581. pNew->pUserData = pArg;
  102582. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  102583. return pNew;
  102584. }
  102585. /*
  102586. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  102587. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  102588. ** array if it is missing. If pTab is already in the array, this routine
  102589. ** is a no-op.
  102590. */
  102591. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  102592. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  102593. int i, n;
  102594. Table **apVtabLock;
  102595. assert( IsVirtual(pTab) );
  102596. for(i=0; i<pToplevel->nVtabLock; i++){
  102597. if( pTab==pToplevel->apVtabLock[i] ) return;
  102598. }
  102599. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  102600. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  102601. if( apVtabLock ){
  102602. pToplevel->apVtabLock = apVtabLock;
  102603. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  102604. }else{
  102605. pToplevel->db->mallocFailed = 1;
  102606. }
  102607. }
  102608. /*
  102609. ** Return the ON CONFLICT resolution mode in effect for the virtual
  102610. ** table update operation currently in progress.
  102611. **
  102612. ** The results of this routine are undefined unless it is called from
  102613. ** within an xUpdate method.
  102614. */
  102615. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  102616. static const unsigned char aMap[] = {
  102617. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  102618. };
  102619. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  102620. assert( OE_Ignore==4 && OE_Replace==5 );
  102621. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  102622. return (int)aMap[db->vtabOnConflict-1];
  102623. }
  102624. /*
  102625. ** Call from within the xCreate() or xConnect() methods to provide
  102626. ** the SQLite core with additional information about the behavior
  102627. ** of the virtual table being implemented.
  102628. */
  102629. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  102630. va_list ap;
  102631. int rc = SQLITE_OK;
  102632. sqlite3_mutex_enter(db->mutex);
  102633. va_start(ap, op);
  102634. switch( op ){
  102635. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  102636. VtabCtx *p = db->pVtabCtx;
  102637. if( !p ){
  102638. rc = SQLITE_MISUSE_BKPT;
  102639. }else{
  102640. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  102641. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  102642. }
  102643. break;
  102644. }
  102645. default:
  102646. rc = SQLITE_MISUSE_BKPT;
  102647. break;
  102648. }
  102649. va_end(ap);
  102650. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  102651. sqlite3_mutex_leave(db->mutex);
  102652. return rc;
  102653. }
  102654. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  102655. /************** End of vtab.c ************************************************/
  102656. /************** Begin file where.c *******************************************/
  102657. /*
  102658. ** 2001 September 15
  102659. **
  102660. ** The author disclaims copyright to this source code. In place of
  102661. ** a legal notice, here is a blessing:
  102662. **
  102663. ** May you do good and not evil.
  102664. ** May you find forgiveness for yourself and forgive others.
  102665. ** May you share freely, never taking more than you give.
  102666. **
  102667. *************************************************************************
  102668. ** This module contains C code that generates VDBE code used to process
  102669. ** the WHERE clause of SQL statements. This module is responsible for
  102670. ** generating the code that loops through a table looking for applicable
  102671. ** rows. Indices are selected and used to speed the search when doing
  102672. ** so is applicable. Because this module is responsible for selecting
  102673. ** indices, you might also think of this module as the "query optimizer".
  102674. */
  102675. /*
  102676. ** Trace output macros
  102677. */
  102678. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  102679. /***/ int sqlite3WhereTrace = 0;
  102680. #endif
  102681. #if defined(SQLITE_DEBUG) \
  102682. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  102683. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  102684. # define WHERETRACE_ENABLED 1
  102685. #else
  102686. # define WHERETRACE(K,X)
  102687. #endif
  102688. /* Forward references
  102689. */
  102690. typedef struct WhereClause WhereClause;
  102691. typedef struct WhereMaskSet WhereMaskSet;
  102692. typedef struct WhereOrInfo WhereOrInfo;
  102693. typedef struct WhereAndInfo WhereAndInfo;
  102694. typedef struct WhereLevel WhereLevel;
  102695. typedef struct WhereLoop WhereLoop;
  102696. typedef struct WherePath WherePath;
  102697. typedef struct WhereTerm WhereTerm;
  102698. typedef struct WhereLoopBuilder WhereLoopBuilder;
  102699. typedef struct WhereScan WhereScan;
  102700. typedef struct WhereOrCost WhereOrCost;
  102701. typedef struct WhereOrSet WhereOrSet;
  102702. /*
  102703. ** This object contains information needed to implement a single nested
  102704. ** loop in WHERE clause.
  102705. **
  102706. ** Contrast this object with WhereLoop. This object describes the
  102707. ** implementation of the loop. WhereLoop describes the algorithm.
  102708. ** This object contains a pointer to the WhereLoop algorithm as one of
  102709. ** its elements.
  102710. **
  102711. ** The WhereInfo object contains a single instance of this object for
  102712. ** each term in the FROM clause (which is to say, for each of the
  102713. ** nested loops as implemented). The order of WhereLevel objects determines
  102714. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  102715. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  102716. */
  102717. struct WhereLevel {
  102718. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  102719. int iTabCur; /* The VDBE cursor used to access the table */
  102720. int iIdxCur; /* The VDBE cursor used to access pIdx */
  102721. int addrBrk; /* Jump here to break out of the loop */
  102722. int addrNxt; /* Jump here to start the next IN combination */
  102723. int addrCont; /* Jump here to continue with the next loop cycle */
  102724. int addrFirst; /* First instruction of interior of the loop */
  102725. int addrBody; /* Beginning of the body of this loop */
  102726. u8 iFrom; /* Which entry in the FROM clause */
  102727. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  102728. int p1, p2; /* Operands of the opcode used to ends the loop */
  102729. union { /* Information that depends on pWLoop->wsFlags */
  102730. struct {
  102731. int nIn; /* Number of entries in aInLoop[] */
  102732. struct InLoop {
  102733. int iCur; /* The VDBE cursor used by this IN operator */
  102734. int addrInTop; /* Top of the IN loop */
  102735. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  102736. } *aInLoop; /* Information about each nested IN operator */
  102737. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  102738. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  102739. } u;
  102740. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  102741. Bitmask notReady; /* FROM entries not usable at this level */
  102742. };
  102743. /*
  102744. ** Each instance of this object represents an algorithm for evaluating one
  102745. ** term of a join. Every term of the FROM clause will have at least
  102746. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  102747. ** prevent a query solution - which is an error) and many terms of the
  102748. ** FROM clause will have multiple WhereLoop objects, each describing a
  102749. ** potential way of implementing that FROM-clause term, together with
  102750. ** dependencies and cost estimates for using the chosen algorithm.
  102751. **
  102752. ** Query planning consists of building up a collection of these WhereLoop
  102753. ** objects, then computing a particular sequence of WhereLoop objects, with
  102754. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  102755. ** and that minimize the overall cost.
  102756. */
  102757. struct WhereLoop {
  102758. Bitmask prereq; /* Bitmask of other loops that must run first */
  102759. Bitmask maskSelf; /* Bitmask identifying table iTab */
  102760. #ifdef SQLITE_DEBUG
  102761. char cId; /* Symbolic ID of this loop for debugging use */
  102762. #endif
  102763. u8 iTab; /* Position in FROM clause of table for this loop */
  102764. u8 iSortIdx; /* Sorting index number. 0==None */
  102765. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  102766. LogEst rRun; /* Cost of running each loop */
  102767. LogEst nOut; /* Estimated number of output rows */
  102768. union {
  102769. struct { /* Information for internal btree tables */
  102770. int nEq; /* Number of equality constraints */
  102771. Index *pIndex; /* Index used, or NULL */
  102772. } btree;
  102773. struct { /* Information for virtual tables */
  102774. int idxNum; /* Index number */
  102775. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  102776. u8 isOrdered; /* True if satisfies ORDER BY */
  102777. u16 omitMask; /* Terms that may be omitted */
  102778. char *idxStr; /* Index identifier string */
  102779. } vtab;
  102780. } u;
  102781. u32 wsFlags; /* WHERE_* flags describing the plan */
  102782. u16 nLTerm; /* Number of entries in aLTerm[] */
  102783. /**** whereLoopXfer() copies fields above ***********************/
  102784. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  102785. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  102786. WhereTerm **aLTerm; /* WhereTerms used */
  102787. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  102788. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  102789. };
  102790. /* This object holds the prerequisites and the cost of running a
  102791. ** subquery on one operand of an OR operator in the WHERE clause.
  102792. ** See WhereOrSet for additional information
  102793. */
  102794. struct WhereOrCost {
  102795. Bitmask prereq; /* Prerequisites */
  102796. LogEst rRun; /* Cost of running this subquery */
  102797. LogEst nOut; /* Number of outputs for this subquery */
  102798. };
  102799. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  102800. ** correspond to the subquery(s) of OR-clause processing. Only the
  102801. ** best N_OR_COST elements are retained.
  102802. */
  102803. #define N_OR_COST 3
  102804. struct WhereOrSet {
  102805. u16 n; /* Number of valid a[] entries */
  102806. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  102807. };
  102808. /* Forward declaration of methods */
  102809. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  102810. /*
  102811. ** Each instance of this object holds a sequence of WhereLoop objects
  102812. ** that implement some or all of a query plan.
  102813. **
  102814. ** Think of each WhereLoop object as a node in a graph with arcs
  102815. ** showing dependencies and costs for travelling between nodes. (That is
  102816. ** not a completely accurate description because WhereLoop costs are a
  102817. ** vector, not a scalar, and because dependencies are many-to-one, not
  102818. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  102819. ** Then a WherePath object is a path through the graph that visits some
  102820. ** or all of the WhereLoop objects once.
  102821. **
  102822. ** The "solver" works by creating the N best WherePath objects of length
  102823. ** 1. Then using those as a basis to compute the N best WherePath objects
  102824. ** of length 2. And so forth until the length of WherePaths equals the
  102825. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  102826. ** at the end is the choosen query plan.
  102827. */
  102828. struct WherePath {
  102829. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  102830. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  102831. LogEst nRow; /* Estimated number of rows generated by this path */
  102832. LogEst rCost; /* Total cost of this path */
  102833. u8 isOrdered; /* True if this path satisfies ORDER BY */
  102834. u8 isOrderedValid; /* True if the isOrdered field is valid */
  102835. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  102836. };
  102837. /*
  102838. ** The query generator uses an array of instances of this structure to
  102839. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  102840. ** clause subexpression is separated from the others by AND operators,
  102841. ** usually, or sometimes subexpressions separated by OR.
  102842. **
  102843. ** All WhereTerms are collected into a single WhereClause structure.
  102844. ** The following identity holds:
  102845. **
  102846. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  102847. **
  102848. ** When a term is of the form:
  102849. **
  102850. ** X <op> <expr>
  102851. **
  102852. ** where X is a column name and <op> is one of certain operators,
  102853. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  102854. ** cursor number and column number for X. WhereTerm.eOperator records
  102855. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  102856. ** use of a bitmask encoding for the operator allows us to search
  102857. ** quickly for terms that match any of several different operators.
  102858. **
  102859. ** A WhereTerm might also be two or more subterms connected by OR:
  102860. **
  102861. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  102862. **
  102863. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  102864. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  102865. ** is collected about the OR clause.
  102866. **
  102867. ** If a term in the WHERE clause does not match either of the two previous
  102868. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  102869. ** to the original subexpression content and wtFlags is set up appropriately
  102870. ** but no other fields in the WhereTerm object are meaningful.
  102871. **
  102872. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  102873. ** but they do so indirectly. A single WhereMaskSet structure translates
  102874. ** cursor number into bits and the translated bit is stored in the prereq
  102875. ** fields. The translation is used in order to maximize the number of
  102876. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  102877. ** spread out over the non-negative integers. For example, the cursor
  102878. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  102879. ** translates these sparse cursor numbers into consecutive integers
  102880. ** beginning with 0 in order to make the best possible use of the available
  102881. ** bits in the Bitmask. So, in the example above, the cursor numbers
  102882. ** would be mapped into integers 0 through 7.
  102883. **
  102884. ** The number of terms in a join is limited by the number of bits
  102885. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  102886. ** is only able to process joins with 64 or fewer tables.
  102887. */
  102888. struct WhereTerm {
  102889. Expr *pExpr; /* Pointer to the subexpression that is this term */
  102890. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  102891. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  102892. union {
  102893. int leftColumn; /* Column number of X in "X <op> <expr>" */
  102894. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  102895. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  102896. } u;
  102897. LogEst truthProb; /* Probability of truth for this expression */
  102898. u16 eOperator; /* A WO_xx value describing <op> */
  102899. u8 wtFlags; /* TERM_xxx bit flags. See below */
  102900. u8 nChild; /* Number of children that must disable us */
  102901. WhereClause *pWC; /* The clause this term is part of */
  102902. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  102903. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  102904. };
  102905. /*
  102906. ** Allowed values of WhereTerm.wtFlags
  102907. */
  102908. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  102909. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  102910. #define TERM_CODED 0x04 /* This term is already coded */
  102911. #define TERM_COPIED 0x08 /* Has a child */
  102912. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  102913. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  102914. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  102915. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  102916. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  102917. #else
  102918. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  102919. #endif
  102920. /*
  102921. ** An instance of the WhereScan object is used as an iterator for locating
  102922. ** terms in the WHERE clause that are useful to the query planner.
  102923. */
  102924. struct WhereScan {
  102925. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  102926. WhereClause *pWC; /* WhereClause currently being scanned */
  102927. char *zCollName; /* Required collating sequence, if not NULL */
  102928. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  102929. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  102930. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  102931. u32 opMask; /* Acceptable operators */
  102932. int k; /* Resume scanning at this->pWC->a[this->k] */
  102933. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  102934. };
  102935. /*
  102936. ** An instance of the following structure holds all information about a
  102937. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  102938. **
  102939. ** Explanation of pOuter: For a WHERE clause of the form
  102940. **
  102941. ** a AND ((b AND c) OR (d AND e)) AND f
  102942. **
  102943. ** There are separate WhereClause objects for the whole clause and for
  102944. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  102945. ** subclauses points to the WhereClause object for the whole clause.
  102946. */
  102947. struct WhereClause {
  102948. WhereInfo *pWInfo; /* WHERE clause processing context */
  102949. WhereClause *pOuter; /* Outer conjunction */
  102950. u8 op; /* Split operator. TK_AND or TK_OR */
  102951. int nTerm; /* Number of terms */
  102952. int nSlot; /* Number of entries in a[] */
  102953. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  102954. #if defined(SQLITE_SMALL_STACK)
  102955. WhereTerm aStatic[1]; /* Initial static space for a[] */
  102956. #else
  102957. WhereTerm aStatic[8]; /* Initial static space for a[] */
  102958. #endif
  102959. };
  102960. /*
  102961. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  102962. ** a dynamically allocated instance of the following structure.
  102963. */
  102964. struct WhereOrInfo {
  102965. WhereClause wc; /* Decomposition into subterms */
  102966. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  102967. };
  102968. /*
  102969. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  102970. ** a dynamically allocated instance of the following structure.
  102971. */
  102972. struct WhereAndInfo {
  102973. WhereClause wc; /* The subexpression broken out */
  102974. };
  102975. /*
  102976. ** An instance of the following structure keeps track of a mapping
  102977. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  102978. **
  102979. ** The VDBE cursor numbers are small integers contained in
  102980. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  102981. ** clause, the cursor numbers might not begin with 0 and they might
  102982. ** contain gaps in the numbering sequence. But we want to make maximum
  102983. ** use of the bits in our bitmasks. This structure provides a mapping
  102984. ** from the sparse cursor numbers into consecutive integers beginning
  102985. ** with 0.
  102986. **
  102987. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  102988. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  102989. **
  102990. ** For example, if the WHERE clause expression used these VDBE
  102991. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  102992. ** would map those cursor numbers into bits 0 through 5.
  102993. **
  102994. ** Note that the mapping is not necessarily ordered. In the example
  102995. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  102996. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  102997. ** does not really matter. What is important is that sparse cursor
  102998. ** numbers all get mapped into bit numbers that begin with 0 and contain
  102999. ** no gaps.
  103000. */
  103001. struct WhereMaskSet {
  103002. int n; /* Number of assigned cursor values */
  103003. int ix[BMS]; /* Cursor assigned to each bit */
  103004. };
  103005. /*
  103006. ** This object is a convenience wrapper holding all information needed
  103007. ** to construct WhereLoop objects for a particular query.
  103008. */
  103009. struct WhereLoopBuilder {
  103010. WhereInfo *pWInfo; /* Information about this WHERE */
  103011. WhereClause *pWC; /* WHERE clause terms */
  103012. ExprList *pOrderBy; /* ORDER BY clause */
  103013. WhereLoop *pNew; /* Template WhereLoop */
  103014. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  103015. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  103016. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  103017. int nRecValid; /* Number of valid fields currently in pRec */
  103018. #endif
  103019. };
  103020. /*
  103021. ** The WHERE clause processing routine has two halves. The
  103022. ** first part does the start of the WHERE loop and the second
  103023. ** half does the tail of the WHERE loop. An instance of
  103024. ** this structure is returned by the first half and passed
  103025. ** into the second half to give some continuity.
  103026. **
  103027. ** An instance of this object holds the complete state of the query
  103028. ** planner.
  103029. */
  103030. struct WhereInfo {
  103031. Parse *pParse; /* Parsing and code generating context */
  103032. SrcList *pTabList; /* List of tables in the join */
  103033. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  103034. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  103035. WhereLoop *pLoops; /* List of all WhereLoop objects */
  103036. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  103037. LogEst nRowOut; /* Estimated number of output rows */
  103038. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  103039. u8 bOBSat; /* ORDER BY satisfied by indices */
  103040. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  103041. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  103042. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  103043. u8 nLevel; /* Number of nested loop */
  103044. int iTop; /* The very beginning of the WHERE loop */
  103045. int iContinue; /* Jump here to continue with next record */
  103046. int iBreak; /* Jump here to break out of the loop */
  103047. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  103048. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  103049. WhereClause sWC; /* Decomposition of the WHERE clause */
  103050. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  103051. };
  103052. /*
  103053. ** Bitmasks for the operators on WhereTerm objects. These are all
  103054. ** operators that are of interest to the query planner. An
  103055. ** OR-ed combination of these values can be used when searching for
  103056. ** particular WhereTerms within a WhereClause.
  103057. */
  103058. #define WO_IN 0x001
  103059. #define WO_EQ 0x002
  103060. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  103061. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  103062. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  103063. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  103064. #define WO_MATCH 0x040
  103065. #define WO_ISNULL 0x080
  103066. #define WO_OR 0x100 /* Two or more OR-connected terms */
  103067. #define WO_AND 0x200 /* Two or more AND-connected terms */
  103068. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  103069. #define WO_NOOP 0x800 /* This term does not restrict search space */
  103070. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  103071. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  103072. /*
  103073. ** These are definitions of bits in the WhereLoop.wsFlags field.
  103074. ** The particular combination of bits in each WhereLoop help to
  103075. ** determine the algorithm that WhereLoop represents.
  103076. */
  103077. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  103078. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  103079. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  103080. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  103081. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  103082. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  103083. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  103084. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  103085. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  103086. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  103087. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  103088. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  103089. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  103090. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  103091. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  103092. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  103093. /*
  103094. ** Return the estimated number of output rows from a WHERE clause
  103095. */
  103096. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  103097. return sqlite3LogEstToInt(pWInfo->nRowOut);
  103098. }
  103099. /*
  103100. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  103101. ** WHERE clause returns outputs for DISTINCT processing.
  103102. */
  103103. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  103104. return pWInfo->eDistinct;
  103105. }
  103106. /*
  103107. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  103108. ** Return FALSE if the output needs to be sorted.
  103109. */
  103110. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  103111. return pWInfo->bOBSat!=0;
  103112. }
  103113. /*
  103114. ** Return the VDBE address or label to jump to in order to continue
  103115. ** immediately with the next row of a WHERE clause.
  103116. */
  103117. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  103118. return pWInfo->iContinue;
  103119. }
  103120. /*
  103121. ** Return the VDBE address or label to jump to in order to break
  103122. ** out of a WHERE loop.
  103123. */
  103124. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  103125. return pWInfo->iBreak;
  103126. }
  103127. /*
  103128. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  103129. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  103130. ** UPDATE or DELETE might change subsequent WHERE clause results.
  103131. */
  103132. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  103133. return pWInfo->okOnePass;
  103134. }
  103135. /*
  103136. ** Move the content of pSrc into pDest
  103137. */
  103138. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  103139. pDest->n = pSrc->n;
  103140. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  103141. }
  103142. /*
  103143. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  103144. **
  103145. ** The new entry might overwrite an existing entry, or it might be
  103146. ** appended, or it might be discarded. Do whatever is the right thing
  103147. ** so that pSet keeps the N_OR_COST best entries seen so far.
  103148. */
  103149. static int whereOrInsert(
  103150. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  103151. Bitmask prereq, /* Prerequisites of the new entry */
  103152. LogEst rRun, /* Run-cost of the new entry */
  103153. LogEst nOut /* Number of outputs for the new entry */
  103154. ){
  103155. u16 i;
  103156. WhereOrCost *p;
  103157. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  103158. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  103159. goto whereOrInsert_done;
  103160. }
  103161. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  103162. return 0;
  103163. }
  103164. }
  103165. if( pSet->n<N_OR_COST ){
  103166. p = &pSet->a[pSet->n++];
  103167. p->nOut = nOut;
  103168. }else{
  103169. p = pSet->a;
  103170. for(i=1; i<pSet->n; i++){
  103171. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  103172. }
  103173. if( p->rRun<=rRun ) return 0;
  103174. }
  103175. whereOrInsert_done:
  103176. p->prereq = prereq;
  103177. p->rRun = rRun;
  103178. if( p->nOut>nOut ) p->nOut = nOut;
  103179. return 1;
  103180. }
  103181. /*
  103182. ** Initialize a preallocated WhereClause structure.
  103183. */
  103184. static void whereClauseInit(
  103185. WhereClause *pWC, /* The WhereClause to be initialized */
  103186. WhereInfo *pWInfo /* The WHERE processing context */
  103187. ){
  103188. pWC->pWInfo = pWInfo;
  103189. pWC->pOuter = 0;
  103190. pWC->nTerm = 0;
  103191. pWC->nSlot = ArraySize(pWC->aStatic);
  103192. pWC->a = pWC->aStatic;
  103193. }
  103194. /* Forward reference */
  103195. static void whereClauseClear(WhereClause*);
  103196. /*
  103197. ** Deallocate all memory associated with a WhereOrInfo object.
  103198. */
  103199. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  103200. whereClauseClear(&p->wc);
  103201. sqlite3DbFree(db, p);
  103202. }
  103203. /*
  103204. ** Deallocate all memory associated with a WhereAndInfo object.
  103205. */
  103206. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  103207. whereClauseClear(&p->wc);
  103208. sqlite3DbFree(db, p);
  103209. }
  103210. /*
  103211. ** Deallocate a WhereClause structure. The WhereClause structure
  103212. ** itself is not freed. This routine is the inverse of whereClauseInit().
  103213. */
  103214. static void whereClauseClear(WhereClause *pWC){
  103215. int i;
  103216. WhereTerm *a;
  103217. sqlite3 *db = pWC->pWInfo->pParse->db;
  103218. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  103219. if( a->wtFlags & TERM_DYNAMIC ){
  103220. sqlite3ExprDelete(db, a->pExpr);
  103221. }
  103222. if( a->wtFlags & TERM_ORINFO ){
  103223. whereOrInfoDelete(db, a->u.pOrInfo);
  103224. }else if( a->wtFlags & TERM_ANDINFO ){
  103225. whereAndInfoDelete(db, a->u.pAndInfo);
  103226. }
  103227. }
  103228. if( pWC->a!=pWC->aStatic ){
  103229. sqlite3DbFree(db, pWC->a);
  103230. }
  103231. }
  103232. /*
  103233. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  103234. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  103235. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  103236. ** 0 is returned if the new WhereTerm could not be added due to a memory
  103237. ** allocation error. The memory allocation failure will be recorded in
  103238. ** the db->mallocFailed flag so that higher-level functions can detect it.
  103239. **
  103240. ** This routine will increase the size of the pWC->a[] array as necessary.
  103241. **
  103242. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  103243. ** for freeing the expression p is assumed by the WhereClause object pWC.
  103244. ** This is true even if this routine fails to allocate a new WhereTerm.
  103245. **
  103246. ** WARNING: This routine might reallocate the space used to store
  103247. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  103248. ** calling this routine. Such pointers may be reinitialized by referencing
  103249. ** the pWC->a[] array.
  103250. */
  103251. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  103252. WhereTerm *pTerm;
  103253. int idx;
  103254. testcase( wtFlags & TERM_VIRTUAL );
  103255. if( pWC->nTerm>=pWC->nSlot ){
  103256. WhereTerm *pOld = pWC->a;
  103257. sqlite3 *db = pWC->pWInfo->pParse->db;
  103258. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  103259. if( pWC->a==0 ){
  103260. if( wtFlags & TERM_DYNAMIC ){
  103261. sqlite3ExprDelete(db, p);
  103262. }
  103263. pWC->a = pOld;
  103264. return 0;
  103265. }
  103266. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  103267. if( pOld!=pWC->aStatic ){
  103268. sqlite3DbFree(db, pOld);
  103269. }
  103270. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  103271. }
  103272. pTerm = &pWC->a[idx = pWC->nTerm++];
  103273. if( p && ExprHasProperty(p, EP_Unlikely) ){
  103274. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  103275. }else{
  103276. pTerm->truthProb = -1;
  103277. }
  103278. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  103279. pTerm->wtFlags = wtFlags;
  103280. pTerm->pWC = pWC;
  103281. pTerm->iParent = -1;
  103282. return idx;
  103283. }
  103284. /*
  103285. ** This routine identifies subexpressions in the WHERE clause where
  103286. ** each subexpression is separated by the AND operator or some other
  103287. ** operator specified in the op parameter. The WhereClause structure
  103288. ** is filled with pointers to subexpressions. For example:
  103289. **
  103290. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  103291. ** \________/ \_______________/ \________________/
  103292. ** slot[0] slot[1] slot[2]
  103293. **
  103294. ** The original WHERE clause in pExpr is unaltered. All this routine
  103295. ** does is make slot[] entries point to substructure within pExpr.
  103296. **
  103297. ** In the previous sentence and in the diagram, "slot[]" refers to
  103298. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  103299. ** all terms of the WHERE clause.
  103300. */
  103301. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  103302. pWC->op = op;
  103303. if( pExpr==0 ) return;
  103304. if( pExpr->op!=op ){
  103305. whereClauseInsert(pWC, pExpr, 0);
  103306. }else{
  103307. whereSplit(pWC, pExpr->pLeft, op);
  103308. whereSplit(pWC, pExpr->pRight, op);
  103309. }
  103310. }
  103311. /*
  103312. ** Initialize a WhereMaskSet object
  103313. */
  103314. #define initMaskSet(P) (P)->n=0
  103315. /*
  103316. ** Return the bitmask for the given cursor number. Return 0 if
  103317. ** iCursor is not in the set.
  103318. */
  103319. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  103320. int i;
  103321. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  103322. for(i=0; i<pMaskSet->n; i++){
  103323. if( pMaskSet->ix[i]==iCursor ){
  103324. return MASKBIT(i);
  103325. }
  103326. }
  103327. return 0;
  103328. }
  103329. /*
  103330. ** Create a new mask for cursor iCursor.
  103331. **
  103332. ** There is one cursor per table in the FROM clause. The number of
  103333. ** tables in the FROM clause is limited by a test early in the
  103334. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  103335. ** array will never overflow.
  103336. */
  103337. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  103338. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  103339. pMaskSet->ix[pMaskSet->n++] = iCursor;
  103340. }
  103341. /*
  103342. ** These routines walk (recursively) an expression tree and generate
  103343. ** a bitmask indicating which tables are used in that expression
  103344. ** tree.
  103345. */
  103346. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  103347. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  103348. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  103349. Bitmask mask = 0;
  103350. if( p==0 ) return 0;
  103351. if( p->op==TK_COLUMN ){
  103352. mask = getMask(pMaskSet, p->iTable);
  103353. return mask;
  103354. }
  103355. mask = exprTableUsage(pMaskSet, p->pRight);
  103356. mask |= exprTableUsage(pMaskSet, p->pLeft);
  103357. if( ExprHasProperty(p, EP_xIsSelect) ){
  103358. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  103359. }else{
  103360. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  103361. }
  103362. return mask;
  103363. }
  103364. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  103365. int i;
  103366. Bitmask mask = 0;
  103367. if( pList ){
  103368. for(i=0; i<pList->nExpr; i++){
  103369. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  103370. }
  103371. }
  103372. return mask;
  103373. }
  103374. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  103375. Bitmask mask = 0;
  103376. while( pS ){
  103377. SrcList *pSrc = pS->pSrc;
  103378. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  103379. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  103380. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  103381. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  103382. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  103383. if( ALWAYS(pSrc!=0) ){
  103384. int i;
  103385. for(i=0; i<pSrc->nSrc; i++){
  103386. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  103387. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  103388. }
  103389. }
  103390. pS = pS->pPrior;
  103391. }
  103392. return mask;
  103393. }
  103394. /*
  103395. ** Return TRUE if the given operator is one of the operators that is
  103396. ** allowed for an indexable WHERE clause term. The allowed operators are
  103397. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  103398. */
  103399. static int allowedOp(int op){
  103400. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  103401. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  103402. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  103403. assert( TK_GE==TK_EQ+4 );
  103404. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  103405. }
  103406. /*
  103407. ** Swap two objects of type TYPE.
  103408. */
  103409. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  103410. /*
  103411. ** Commute a comparison operator. Expressions of the form "X op Y"
  103412. ** are converted into "Y op X".
  103413. **
  103414. ** If left/right precedence rules come into play when determining the
  103415. ** collating sequence, then COLLATE operators are adjusted to ensure
  103416. ** that the collating sequence does not change. For example:
  103417. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  103418. ** the left hand side of a comparison overrides any collation sequence
  103419. ** attached to the right. For the same reason the EP_Collate flag
  103420. ** is not commuted.
  103421. */
  103422. static void exprCommute(Parse *pParse, Expr *pExpr){
  103423. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  103424. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  103425. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  103426. if( expRight==expLeft ){
  103427. /* Either X and Y both have COLLATE operator or neither do */
  103428. if( expRight ){
  103429. /* Both X and Y have COLLATE operators. Make sure X is always
  103430. ** used by clearing the EP_Collate flag from Y. */
  103431. pExpr->pRight->flags &= ~EP_Collate;
  103432. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  103433. /* Neither X nor Y have COLLATE operators, but X has a non-default
  103434. ** collating sequence. So add the EP_Collate marker on X to cause
  103435. ** it to be searched first. */
  103436. pExpr->pLeft->flags |= EP_Collate;
  103437. }
  103438. }
  103439. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  103440. if( pExpr->op>=TK_GT ){
  103441. assert( TK_LT==TK_GT+2 );
  103442. assert( TK_GE==TK_LE+2 );
  103443. assert( TK_GT>TK_EQ );
  103444. assert( TK_GT<TK_LE );
  103445. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  103446. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  103447. }
  103448. }
  103449. /*
  103450. ** Translate from TK_xx operator to WO_xx bitmask.
  103451. */
  103452. static u16 operatorMask(int op){
  103453. u16 c;
  103454. assert( allowedOp(op) );
  103455. if( op==TK_IN ){
  103456. c = WO_IN;
  103457. }else if( op==TK_ISNULL ){
  103458. c = WO_ISNULL;
  103459. }else{
  103460. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  103461. c = (u16)(WO_EQ<<(op-TK_EQ));
  103462. }
  103463. assert( op!=TK_ISNULL || c==WO_ISNULL );
  103464. assert( op!=TK_IN || c==WO_IN );
  103465. assert( op!=TK_EQ || c==WO_EQ );
  103466. assert( op!=TK_LT || c==WO_LT );
  103467. assert( op!=TK_LE || c==WO_LE );
  103468. assert( op!=TK_GT || c==WO_GT );
  103469. assert( op!=TK_GE || c==WO_GE );
  103470. return c;
  103471. }
  103472. /*
  103473. ** Advance to the next WhereTerm that matches according to the criteria
  103474. ** established when the pScan object was initialized by whereScanInit().
  103475. ** Return NULL if there are no more matching WhereTerms.
  103476. */
  103477. static WhereTerm *whereScanNext(WhereScan *pScan){
  103478. int iCur; /* The cursor on the LHS of the term */
  103479. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  103480. Expr *pX; /* An expression being tested */
  103481. WhereClause *pWC; /* Shorthand for pScan->pWC */
  103482. WhereTerm *pTerm; /* The term being tested */
  103483. int k = pScan->k; /* Where to start scanning */
  103484. while( pScan->iEquiv<=pScan->nEquiv ){
  103485. iCur = pScan->aEquiv[pScan->iEquiv-2];
  103486. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  103487. while( (pWC = pScan->pWC)!=0 ){
  103488. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  103489. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  103490. if( (pTerm->eOperator & WO_EQUIV)!=0
  103491. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  103492. ){
  103493. int j;
  103494. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  103495. assert( pX->op==TK_COLUMN );
  103496. for(j=0; j<pScan->nEquiv; j+=2){
  103497. if( pScan->aEquiv[j]==pX->iTable
  103498. && pScan->aEquiv[j+1]==pX->iColumn ){
  103499. break;
  103500. }
  103501. }
  103502. if( j==pScan->nEquiv ){
  103503. pScan->aEquiv[j] = pX->iTable;
  103504. pScan->aEquiv[j+1] = pX->iColumn;
  103505. pScan->nEquiv += 2;
  103506. }
  103507. }
  103508. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  103509. /* Verify the affinity and collating sequence match */
  103510. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  103511. CollSeq *pColl;
  103512. Parse *pParse = pWC->pWInfo->pParse;
  103513. pX = pTerm->pExpr;
  103514. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  103515. continue;
  103516. }
  103517. assert(pX->pLeft);
  103518. pColl = sqlite3BinaryCompareCollSeq(pParse,
  103519. pX->pLeft, pX->pRight);
  103520. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  103521. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  103522. continue;
  103523. }
  103524. }
  103525. if( (pTerm->eOperator & WO_EQ)!=0
  103526. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  103527. && pX->iTable==pScan->aEquiv[0]
  103528. && pX->iColumn==pScan->aEquiv[1]
  103529. ){
  103530. continue;
  103531. }
  103532. pScan->k = k+1;
  103533. return pTerm;
  103534. }
  103535. }
  103536. }
  103537. pScan->pWC = pScan->pWC->pOuter;
  103538. k = 0;
  103539. }
  103540. pScan->pWC = pScan->pOrigWC;
  103541. k = 0;
  103542. pScan->iEquiv += 2;
  103543. }
  103544. return 0;
  103545. }
  103546. /*
  103547. ** Initialize a WHERE clause scanner object. Return a pointer to the
  103548. ** first match. Return NULL if there are no matches.
  103549. **
  103550. ** The scanner will be searching the WHERE clause pWC. It will look
  103551. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  103552. ** iCur. The <op> must be one of the operators described by opMask.
  103553. **
  103554. ** If the search is for X and the WHERE clause contains terms of the
  103555. ** form X=Y then this routine might also return terms of the form
  103556. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  103557. ** but is enough to handle most commonly occurring SQL statements.
  103558. **
  103559. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  103560. ** index pIdx.
  103561. */
  103562. static WhereTerm *whereScanInit(
  103563. WhereScan *pScan, /* The WhereScan object being initialized */
  103564. WhereClause *pWC, /* The WHERE clause to be scanned */
  103565. int iCur, /* Cursor to scan for */
  103566. int iColumn, /* Column to scan for */
  103567. u32 opMask, /* Operator(s) to scan for */
  103568. Index *pIdx /* Must be compatible with this index */
  103569. ){
  103570. int j;
  103571. /* memset(pScan, 0, sizeof(*pScan)); */
  103572. pScan->pOrigWC = pWC;
  103573. pScan->pWC = pWC;
  103574. if( pIdx && iColumn>=0 ){
  103575. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  103576. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  103577. if( NEVER(j>=pIdx->nColumn) ) return 0;
  103578. }
  103579. pScan->zCollName = pIdx->azColl[j];
  103580. }else{
  103581. pScan->idxaff = 0;
  103582. pScan->zCollName = 0;
  103583. }
  103584. pScan->opMask = opMask;
  103585. pScan->k = 0;
  103586. pScan->aEquiv[0] = iCur;
  103587. pScan->aEquiv[1] = iColumn;
  103588. pScan->nEquiv = 2;
  103589. pScan->iEquiv = 2;
  103590. return whereScanNext(pScan);
  103591. }
  103592. /*
  103593. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  103594. ** where X is a reference to the iColumn of table iCur and <op> is one of
  103595. ** the WO_xx operator codes specified by the op parameter.
  103596. ** Return a pointer to the term. Return 0 if not found.
  103597. **
  103598. ** The term returned might by Y=<expr> if there is another constraint in
  103599. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  103600. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  103601. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  103602. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  103603. ** and the second is for the column number. There are 22 slots in aEquiv[]
  103604. ** so that means we can look for X plus up to 10 other equivalent values.
  103605. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  103606. ** and ... and A9=A10 and A10=<expr>.
  103607. **
  103608. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  103609. ** then try for the one with no dependencies on <expr> - in other words where
  103610. ** <expr> is a constant expression of some kind. Only return entries of
  103611. ** the form "X <op> Y" where Y is a column in another table if no terms of
  103612. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  103613. ** exist, try to return a term that does not use WO_EQUIV.
  103614. */
  103615. static WhereTerm *findTerm(
  103616. WhereClause *pWC, /* The WHERE clause to be searched */
  103617. int iCur, /* Cursor number of LHS */
  103618. int iColumn, /* Column number of LHS */
  103619. Bitmask notReady, /* RHS must not overlap with this mask */
  103620. u32 op, /* Mask of WO_xx values describing operator */
  103621. Index *pIdx /* Must be compatible with this index, if not NULL */
  103622. ){
  103623. WhereTerm *pResult = 0;
  103624. WhereTerm *p;
  103625. WhereScan scan;
  103626. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  103627. while( p ){
  103628. if( (p->prereqRight & notReady)==0 ){
  103629. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  103630. return p;
  103631. }
  103632. if( pResult==0 ) pResult = p;
  103633. }
  103634. p = whereScanNext(&scan);
  103635. }
  103636. return pResult;
  103637. }
  103638. /* Forward reference */
  103639. static void exprAnalyze(SrcList*, WhereClause*, int);
  103640. /*
  103641. ** Call exprAnalyze on all terms in a WHERE clause.
  103642. */
  103643. static void exprAnalyzeAll(
  103644. SrcList *pTabList, /* the FROM clause */
  103645. WhereClause *pWC /* the WHERE clause to be analyzed */
  103646. ){
  103647. int i;
  103648. for(i=pWC->nTerm-1; i>=0; i--){
  103649. exprAnalyze(pTabList, pWC, i);
  103650. }
  103651. }
  103652. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  103653. /*
  103654. ** Check to see if the given expression is a LIKE or GLOB operator that
  103655. ** can be optimized using inequality constraints. Return TRUE if it is
  103656. ** so and false if not.
  103657. **
  103658. ** In order for the operator to be optimizible, the RHS must be a string
  103659. ** literal that does not begin with a wildcard.
  103660. */
  103661. static int isLikeOrGlob(
  103662. Parse *pParse, /* Parsing and code generating context */
  103663. Expr *pExpr, /* Test this expression */
  103664. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  103665. int *pisComplete, /* True if the only wildcard is % in the last character */
  103666. int *pnoCase /* True if uppercase is equivalent to lowercase */
  103667. ){
  103668. const char *z = 0; /* String on RHS of LIKE operator */
  103669. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  103670. ExprList *pList; /* List of operands to the LIKE operator */
  103671. int c; /* One character in z[] */
  103672. int cnt; /* Number of non-wildcard prefix characters */
  103673. char wc[3]; /* Wildcard characters */
  103674. sqlite3 *db = pParse->db; /* Database connection */
  103675. sqlite3_value *pVal = 0;
  103676. int op; /* Opcode of pRight */
  103677. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  103678. return 0;
  103679. }
  103680. #ifdef SQLITE_EBCDIC
  103681. if( *pnoCase ) return 0;
  103682. #endif
  103683. pList = pExpr->x.pList;
  103684. pLeft = pList->a[1].pExpr;
  103685. if( pLeft->op!=TK_COLUMN
  103686. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  103687. || IsVirtual(pLeft->pTab)
  103688. ){
  103689. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  103690. ** be the name of an indexed column with TEXT affinity. */
  103691. return 0;
  103692. }
  103693. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  103694. pRight = pList->a[0].pExpr;
  103695. op = pRight->op;
  103696. if( op==TK_REGISTER ){
  103697. op = pRight->op2;
  103698. }
  103699. if( op==TK_VARIABLE ){
  103700. Vdbe *pReprepare = pParse->pReprepare;
  103701. int iCol = pRight->iColumn;
  103702. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  103703. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  103704. z = (char *)sqlite3_value_text(pVal);
  103705. }
  103706. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  103707. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  103708. }else if( op==TK_STRING ){
  103709. z = pRight->u.zToken;
  103710. }
  103711. if( z ){
  103712. cnt = 0;
  103713. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  103714. cnt++;
  103715. }
  103716. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  103717. Expr *pPrefix;
  103718. *pisComplete = c==wc[0] && z[cnt+1]==0;
  103719. pPrefix = sqlite3Expr(db, TK_STRING, z);
  103720. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  103721. *ppPrefix = pPrefix;
  103722. if( op==TK_VARIABLE ){
  103723. Vdbe *v = pParse->pVdbe;
  103724. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  103725. if( *pisComplete && pRight->u.zToken[1] ){
  103726. /* If the rhs of the LIKE expression is a variable, and the current
  103727. ** value of the variable means there is no need to invoke the LIKE
  103728. ** function, then no OP_Variable will be added to the program.
  103729. ** This causes problems for the sqlite3_bind_parameter_name()
  103730. ** API. To workaround them, add a dummy OP_Variable here.
  103731. */
  103732. int r1 = sqlite3GetTempReg(pParse);
  103733. sqlite3ExprCodeTarget(pParse, pRight, r1);
  103734. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  103735. sqlite3ReleaseTempReg(pParse, r1);
  103736. }
  103737. }
  103738. }else{
  103739. z = 0;
  103740. }
  103741. }
  103742. sqlite3ValueFree(pVal);
  103743. return (z!=0);
  103744. }
  103745. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  103746. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103747. /*
  103748. ** Check to see if the given expression is of the form
  103749. **
  103750. ** column MATCH expr
  103751. **
  103752. ** If it is then return TRUE. If not, return FALSE.
  103753. */
  103754. static int isMatchOfColumn(
  103755. Expr *pExpr /* Test this expression */
  103756. ){
  103757. ExprList *pList;
  103758. if( pExpr->op!=TK_FUNCTION ){
  103759. return 0;
  103760. }
  103761. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  103762. return 0;
  103763. }
  103764. pList = pExpr->x.pList;
  103765. if( pList->nExpr!=2 ){
  103766. return 0;
  103767. }
  103768. if( pList->a[1].pExpr->op != TK_COLUMN ){
  103769. return 0;
  103770. }
  103771. return 1;
  103772. }
  103773. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  103774. /*
  103775. ** If the pBase expression originated in the ON or USING clause of
  103776. ** a join, then transfer the appropriate markings over to derived.
  103777. */
  103778. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  103779. if( pDerived ){
  103780. pDerived->flags |= pBase->flags & EP_FromJoin;
  103781. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  103782. }
  103783. }
  103784. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  103785. /*
  103786. ** Analyze a term that consists of two or more OR-connected
  103787. ** subterms. So in:
  103788. **
  103789. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  103790. ** ^^^^^^^^^^^^^^^^^^^^
  103791. **
  103792. ** This routine analyzes terms such as the middle term in the above example.
  103793. ** A WhereOrTerm object is computed and attached to the term under
  103794. ** analysis, regardless of the outcome of the analysis. Hence:
  103795. **
  103796. ** WhereTerm.wtFlags |= TERM_ORINFO
  103797. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  103798. **
  103799. ** The term being analyzed must have two or more of OR-connected subterms.
  103800. ** A single subterm might be a set of AND-connected sub-subterms.
  103801. ** Examples of terms under analysis:
  103802. **
  103803. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  103804. ** (B) x=expr1 OR expr2=x OR x=expr3
  103805. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  103806. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  103807. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  103808. **
  103809. ** CASE 1:
  103810. **
  103811. ** If all subterms are of the form T.C=expr for some single column of C and
  103812. ** a single table T (as shown in example B above) then create a new virtual
  103813. ** term that is an equivalent IN expression. In other words, if the term
  103814. ** being analyzed is:
  103815. **
  103816. ** x = expr1 OR expr2 = x OR x = expr3
  103817. **
  103818. ** then create a new virtual term like this:
  103819. **
  103820. ** x IN (expr1,expr2,expr3)
  103821. **
  103822. ** CASE 2:
  103823. **
  103824. ** If all subterms are indexable by a single table T, then set
  103825. **
  103826. ** WhereTerm.eOperator = WO_OR
  103827. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  103828. **
  103829. ** A subterm is "indexable" if it is of the form
  103830. ** "T.C <op> <expr>" where C is any column of table T and
  103831. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  103832. ** A subterm is also indexable if it is an AND of two or more
  103833. ** subsubterms at least one of which is indexable. Indexable AND
  103834. ** subterms have their eOperator set to WO_AND and they have
  103835. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  103836. **
  103837. ** From another point of view, "indexable" means that the subterm could
  103838. ** potentially be used with an index if an appropriate index exists.
  103839. ** This analysis does not consider whether or not the index exists; that
  103840. ** is decided elsewhere. This analysis only looks at whether subterms
  103841. ** appropriate for indexing exist.
  103842. **
  103843. ** All examples A through E above satisfy case 2. But if a term
  103844. ** also statisfies case 1 (such as B) we know that the optimizer will
  103845. ** always prefer case 1, so in that case we pretend that case 2 is not
  103846. ** satisfied.
  103847. **
  103848. ** It might be the case that multiple tables are indexable. For example,
  103849. ** (E) above is indexable on tables P, Q, and R.
  103850. **
  103851. ** Terms that satisfy case 2 are candidates for lookup by using
  103852. ** separate indices to find rowids for each subterm and composing
  103853. ** the union of all rowids using a RowSet object. This is similar
  103854. ** to "bitmap indices" in other database engines.
  103855. **
  103856. ** OTHERWISE:
  103857. **
  103858. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  103859. ** zero. This term is not useful for search.
  103860. */
  103861. static void exprAnalyzeOrTerm(
  103862. SrcList *pSrc, /* the FROM clause */
  103863. WhereClause *pWC, /* the complete WHERE clause */
  103864. int idxTerm /* Index of the OR-term to be analyzed */
  103865. ){
  103866. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  103867. Parse *pParse = pWInfo->pParse; /* Parser context */
  103868. sqlite3 *db = pParse->db; /* Database connection */
  103869. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  103870. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  103871. int i; /* Loop counters */
  103872. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  103873. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  103874. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  103875. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  103876. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  103877. /*
  103878. ** Break the OR clause into its separate subterms. The subterms are
  103879. ** stored in a WhereClause structure containing within the WhereOrInfo
  103880. ** object that is attached to the original OR clause term.
  103881. */
  103882. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  103883. assert( pExpr->op==TK_OR );
  103884. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  103885. if( pOrInfo==0 ) return;
  103886. pTerm->wtFlags |= TERM_ORINFO;
  103887. pOrWc = &pOrInfo->wc;
  103888. whereClauseInit(pOrWc, pWInfo);
  103889. whereSplit(pOrWc, pExpr, TK_OR);
  103890. exprAnalyzeAll(pSrc, pOrWc);
  103891. if( db->mallocFailed ) return;
  103892. assert( pOrWc->nTerm>=2 );
  103893. /*
  103894. ** Compute the set of tables that might satisfy cases 1 or 2.
  103895. */
  103896. indexable = ~(Bitmask)0;
  103897. chngToIN = ~(Bitmask)0;
  103898. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  103899. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  103900. WhereAndInfo *pAndInfo;
  103901. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  103902. chngToIN = 0;
  103903. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  103904. if( pAndInfo ){
  103905. WhereClause *pAndWC;
  103906. WhereTerm *pAndTerm;
  103907. int j;
  103908. Bitmask b = 0;
  103909. pOrTerm->u.pAndInfo = pAndInfo;
  103910. pOrTerm->wtFlags |= TERM_ANDINFO;
  103911. pOrTerm->eOperator = WO_AND;
  103912. pAndWC = &pAndInfo->wc;
  103913. whereClauseInit(pAndWC, pWC->pWInfo);
  103914. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  103915. exprAnalyzeAll(pSrc, pAndWC);
  103916. pAndWC->pOuter = pWC;
  103917. testcase( db->mallocFailed );
  103918. if( !db->mallocFailed ){
  103919. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  103920. assert( pAndTerm->pExpr );
  103921. if( allowedOp(pAndTerm->pExpr->op) ){
  103922. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  103923. }
  103924. }
  103925. }
  103926. indexable &= b;
  103927. }
  103928. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  103929. /* Skip this term for now. We revisit it when we process the
  103930. ** corresponding TERM_VIRTUAL term */
  103931. }else{
  103932. Bitmask b;
  103933. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  103934. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  103935. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  103936. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  103937. }
  103938. indexable &= b;
  103939. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  103940. chngToIN = 0;
  103941. }else{
  103942. chngToIN &= b;
  103943. }
  103944. }
  103945. }
  103946. /*
  103947. ** Record the set of tables that satisfy case 2. The set might be
  103948. ** empty.
  103949. */
  103950. pOrInfo->indexable = indexable;
  103951. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  103952. /*
  103953. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  103954. ** we have to do some additional checking to see if case 1 really
  103955. ** is satisfied.
  103956. **
  103957. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  103958. ** that there is no possibility of transforming the OR clause into an
  103959. ** IN operator because one or more terms in the OR clause contain
  103960. ** something other than == on a column in the single table. The 1-bit
  103961. ** case means that every term of the OR clause is of the form
  103962. ** "table.column=expr" for some single table. The one bit that is set
  103963. ** will correspond to the common table. We still need to check to make
  103964. ** sure the same column is used on all terms. The 2-bit case is when
  103965. ** the all terms are of the form "table1.column=table2.column". It
  103966. ** might be possible to form an IN operator with either table1.column
  103967. ** or table2.column as the LHS if either is common to every term of
  103968. ** the OR clause.
  103969. **
  103970. ** Note that terms of the form "table.column1=table.column2" (the
  103971. ** same table on both sizes of the ==) cannot be optimized.
  103972. */
  103973. if( chngToIN ){
  103974. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  103975. int iColumn = -1; /* Column index on lhs of IN operator */
  103976. int iCursor = -1; /* Table cursor common to all terms */
  103977. int j = 0; /* Loop counter */
  103978. /* Search for a table and column that appears on one side or the
  103979. ** other of the == operator in every subterm. That table and column
  103980. ** will be recorded in iCursor and iColumn. There might not be any
  103981. ** such table and column. Set okToChngToIN if an appropriate table
  103982. ** and column is found but leave okToChngToIN false if not found.
  103983. */
  103984. for(j=0; j<2 && !okToChngToIN; j++){
  103985. pOrTerm = pOrWc->a;
  103986. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  103987. assert( pOrTerm->eOperator & WO_EQ );
  103988. pOrTerm->wtFlags &= ~TERM_OR_OK;
  103989. if( pOrTerm->leftCursor==iCursor ){
  103990. /* This is the 2-bit case and we are on the second iteration and
  103991. ** current term is from the first iteration. So skip this term. */
  103992. assert( j==1 );
  103993. continue;
  103994. }
  103995. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  103996. /* This term must be of the form t1.a==t2.b where t2 is in the
  103997. ** chngToIN set but t1 is not. This term will be either preceeded
  103998. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  103999. ** and use its inversion. */
  104000. testcase( pOrTerm->wtFlags & TERM_COPIED );
  104001. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  104002. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  104003. continue;
  104004. }
  104005. iColumn = pOrTerm->u.leftColumn;
  104006. iCursor = pOrTerm->leftCursor;
  104007. break;
  104008. }
  104009. if( i<0 ){
  104010. /* No candidate table+column was found. This can only occur
  104011. ** on the second iteration */
  104012. assert( j==1 );
  104013. assert( IsPowerOfTwo(chngToIN) );
  104014. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  104015. break;
  104016. }
  104017. testcase( j==1 );
  104018. /* We have found a candidate table and column. Check to see if that
  104019. ** table and column is common to every term in the OR clause */
  104020. okToChngToIN = 1;
  104021. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  104022. assert( pOrTerm->eOperator & WO_EQ );
  104023. if( pOrTerm->leftCursor!=iCursor ){
  104024. pOrTerm->wtFlags &= ~TERM_OR_OK;
  104025. }else if( pOrTerm->u.leftColumn!=iColumn ){
  104026. okToChngToIN = 0;
  104027. }else{
  104028. int affLeft, affRight;
  104029. /* If the right-hand side is also a column, then the affinities
  104030. ** of both right and left sides must be such that no type
  104031. ** conversions are required on the right. (Ticket #2249)
  104032. */
  104033. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  104034. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  104035. if( affRight!=0 && affRight!=affLeft ){
  104036. okToChngToIN = 0;
  104037. }else{
  104038. pOrTerm->wtFlags |= TERM_OR_OK;
  104039. }
  104040. }
  104041. }
  104042. }
  104043. /* At this point, okToChngToIN is true if original pTerm satisfies
  104044. ** case 1. In that case, construct a new virtual term that is
  104045. ** pTerm converted into an IN operator.
  104046. */
  104047. if( okToChngToIN ){
  104048. Expr *pDup; /* A transient duplicate expression */
  104049. ExprList *pList = 0; /* The RHS of the IN operator */
  104050. Expr *pLeft = 0; /* The LHS of the IN operator */
  104051. Expr *pNew; /* The complete IN operator */
  104052. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  104053. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  104054. assert( pOrTerm->eOperator & WO_EQ );
  104055. assert( pOrTerm->leftCursor==iCursor );
  104056. assert( pOrTerm->u.leftColumn==iColumn );
  104057. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  104058. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  104059. pLeft = pOrTerm->pExpr->pLeft;
  104060. }
  104061. assert( pLeft!=0 );
  104062. pDup = sqlite3ExprDup(db, pLeft, 0);
  104063. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  104064. if( pNew ){
  104065. int idxNew;
  104066. transferJoinMarkings(pNew, pExpr);
  104067. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  104068. pNew->x.pList = pList;
  104069. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  104070. testcase( idxNew==0 );
  104071. exprAnalyze(pSrc, pWC, idxNew);
  104072. pTerm = &pWC->a[idxTerm];
  104073. pWC->a[idxNew].iParent = idxTerm;
  104074. pTerm->nChild = 1;
  104075. }else{
  104076. sqlite3ExprListDelete(db, pList);
  104077. }
  104078. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  104079. }
  104080. }
  104081. }
  104082. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  104083. /*
  104084. ** The input to this routine is an WhereTerm structure with only the
  104085. ** "pExpr" field filled in. The job of this routine is to analyze the
  104086. ** subexpression and populate all the other fields of the WhereTerm
  104087. ** structure.
  104088. **
  104089. ** If the expression is of the form "<expr> <op> X" it gets commuted
  104090. ** to the standard form of "X <op> <expr>".
  104091. **
  104092. ** If the expression is of the form "X <op> Y" where both X and Y are
  104093. ** columns, then the original expression is unchanged and a new virtual
  104094. ** term of the form "Y <op> X" is added to the WHERE clause and
  104095. ** analyzed separately. The original term is marked with TERM_COPIED
  104096. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  104097. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  104098. ** is a commuted copy of a prior term.) The original term has nChild=1
  104099. ** and the copy has idxParent set to the index of the original term.
  104100. */
  104101. static void exprAnalyze(
  104102. SrcList *pSrc, /* the FROM clause */
  104103. WhereClause *pWC, /* the WHERE clause */
  104104. int idxTerm /* Index of the term to be analyzed */
  104105. ){
  104106. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  104107. WhereTerm *pTerm; /* The term to be analyzed */
  104108. WhereMaskSet *pMaskSet; /* Set of table index masks */
  104109. Expr *pExpr; /* The expression to be analyzed */
  104110. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  104111. Bitmask prereqAll; /* Prerequesites of pExpr */
  104112. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  104113. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  104114. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  104115. int noCase = 0; /* LIKE/GLOB distinguishes case */
  104116. int op; /* Top-level operator. pExpr->op */
  104117. Parse *pParse = pWInfo->pParse; /* Parsing context */
  104118. sqlite3 *db = pParse->db; /* Database connection */
  104119. if( db->mallocFailed ){
  104120. return;
  104121. }
  104122. pTerm = &pWC->a[idxTerm];
  104123. pMaskSet = &pWInfo->sMaskSet;
  104124. pExpr = pTerm->pExpr;
  104125. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  104126. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  104127. op = pExpr->op;
  104128. if( op==TK_IN ){
  104129. assert( pExpr->pRight==0 );
  104130. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  104131. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  104132. }else{
  104133. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  104134. }
  104135. }else if( op==TK_ISNULL ){
  104136. pTerm->prereqRight = 0;
  104137. }else{
  104138. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  104139. }
  104140. prereqAll = exprTableUsage(pMaskSet, pExpr);
  104141. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  104142. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  104143. prereqAll |= x;
  104144. extraRight = x-1; /* ON clause terms may not be used with an index
  104145. ** on left table of a LEFT JOIN. Ticket #3015 */
  104146. }
  104147. pTerm->prereqAll = prereqAll;
  104148. pTerm->leftCursor = -1;
  104149. pTerm->iParent = -1;
  104150. pTerm->eOperator = 0;
  104151. if( allowedOp(op) ){
  104152. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  104153. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  104154. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  104155. if( pLeft->op==TK_COLUMN ){
  104156. pTerm->leftCursor = pLeft->iTable;
  104157. pTerm->u.leftColumn = pLeft->iColumn;
  104158. pTerm->eOperator = operatorMask(op) & opMask;
  104159. }
  104160. if( pRight && pRight->op==TK_COLUMN ){
  104161. WhereTerm *pNew;
  104162. Expr *pDup;
  104163. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  104164. if( pTerm->leftCursor>=0 ){
  104165. int idxNew;
  104166. pDup = sqlite3ExprDup(db, pExpr, 0);
  104167. if( db->mallocFailed ){
  104168. sqlite3ExprDelete(db, pDup);
  104169. return;
  104170. }
  104171. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  104172. if( idxNew==0 ) return;
  104173. pNew = &pWC->a[idxNew];
  104174. pNew->iParent = idxTerm;
  104175. pTerm = &pWC->a[idxTerm];
  104176. pTerm->nChild = 1;
  104177. pTerm->wtFlags |= TERM_COPIED;
  104178. if( pExpr->op==TK_EQ
  104179. && !ExprHasProperty(pExpr, EP_FromJoin)
  104180. && OptimizationEnabled(db, SQLITE_Transitive)
  104181. ){
  104182. pTerm->eOperator |= WO_EQUIV;
  104183. eExtraOp = WO_EQUIV;
  104184. }
  104185. }else{
  104186. pDup = pExpr;
  104187. pNew = pTerm;
  104188. }
  104189. exprCommute(pParse, pDup);
  104190. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  104191. pNew->leftCursor = pLeft->iTable;
  104192. pNew->u.leftColumn = pLeft->iColumn;
  104193. testcase( (prereqLeft | extraRight) != prereqLeft );
  104194. pNew->prereqRight = prereqLeft | extraRight;
  104195. pNew->prereqAll = prereqAll;
  104196. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  104197. }
  104198. }
  104199. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  104200. /* If a term is the BETWEEN operator, create two new virtual terms
  104201. ** that define the range that the BETWEEN implements. For example:
  104202. **
  104203. ** a BETWEEN b AND c
  104204. **
  104205. ** is converted into:
  104206. **
  104207. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  104208. **
  104209. ** The two new terms are added onto the end of the WhereClause object.
  104210. ** The new terms are "dynamic" and are children of the original BETWEEN
  104211. ** term. That means that if the BETWEEN term is coded, the children are
  104212. ** skipped. Or, if the children are satisfied by an index, the original
  104213. ** BETWEEN term is skipped.
  104214. */
  104215. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  104216. ExprList *pList = pExpr->x.pList;
  104217. int i;
  104218. static const u8 ops[] = {TK_GE, TK_LE};
  104219. assert( pList!=0 );
  104220. assert( pList->nExpr==2 );
  104221. for(i=0; i<2; i++){
  104222. Expr *pNewExpr;
  104223. int idxNew;
  104224. pNewExpr = sqlite3PExpr(pParse, ops[i],
  104225. sqlite3ExprDup(db, pExpr->pLeft, 0),
  104226. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  104227. transferJoinMarkings(pNewExpr, pExpr);
  104228. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  104229. testcase( idxNew==0 );
  104230. exprAnalyze(pSrc, pWC, idxNew);
  104231. pTerm = &pWC->a[idxTerm];
  104232. pWC->a[idxNew].iParent = idxTerm;
  104233. }
  104234. pTerm->nChild = 2;
  104235. }
  104236. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  104237. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  104238. /* Analyze a term that is composed of two or more subterms connected by
  104239. ** an OR operator.
  104240. */
  104241. else if( pExpr->op==TK_OR ){
  104242. assert( pWC->op==TK_AND );
  104243. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  104244. pTerm = &pWC->a[idxTerm];
  104245. }
  104246. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  104247. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  104248. /* Add constraints to reduce the search space on a LIKE or GLOB
  104249. ** operator.
  104250. **
  104251. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  104252. **
  104253. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  104254. **
  104255. ** The last character of the prefix "abc" is incremented to form the
  104256. ** termination condition "abd".
  104257. */
  104258. if( pWC->op==TK_AND
  104259. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  104260. ){
  104261. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  104262. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  104263. Expr *pNewExpr1;
  104264. Expr *pNewExpr2;
  104265. int idxNew1;
  104266. int idxNew2;
  104267. Token sCollSeqName; /* Name of collating sequence */
  104268. pLeft = pExpr->x.pList->a[1].pExpr;
  104269. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  104270. if( !db->mallocFailed ){
  104271. u8 c, *pC; /* Last character before the first wildcard */
  104272. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  104273. c = *pC;
  104274. if( noCase ){
  104275. /* The point is to increment the last character before the first
  104276. ** wildcard. But if we increment '@', that will push it into the
  104277. ** alphabetic range where case conversions will mess up the
  104278. ** inequality. To avoid this, make sure to also run the full
  104279. ** LIKE on all candidate expressions by clearing the isComplete flag
  104280. */
  104281. if( c=='A'-1 ) isComplete = 0;
  104282. c = sqlite3UpperToLower[c];
  104283. }
  104284. *pC = c + 1;
  104285. }
  104286. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  104287. sCollSeqName.n = 6;
  104288. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  104289. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  104290. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  104291. pStr1, 0);
  104292. transferJoinMarkings(pNewExpr1, pExpr);
  104293. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  104294. testcase( idxNew1==0 );
  104295. exprAnalyze(pSrc, pWC, idxNew1);
  104296. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  104297. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  104298. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  104299. pStr2, 0);
  104300. transferJoinMarkings(pNewExpr2, pExpr);
  104301. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  104302. testcase( idxNew2==0 );
  104303. exprAnalyze(pSrc, pWC, idxNew2);
  104304. pTerm = &pWC->a[idxTerm];
  104305. if( isComplete ){
  104306. pWC->a[idxNew1].iParent = idxTerm;
  104307. pWC->a[idxNew2].iParent = idxTerm;
  104308. pTerm->nChild = 2;
  104309. }
  104310. }
  104311. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  104312. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104313. /* Add a WO_MATCH auxiliary term to the constraint set if the
  104314. ** current expression is of the form: column MATCH expr.
  104315. ** This information is used by the xBestIndex methods of
  104316. ** virtual tables. The native query optimizer does not attempt
  104317. ** to do anything with MATCH functions.
  104318. */
  104319. if( isMatchOfColumn(pExpr) ){
  104320. int idxNew;
  104321. Expr *pRight, *pLeft;
  104322. WhereTerm *pNewTerm;
  104323. Bitmask prereqColumn, prereqExpr;
  104324. pRight = pExpr->x.pList->a[0].pExpr;
  104325. pLeft = pExpr->x.pList->a[1].pExpr;
  104326. prereqExpr = exprTableUsage(pMaskSet, pRight);
  104327. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  104328. if( (prereqExpr & prereqColumn)==0 ){
  104329. Expr *pNewExpr;
  104330. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  104331. 0, sqlite3ExprDup(db, pRight, 0), 0);
  104332. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  104333. testcase( idxNew==0 );
  104334. pNewTerm = &pWC->a[idxNew];
  104335. pNewTerm->prereqRight = prereqExpr;
  104336. pNewTerm->leftCursor = pLeft->iTable;
  104337. pNewTerm->u.leftColumn = pLeft->iColumn;
  104338. pNewTerm->eOperator = WO_MATCH;
  104339. pNewTerm->iParent = idxTerm;
  104340. pTerm = &pWC->a[idxTerm];
  104341. pTerm->nChild = 1;
  104342. pTerm->wtFlags |= TERM_COPIED;
  104343. pNewTerm->prereqAll = pTerm->prereqAll;
  104344. }
  104345. }
  104346. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104347. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104348. /* When sqlite_stat3 histogram data is available an operator of the
  104349. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  104350. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  104351. ** virtual term of that form.
  104352. **
  104353. ** Note that the virtual term must be tagged with TERM_VNULL. This
  104354. ** TERM_VNULL tag will suppress the not-null check at the beginning
  104355. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  104356. ** the start of the loop will prevent any results from being returned.
  104357. */
  104358. if( pExpr->op==TK_NOTNULL
  104359. && pExpr->pLeft->op==TK_COLUMN
  104360. && pExpr->pLeft->iColumn>=0
  104361. && OptimizationEnabled(db, SQLITE_Stat3)
  104362. ){
  104363. Expr *pNewExpr;
  104364. Expr *pLeft = pExpr->pLeft;
  104365. int idxNew;
  104366. WhereTerm *pNewTerm;
  104367. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  104368. sqlite3ExprDup(db, pLeft, 0),
  104369. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  104370. idxNew = whereClauseInsert(pWC, pNewExpr,
  104371. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  104372. if( idxNew ){
  104373. pNewTerm = &pWC->a[idxNew];
  104374. pNewTerm->prereqRight = 0;
  104375. pNewTerm->leftCursor = pLeft->iTable;
  104376. pNewTerm->u.leftColumn = pLeft->iColumn;
  104377. pNewTerm->eOperator = WO_GT;
  104378. pNewTerm->iParent = idxTerm;
  104379. pTerm = &pWC->a[idxTerm];
  104380. pTerm->nChild = 1;
  104381. pTerm->wtFlags |= TERM_COPIED;
  104382. pNewTerm->prereqAll = pTerm->prereqAll;
  104383. }
  104384. }
  104385. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  104386. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  104387. ** an index for tables to the left of the join.
  104388. */
  104389. pTerm->prereqRight |= extraRight;
  104390. }
  104391. /*
  104392. ** This function searches pList for a entry that matches the iCol-th column
  104393. ** of index pIdx.
  104394. **
  104395. ** If such an expression is found, its index in pList->a[] is returned. If
  104396. ** no expression is found, -1 is returned.
  104397. */
  104398. static int findIndexCol(
  104399. Parse *pParse, /* Parse context */
  104400. ExprList *pList, /* Expression list to search */
  104401. int iBase, /* Cursor for table associated with pIdx */
  104402. Index *pIdx, /* Index to match column of */
  104403. int iCol /* Column of index to match */
  104404. ){
  104405. int i;
  104406. const char *zColl = pIdx->azColl[iCol];
  104407. for(i=0; i<pList->nExpr; i++){
  104408. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  104409. if( p->op==TK_COLUMN
  104410. && p->iColumn==pIdx->aiColumn[iCol]
  104411. && p->iTable==iBase
  104412. ){
  104413. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  104414. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  104415. return i;
  104416. }
  104417. }
  104418. }
  104419. return -1;
  104420. }
  104421. /*
  104422. ** Return true if the DISTINCT expression-list passed as the third argument
  104423. ** is redundant.
  104424. **
  104425. ** A DISTINCT list is redundant if the database contains some subset of
  104426. ** columns that are unique and non-null.
  104427. */
  104428. static int isDistinctRedundant(
  104429. Parse *pParse, /* Parsing context */
  104430. SrcList *pTabList, /* The FROM clause */
  104431. WhereClause *pWC, /* The WHERE clause */
  104432. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  104433. ){
  104434. Table *pTab;
  104435. Index *pIdx;
  104436. int i;
  104437. int iBase;
  104438. /* If there is more than one table or sub-select in the FROM clause of
  104439. ** this query, then it will not be possible to show that the DISTINCT
  104440. ** clause is redundant. */
  104441. if( pTabList->nSrc!=1 ) return 0;
  104442. iBase = pTabList->a[0].iCursor;
  104443. pTab = pTabList->a[0].pTab;
  104444. /* If any of the expressions is an IPK column on table iBase, then return
  104445. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  104446. ** current SELECT is a correlated sub-query.
  104447. */
  104448. for(i=0; i<pDistinct->nExpr; i++){
  104449. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  104450. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  104451. }
  104452. /* Loop through all indices on the table, checking each to see if it makes
  104453. ** the DISTINCT qualifier redundant. It does so if:
  104454. **
  104455. ** 1. The index is itself UNIQUE, and
  104456. **
  104457. ** 2. All of the columns in the index are either part of the pDistinct
  104458. ** list, or else the WHERE clause contains a term of the form "col=X",
  104459. ** where X is a constant value. The collation sequences of the
  104460. ** comparison and select-list expressions must match those of the index.
  104461. **
  104462. ** 3. All of those index columns for which the WHERE clause does not
  104463. ** contain a "col=X" term are subject to a NOT NULL constraint.
  104464. */
  104465. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104466. if( pIdx->onError==OE_None ) continue;
  104467. for(i=0; i<pIdx->nColumn; i++){
  104468. int iCol = pIdx->aiColumn[i];
  104469. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  104470. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  104471. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  104472. break;
  104473. }
  104474. }
  104475. }
  104476. if( i==pIdx->nColumn ){
  104477. /* This index implies that the DISTINCT qualifier is redundant. */
  104478. return 1;
  104479. }
  104480. }
  104481. return 0;
  104482. }
  104483. /*
  104484. ** Estimate the logarithm of the input value to base 2.
  104485. */
  104486. static LogEst estLog(LogEst N){
  104487. LogEst x = sqlite3LogEst(N);
  104488. return x>33 ? x - 33 : 0;
  104489. }
  104490. /*
  104491. ** Two routines for printing the content of an sqlite3_index_info
  104492. ** structure. Used for testing and debugging only. If neither
  104493. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  104494. ** are no-ops.
  104495. */
  104496. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  104497. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  104498. int i;
  104499. if( !sqlite3WhereTrace ) return;
  104500. for(i=0; i<p->nConstraint; i++){
  104501. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  104502. i,
  104503. p->aConstraint[i].iColumn,
  104504. p->aConstraint[i].iTermOffset,
  104505. p->aConstraint[i].op,
  104506. p->aConstraint[i].usable);
  104507. }
  104508. for(i=0; i<p->nOrderBy; i++){
  104509. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  104510. i,
  104511. p->aOrderBy[i].iColumn,
  104512. p->aOrderBy[i].desc);
  104513. }
  104514. }
  104515. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  104516. int i;
  104517. if( !sqlite3WhereTrace ) return;
  104518. for(i=0; i<p->nConstraint; i++){
  104519. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  104520. i,
  104521. p->aConstraintUsage[i].argvIndex,
  104522. p->aConstraintUsage[i].omit);
  104523. }
  104524. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  104525. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  104526. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  104527. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  104528. }
  104529. #else
  104530. #define TRACE_IDX_INPUTS(A)
  104531. #define TRACE_IDX_OUTPUTS(A)
  104532. #endif
  104533. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  104534. /*
  104535. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  104536. ** could be used with an index to access pSrc, assuming an appropriate
  104537. ** index existed.
  104538. */
  104539. static int termCanDriveIndex(
  104540. WhereTerm *pTerm, /* WHERE clause term to check */
  104541. struct SrcList_item *pSrc, /* Table we are trying to access */
  104542. Bitmask notReady /* Tables in outer loops of the join */
  104543. ){
  104544. char aff;
  104545. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  104546. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  104547. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  104548. if( pTerm->u.leftColumn<0 ) return 0;
  104549. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  104550. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  104551. return 1;
  104552. }
  104553. #endif
  104554. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  104555. /*
  104556. ** Generate code to construct the Index object for an automatic index
  104557. ** and to set up the WhereLevel object pLevel so that the code generator
  104558. ** makes use of the automatic index.
  104559. */
  104560. static void constructAutomaticIndex(
  104561. Parse *pParse, /* The parsing context */
  104562. WhereClause *pWC, /* The WHERE clause */
  104563. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  104564. Bitmask notReady, /* Mask of cursors that are not available */
  104565. WhereLevel *pLevel /* Write new index here */
  104566. ){
  104567. int nColumn; /* Number of columns in the constructed index */
  104568. WhereTerm *pTerm; /* A single term of the WHERE clause */
  104569. WhereTerm *pWCEnd; /* End of pWC->a[] */
  104570. int nByte; /* Byte of memory needed for pIdx */
  104571. Index *pIdx; /* Object describing the transient index */
  104572. Vdbe *v; /* Prepared statement under construction */
  104573. int addrInit; /* Address of the initialization bypass jump */
  104574. Table *pTable; /* The table being indexed */
  104575. KeyInfo *pKeyinfo; /* Key information for the index */
  104576. int addrTop; /* Top of the index fill loop */
  104577. int regRecord; /* Register holding an index record */
  104578. int n; /* Column counter */
  104579. int i; /* Loop counter */
  104580. int mxBitCol; /* Maximum column in pSrc->colUsed */
  104581. CollSeq *pColl; /* Collating sequence to on a column */
  104582. WhereLoop *pLoop; /* The Loop object */
  104583. Bitmask idxCols; /* Bitmap of columns used for indexing */
  104584. Bitmask extraCols; /* Bitmap of additional columns */
  104585. u8 sentWarning = 0; /* True if a warnning has been issued */
  104586. /* Generate code to skip over the creation and initialization of the
  104587. ** transient index on 2nd and subsequent iterations of the loop. */
  104588. v = pParse->pVdbe;
  104589. assert( v!=0 );
  104590. addrInit = sqlite3CodeOnce(pParse);
  104591. /* Count the number of columns that will be added to the index
  104592. ** and used to match WHERE clause constraints */
  104593. nColumn = 0;
  104594. pTable = pSrc->pTab;
  104595. pWCEnd = &pWC->a[pWC->nTerm];
  104596. pLoop = pLevel->pWLoop;
  104597. idxCols = 0;
  104598. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  104599. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  104600. int iCol = pTerm->u.leftColumn;
  104601. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  104602. testcase( iCol==BMS );
  104603. testcase( iCol==BMS-1 );
  104604. if( !sentWarning ){
  104605. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  104606. "automatic index on %s(%s)", pTable->zName,
  104607. pTable->aCol[iCol].zName);
  104608. sentWarning = 1;
  104609. }
  104610. if( (idxCols & cMask)==0 ){
  104611. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  104612. pLoop->aLTerm[nColumn++] = pTerm;
  104613. idxCols |= cMask;
  104614. }
  104615. }
  104616. }
  104617. assert( nColumn>0 );
  104618. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  104619. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  104620. | WHERE_AUTO_INDEX;
  104621. /* Count the number of additional columns needed to create a
  104622. ** covering index. A "covering index" is an index that contains all
  104623. ** columns that are needed by the query. With a covering index, the
  104624. ** original table never needs to be accessed. Automatic indices must
  104625. ** be a covering index because the index will not be updated if the
  104626. ** original table changes and the index and table cannot both be used
  104627. ** if they go out of sync.
  104628. */
  104629. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  104630. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  104631. testcase( pTable->nCol==BMS-1 );
  104632. testcase( pTable->nCol==BMS-2 );
  104633. for(i=0; i<mxBitCol; i++){
  104634. if( extraCols & MASKBIT(i) ) nColumn++;
  104635. }
  104636. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  104637. nColumn += pTable->nCol - BMS + 1;
  104638. }
  104639. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  104640. /* Construct the Index object to describe this index */
  104641. nByte = sizeof(Index);
  104642. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  104643. nByte += nColumn*sizeof(char*); /* Index.azColl */
  104644. nByte += nColumn; /* Index.aSortOrder */
  104645. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  104646. if( pIdx==0 ) return;
  104647. pLoop->u.btree.pIndex = pIdx;
  104648. pIdx->azColl = (char**)&pIdx[1];
  104649. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  104650. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  104651. pIdx->zName = "auto-index";
  104652. pIdx->nColumn = nColumn;
  104653. pIdx->pTable = pTable;
  104654. n = 0;
  104655. idxCols = 0;
  104656. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  104657. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  104658. int iCol = pTerm->u.leftColumn;
  104659. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  104660. testcase( iCol==BMS-1 );
  104661. testcase( iCol==BMS );
  104662. if( (idxCols & cMask)==0 ){
  104663. Expr *pX = pTerm->pExpr;
  104664. idxCols |= cMask;
  104665. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  104666. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  104667. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  104668. n++;
  104669. }
  104670. }
  104671. }
  104672. assert( (u32)n==pLoop->u.btree.nEq );
  104673. /* Add additional columns needed to make the automatic index into
  104674. ** a covering index */
  104675. for(i=0; i<mxBitCol; i++){
  104676. if( extraCols & MASKBIT(i) ){
  104677. pIdx->aiColumn[n] = i;
  104678. pIdx->azColl[n] = "BINARY";
  104679. n++;
  104680. }
  104681. }
  104682. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  104683. for(i=BMS-1; i<pTable->nCol; i++){
  104684. pIdx->aiColumn[n] = i;
  104685. pIdx->azColl[n] = "BINARY";
  104686. n++;
  104687. }
  104688. }
  104689. assert( n==nColumn );
  104690. /* Create the automatic index */
  104691. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  104692. assert( pLevel->iIdxCur>=0 );
  104693. pLevel->iIdxCur = pParse->nTab++;
  104694. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  104695. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  104696. VdbeComment((v, "for %s", pTable->zName));
  104697. /* Fill the automatic index with content */
  104698. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  104699. regRecord = sqlite3GetTempReg(pParse);
  104700. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  104701. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  104702. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  104703. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  104704. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  104705. sqlite3VdbeJumpHere(v, addrTop);
  104706. sqlite3ReleaseTempReg(pParse, regRecord);
  104707. /* Jump here when skipping the initialization */
  104708. sqlite3VdbeJumpHere(v, addrInit);
  104709. }
  104710. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  104711. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104712. /*
  104713. ** Allocate and populate an sqlite3_index_info structure. It is the
  104714. ** responsibility of the caller to eventually release the structure
  104715. ** by passing the pointer returned by this function to sqlite3_free().
  104716. */
  104717. static sqlite3_index_info *allocateIndexInfo(
  104718. Parse *pParse,
  104719. WhereClause *pWC,
  104720. struct SrcList_item *pSrc,
  104721. ExprList *pOrderBy
  104722. ){
  104723. int i, j;
  104724. int nTerm;
  104725. struct sqlite3_index_constraint *pIdxCons;
  104726. struct sqlite3_index_orderby *pIdxOrderBy;
  104727. struct sqlite3_index_constraint_usage *pUsage;
  104728. WhereTerm *pTerm;
  104729. int nOrderBy;
  104730. sqlite3_index_info *pIdxInfo;
  104731. /* Count the number of possible WHERE clause constraints referring
  104732. ** to this virtual table */
  104733. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  104734. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  104735. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  104736. testcase( pTerm->eOperator & WO_IN );
  104737. testcase( pTerm->eOperator & WO_ISNULL );
  104738. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  104739. if( pTerm->wtFlags & TERM_VNULL ) continue;
  104740. nTerm++;
  104741. }
  104742. /* If the ORDER BY clause contains only columns in the current
  104743. ** virtual table then allocate space for the aOrderBy part of
  104744. ** the sqlite3_index_info structure.
  104745. */
  104746. nOrderBy = 0;
  104747. if( pOrderBy ){
  104748. int n = pOrderBy->nExpr;
  104749. for(i=0; i<n; i++){
  104750. Expr *pExpr = pOrderBy->a[i].pExpr;
  104751. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  104752. }
  104753. if( i==n){
  104754. nOrderBy = n;
  104755. }
  104756. }
  104757. /* Allocate the sqlite3_index_info structure
  104758. */
  104759. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  104760. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  104761. + sizeof(*pIdxOrderBy)*nOrderBy );
  104762. if( pIdxInfo==0 ){
  104763. sqlite3ErrorMsg(pParse, "out of memory");
  104764. return 0;
  104765. }
  104766. /* Initialize the structure. The sqlite3_index_info structure contains
  104767. ** many fields that are declared "const" to prevent xBestIndex from
  104768. ** changing them. We have to do some funky casting in order to
  104769. ** initialize those fields.
  104770. */
  104771. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  104772. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  104773. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  104774. *(int*)&pIdxInfo->nConstraint = nTerm;
  104775. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  104776. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  104777. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  104778. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  104779. pUsage;
  104780. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  104781. u8 op;
  104782. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  104783. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  104784. testcase( pTerm->eOperator & WO_IN );
  104785. testcase( pTerm->eOperator & WO_ISNULL );
  104786. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  104787. if( pTerm->wtFlags & TERM_VNULL ) continue;
  104788. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  104789. pIdxCons[j].iTermOffset = i;
  104790. op = (u8)pTerm->eOperator & WO_ALL;
  104791. if( op==WO_IN ) op = WO_EQ;
  104792. pIdxCons[j].op = op;
  104793. /* The direct assignment in the previous line is possible only because
  104794. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  104795. ** following asserts verify this fact. */
  104796. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  104797. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  104798. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  104799. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  104800. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  104801. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  104802. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  104803. j++;
  104804. }
  104805. for(i=0; i<nOrderBy; i++){
  104806. Expr *pExpr = pOrderBy->a[i].pExpr;
  104807. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  104808. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  104809. }
  104810. return pIdxInfo;
  104811. }
  104812. /*
  104813. ** The table object reference passed as the second argument to this function
  104814. ** must represent a virtual table. This function invokes the xBestIndex()
  104815. ** method of the virtual table with the sqlite3_index_info object that
  104816. ** comes in as the 3rd argument to this function.
  104817. **
  104818. ** If an error occurs, pParse is populated with an error message and a
  104819. ** non-zero value is returned. Otherwise, 0 is returned and the output
  104820. ** part of the sqlite3_index_info structure is left populated.
  104821. **
  104822. ** Whether or not an error is returned, it is the responsibility of the
  104823. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  104824. ** that this is required.
  104825. */
  104826. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  104827. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  104828. int i;
  104829. int rc;
  104830. TRACE_IDX_INPUTS(p);
  104831. rc = pVtab->pModule->xBestIndex(pVtab, p);
  104832. TRACE_IDX_OUTPUTS(p);
  104833. if( rc!=SQLITE_OK ){
  104834. if( rc==SQLITE_NOMEM ){
  104835. pParse->db->mallocFailed = 1;
  104836. }else if( !pVtab->zErrMsg ){
  104837. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  104838. }else{
  104839. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  104840. }
  104841. }
  104842. sqlite3_free(pVtab->zErrMsg);
  104843. pVtab->zErrMsg = 0;
  104844. for(i=0; i<p->nConstraint; i++){
  104845. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  104846. sqlite3ErrorMsg(pParse,
  104847. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  104848. }
  104849. }
  104850. return pParse->nErr;
  104851. }
  104852. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  104853. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104854. /*
  104855. ** Estimate the location of a particular key among all keys in an
  104856. ** index. Store the results in aStat as follows:
  104857. **
  104858. ** aStat[0] Est. number of rows less than pVal
  104859. ** aStat[1] Est. number of rows equal to pVal
  104860. **
  104861. ** Return SQLITE_OK on success.
  104862. */
  104863. static void whereKeyStats(
  104864. Parse *pParse, /* Database connection */
  104865. Index *pIdx, /* Index to consider domain of */
  104866. UnpackedRecord *pRec, /* Vector of values to consider */
  104867. int roundUp, /* Round up if true. Round down if false */
  104868. tRowcnt *aStat /* OUT: stats written here */
  104869. ){
  104870. IndexSample *aSample = pIdx->aSample;
  104871. int iCol; /* Index of required stats in anEq[] etc. */
  104872. int iMin = 0; /* Smallest sample not yet tested */
  104873. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  104874. int iTest; /* Next sample to test */
  104875. int res; /* Result of comparison operation */
  104876. #ifndef SQLITE_DEBUG
  104877. UNUSED_PARAMETER( pParse );
  104878. #endif
  104879. assert( pRec!=0 || pParse->db->mallocFailed );
  104880. if( pRec==0 ) return;
  104881. iCol = pRec->nField - 1;
  104882. assert( pIdx->nSample>0 );
  104883. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  104884. do{
  104885. iTest = (iMin+i)/2;
  104886. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  104887. if( res<0 ){
  104888. iMin = iTest+1;
  104889. }else{
  104890. i = iTest;
  104891. }
  104892. }while( res && iMin<i );
  104893. #ifdef SQLITE_DEBUG
  104894. /* The following assert statements check that the binary search code
  104895. ** above found the right answer. This block serves no purpose other
  104896. ** than to invoke the asserts. */
  104897. if( res==0 ){
  104898. /* If (res==0) is true, then sample $i must be equal to pRec */
  104899. assert( i<pIdx->nSample );
  104900. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  104901. || pParse->db->mallocFailed );
  104902. }else{
  104903. /* Otherwise, pRec must be smaller than sample $i and larger than
  104904. ** sample ($i-1). */
  104905. assert( i==pIdx->nSample
  104906. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  104907. || pParse->db->mallocFailed );
  104908. assert( i==0
  104909. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  104910. || pParse->db->mallocFailed );
  104911. }
  104912. #endif /* ifdef SQLITE_DEBUG */
  104913. /* At this point, aSample[i] is the first sample that is greater than
  104914. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  104915. ** than pVal. If aSample[i]==pVal, then res==0.
  104916. */
  104917. if( res==0 ){
  104918. aStat[0] = aSample[i].anLt[iCol];
  104919. aStat[1] = aSample[i].anEq[iCol];
  104920. }else{
  104921. tRowcnt iLower, iUpper, iGap;
  104922. if( i==0 ){
  104923. iLower = 0;
  104924. iUpper = aSample[0].anLt[iCol];
  104925. }else{
  104926. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  104927. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  104928. }
  104929. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  104930. if( iLower>=iUpper ){
  104931. iGap = 0;
  104932. }else{
  104933. iGap = iUpper - iLower;
  104934. }
  104935. if( roundUp ){
  104936. iGap = (iGap*2)/3;
  104937. }else{
  104938. iGap = iGap/3;
  104939. }
  104940. aStat[0] = iLower + iGap;
  104941. }
  104942. }
  104943. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  104944. /*
  104945. ** This function is used to estimate the number of rows that will be visited
  104946. ** by scanning an index for a range of values. The range may have an upper
  104947. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  104948. ** and lower bounds are represented by pLower and pUpper respectively. For
  104949. ** example, assuming that index p is on t1(a):
  104950. **
  104951. ** ... FROM t1 WHERE a > ? AND a < ? ...
  104952. ** |_____| |_____|
  104953. ** | |
  104954. ** pLower pUpper
  104955. **
  104956. ** If either of the upper or lower bound is not present, then NULL is passed in
  104957. ** place of the corresponding WhereTerm.
  104958. **
  104959. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  104960. ** column subject to the range constraint. Or, equivalently, the number of
  104961. ** equality constraints optimized by the proposed index scan. For example,
  104962. ** assuming index p is on t1(a, b), and the SQL query is:
  104963. **
  104964. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  104965. **
  104966. ** then nEq is set to 1 (as the range restricted column, b, is the second
  104967. ** left-most column of the index). Or, if the query is:
  104968. **
  104969. ** ... FROM t1 WHERE a > ? AND a < ? ...
  104970. **
  104971. ** then nEq is set to 0.
  104972. **
  104973. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  104974. ** number of rows that the index scan is expected to visit without
  104975. ** considering the range constraints. If nEq is 0, this is the number of
  104976. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  104977. ** to account for the range contraints pLower and pUpper.
  104978. **
  104979. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  104980. ** used, each range inequality reduces the search space by a factor of 4.
  104981. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  104982. ** rows visited by a factor of 16.
  104983. */
  104984. static int whereRangeScanEst(
  104985. Parse *pParse, /* Parsing & code generating context */
  104986. WhereLoopBuilder *pBuilder,
  104987. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  104988. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  104989. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  104990. ){
  104991. int rc = SQLITE_OK;
  104992. int nOut = pLoop->nOut;
  104993. LogEst nNew;
  104994. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104995. Index *p = pLoop->u.btree.pIndex;
  104996. int nEq = pLoop->u.btree.nEq;
  104997. if( p->nSample>0
  104998. && nEq==pBuilder->nRecValid
  104999. && nEq<p->nSampleCol
  105000. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  105001. ){
  105002. UnpackedRecord *pRec = pBuilder->pRec;
  105003. tRowcnt a[2];
  105004. u8 aff;
  105005. /* Variable iLower will be set to the estimate of the number of rows in
  105006. ** the index that are less than the lower bound of the range query. The
  105007. ** lower bound being the concatenation of $P and $L, where $P is the
  105008. ** key-prefix formed by the nEq values matched against the nEq left-most
  105009. ** columns of the index, and $L is the value in pLower.
  105010. **
  105011. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  105012. ** is not a simple variable or literal value), the lower bound of the
  105013. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  105014. ** if $L is available, whereKeyStats() is called for both ($P) and
  105015. ** ($P:$L) and the larger of the two returned values used.
  105016. **
  105017. ** Similarly, iUpper is to be set to the estimate of the number of rows
  105018. ** less than the upper bound of the range query. Where the upper bound
  105019. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  105020. ** of iUpper are requested of whereKeyStats() and the smaller used.
  105021. */
  105022. tRowcnt iLower;
  105023. tRowcnt iUpper;
  105024. if( nEq==p->nColumn ){
  105025. aff = SQLITE_AFF_INTEGER;
  105026. }else{
  105027. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  105028. }
  105029. /* Determine iLower and iUpper using ($P) only. */
  105030. if( nEq==0 ){
  105031. iLower = 0;
  105032. iUpper = p->aiRowEst[0];
  105033. }else{
  105034. /* Note: this call could be optimized away - since the same values must
  105035. ** have been requested when testing key $P in whereEqualScanEst(). */
  105036. whereKeyStats(pParse, p, pRec, 0, a);
  105037. iLower = a[0];
  105038. iUpper = a[0] + a[1];
  105039. }
  105040. /* If possible, improve on the iLower estimate using ($P:$L). */
  105041. if( pLower ){
  105042. int bOk; /* True if value is extracted from pExpr */
  105043. Expr *pExpr = pLower->pExpr->pRight;
  105044. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  105045. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  105046. if( rc==SQLITE_OK && bOk ){
  105047. tRowcnt iNew;
  105048. whereKeyStats(pParse, p, pRec, 0, a);
  105049. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  105050. if( iNew>iLower ) iLower = iNew;
  105051. nOut--;
  105052. }
  105053. }
  105054. /* If possible, improve on the iUpper estimate using ($P:$U). */
  105055. if( pUpper ){
  105056. int bOk; /* True if value is extracted from pExpr */
  105057. Expr *pExpr = pUpper->pExpr->pRight;
  105058. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  105059. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  105060. if( rc==SQLITE_OK && bOk ){
  105061. tRowcnt iNew;
  105062. whereKeyStats(pParse, p, pRec, 1, a);
  105063. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  105064. if( iNew<iUpper ) iUpper = iNew;
  105065. nOut--;
  105066. }
  105067. }
  105068. pBuilder->pRec = pRec;
  105069. if( rc==SQLITE_OK ){
  105070. if( iUpper>iLower ){
  105071. nNew = sqlite3LogEst(iUpper - iLower);
  105072. }else{
  105073. nNew = 10; assert( 10==sqlite3LogEst(2) );
  105074. }
  105075. if( nNew<nOut ){
  105076. nOut = nNew;
  105077. }
  105078. pLoop->nOut = (LogEst)nOut;
  105079. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  105080. (u32)iLower, (u32)iUpper, nOut));
  105081. return SQLITE_OK;
  105082. }
  105083. }
  105084. #else
  105085. UNUSED_PARAMETER(pParse);
  105086. UNUSED_PARAMETER(pBuilder);
  105087. #endif
  105088. assert( pLower || pUpper );
  105089. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  105090. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  105091. nNew = nOut;
  105092. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  105093. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  105094. nOut--;
  105095. }
  105096. if( pUpper ){
  105097. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  105098. nOut--;
  105099. }
  105100. if( nNew<10 ) nNew = 10;
  105101. if( nNew<nOut ) nOut = nNew;
  105102. pLoop->nOut = (LogEst)nOut;
  105103. return rc;
  105104. }
  105105. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  105106. /*
  105107. ** Estimate the number of rows that will be returned based on
  105108. ** an equality constraint x=VALUE and where that VALUE occurs in
  105109. ** the histogram data. This only works when x is the left-most
  105110. ** column of an index and sqlite_stat3 histogram data is available
  105111. ** for that index. When pExpr==NULL that means the constraint is
  105112. ** "x IS NULL" instead of "x=VALUE".
  105113. **
  105114. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  105115. ** If unable to make an estimate, leave *pnRow unchanged and return
  105116. ** non-zero.
  105117. **
  105118. ** This routine can fail if it is unable to load a collating sequence
  105119. ** required for string comparison, or if unable to allocate memory
  105120. ** for a UTF conversion required for comparison. The error is stored
  105121. ** in the pParse structure.
  105122. */
  105123. static int whereEqualScanEst(
  105124. Parse *pParse, /* Parsing & code generating context */
  105125. WhereLoopBuilder *pBuilder,
  105126. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  105127. tRowcnt *pnRow /* Write the revised row estimate here */
  105128. ){
  105129. Index *p = pBuilder->pNew->u.btree.pIndex;
  105130. int nEq = pBuilder->pNew->u.btree.nEq;
  105131. UnpackedRecord *pRec = pBuilder->pRec;
  105132. u8 aff; /* Column affinity */
  105133. int rc; /* Subfunction return code */
  105134. tRowcnt a[2]; /* Statistics */
  105135. int bOk;
  105136. assert( nEq>=1 );
  105137. assert( nEq<=(p->nColumn+1) );
  105138. assert( p->aSample!=0 );
  105139. assert( p->nSample>0 );
  105140. assert( pBuilder->nRecValid<nEq );
  105141. /* If values are not available for all fields of the index to the left
  105142. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  105143. if( pBuilder->nRecValid<(nEq-1) ){
  105144. return SQLITE_NOTFOUND;
  105145. }
  105146. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  105147. ** below would return the same value. */
  105148. if( nEq>p->nColumn ){
  105149. *pnRow = 1;
  105150. return SQLITE_OK;
  105151. }
  105152. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  105153. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  105154. pBuilder->pRec = pRec;
  105155. if( rc!=SQLITE_OK ) return rc;
  105156. if( bOk==0 ) return SQLITE_NOTFOUND;
  105157. pBuilder->nRecValid = nEq;
  105158. whereKeyStats(pParse, p, pRec, 0, a);
  105159. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  105160. *pnRow = a[1];
  105161. return rc;
  105162. }
  105163. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  105164. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  105165. /*
  105166. ** Estimate the number of rows that will be returned based on
  105167. ** an IN constraint where the right-hand side of the IN operator
  105168. ** is a list of values. Example:
  105169. **
  105170. ** WHERE x IN (1,2,3,4)
  105171. **
  105172. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  105173. ** If unable to make an estimate, leave *pnRow unchanged and return
  105174. ** non-zero.
  105175. **
  105176. ** This routine can fail if it is unable to load a collating sequence
  105177. ** required for string comparison, or if unable to allocate memory
  105178. ** for a UTF conversion required for comparison. The error is stored
  105179. ** in the pParse structure.
  105180. */
  105181. static int whereInScanEst(
  105182. Parse *pParse, /* Parsing & code generating context */
  105183. WhereLoopBuilder *pBuilder,
  105184. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  105185. tRowcnt *pnRow /* Write the revised row estimate here */
  105186. ){
  105187. Index *p = pBuilder->pNew->u.btree.pIndex;
  105188. int nRecValid = pBuilder->nRecValid;
  105189. int rc = SQLITE_OK; /* Subfunction return code */
  105190. tRowcnt nEst; /* Number of rows for a single term */
  105191. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  105192. int i; /* Loop counter */
  105193. assert( p->aSample!=0 );
  105194. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  105195. nEst = p->aiRowEst[0];
  105196. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  105197. nRowEst += nEst;
  105198. pBuilder->nRecValid = nRecValid;
  105199. }
  105200. if( rc==SQLITE_OK ){
  105201. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  105202. *pnRow = nRowEst;
  105203. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  105204. }
  105205. assert( pBuilder->nRecValid==nRecValid );
  105206. return rc;
  105207. }
  105208. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  105209. /*
  105210. ** Disable a term in the WHERE clause. Except, do not disable the term
  105211. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  105212. ** or USING clause of that join.
  105213. **
  105214. ** Consider the term t2.z='ok' in the following queries:
  105215. **
  105216. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  105217. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  105218. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  105219. **
  105220. ** The t2.z='ok' is disabled in the in (2) because it originates
  105221. ** in the ON clause. The term is disabled in (3) because it is not part
  105222. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  105223. **
  105224. ** Disabling a term causes that term to not be tested in the inner loop
  105225. ** of the join. Disabling is an optimization. When terms are satisfied
  105226. ** by indices, we disable them to prevent redundant tests in the inner
  105227. ** loop. We would get the correct results if nothing were ever disabled,
  105228. ** but joins might run a little slower. The trick is to disable as much
  105229. ** as we can without disabling too much. If we disabled in (1), we'd get
  105230. ** the wrong answer. See ticket #813.
  105231. */
  105232. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  105233. if( pTerm
  105234. && (pTerm->wtFlags & TERM_CODED)==0
  105235. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  105236. && (pLevel->notReady & pTerm->prereqAll)==0
  105237. ){
  105238. pTerm->wtFlags |= TERM_CODED;
  105239. if( pTerm->iParent>=0 ){
  105240. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  105241. if( (--pOther->nChild)==0 ){
  105242. disableTerm(pLevel, pOther);
  105243. }
  105244. }
  105245. }
  105246. }
  105247. /*
  105248. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  105249. ** to the n registers starting at base.
  105250. **
  105251. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  105252. ** beginning and end of zAff are ignored. If all entries in zAff are
  105253. ** SQLITE_AFF_NONE, then no code gets generated.
  105254. **
  105255. ** This routine makes its own copy of zAff so that the caller is free
  105256. ** to modify zAff after this routine returns.
  105257. */
  105258. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  105259. Vdbe *v = pParse->pVdbe;
  105260. if( zAff==0 ){
  105261. assert( pParse->db->mallocFailed );
  105262. return;
  105263. }
  105264. assert( v!=0 );
  105265. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  105266. ** and end of the affinity string.
  105267. */
  105268. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  105269. n--;
  105270. base++;
  105271. zAff++;
  105272. }
  105273. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  105274. n--;
  105275. }
  105276. /* Code the OP_Affinity opcode if there is anything left to do. */
  105277. if( n>0 ){
  105278. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  105279. sqlite3VdbeChangeP4(v, -1, zAff, n);
  105280. sqlite3ExprCacheAffinityChange(pParse, base, n);
  105281. }
  105282. }
  105283. /*
  105284. ** Generate code for a single equality term of the WHERE clause. An equality
  105285. ** term can be either X=expr or X IN (...). pTerm is the term to be
  105286. ** coded.
  105287. **
  105288. ** The current value for the constraint is left in register iReg.
  105289. **
  105290. ** For a constraint of the form X=expr, the expression is evaluated and its
  105291. ** result is left on the stack. For constraints of the form X IN (...)
  105292. ** this routine sets up a loop that will iterate over all values of X.
  105293. */
  105294. static int codeEqualityTerm(
  105295. Parse *pParse, /* The parsing context */
  105296. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  105297. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  105298. int iEq, /* Index of the equality term within this level */
  105299. int bRev, /* True for reverse-order IN operations */
  105300. int iTarget /* Attempt to leave results in this register */
  105301. ){
  105302. Expr *pX = pTerm->pExpr;
  105303. Vdbe *v = pParse->pVdbe;
  105304. int iReg; /* Register holding results */
  105305. assert( iTarget>0 );
  105306. if( pX->op==TK_EQ ){
  105307. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  105308. }else if( pX->op==TK_ISNULL ){
  105309. iReg = iTarget;
  105310. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  105311. #ifndef SQLITE_OMIT_SUBQUERY
  105312. }else{
  105313. int eType;
  105314. int iTab;
  105315. struct InLoop *pIn;
  105316. WhereLoop *pLoop = pLevel->pWLoop;
  105317. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  105318. && pLoop->u.btree.pIndex!=0
  105319. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  105320. ){
  105321. testcase( iEq==0 );
  105322. testcase( bRev );
  105323. bRev = !bRev;
  105324. }
  105325. assert( pX->op==TK_IN );
  105326. iReg = iTarget;
  105327. eType = sqlite3FindInIndex(pParse, pX, 0);
  105328. if( eType==IN_INDEX_INDEX_DESC ){
  105329. testcase( bRev );
  105330. bRev = !bRev;
  105331. }
  105332. iTab = pX->iTable;
  105333. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  105334. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  105335. pLoop->wsFlags |= WHERE_IN_ABLE;
  105336. if( pLevel->u.in.nIn==0 ){
  105337. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  105338. }
  105339. pLevel->u.in.nIn++;
  105340. pLevel->u.in.aInLoop =
  105341. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  105342. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  105343. pIn = pLevel->u.in.aInLoop;
  105344. if( pIn ){
  105345. pIn += pLevel->u.in.nIn - 1;
  105346. pIn->iCur = iTab;
  105347. if( eType==IN_INDEX_ROWID ){
  105348. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  105349. }else{
  105350. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  105351. }
  105352. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  105353. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  105354. }else{
  105355. pLevel->u.in.nIn = 0;
  105356. }
  105357. #endif
  105358. }
  105359. disableTerm(pLevel, pTerm);
  105360. return iReg;
  105361. }
  105362. /*
  105363. ** Generate code that will evaluate all == and IN constraints for an
  105364. ** index.
  105365. **
  105366. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  105367. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  105368. ** The index has as many as three equality constraints, but in this
  105369. ** example, the third "c" value is an inequality. So only two
  105370. ** constraints are coded. This routine will generate code to evaluate
  105371. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  105372. ** in consecutive registers and the index of the first register is returned.
  105373. **
  105374. ** In the example above nEq==2. But this subroutine works for any value
  105375. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  105376. ** The only thing it does is allocate the pLevel->iMem memory cell and
  105377. ** compute the affinity string.
  105378. **
  105379. ** This routine always allocates at least one memory cell and returns
  105380. ** the index of that memory cell. The code that
  105381. ** calls this routine will use that memory cell to store the termination
  105382. ** key value of the loop. If one or more IN operators appear, then
  105383. ** this routine allocates an additional nEq memory cells for internal
  105384. ** use.
  105385. **
  105386. ** Before returning, *pzAff is set to point to a buffer containing a
  105387. ** copy of the column affinity string of the index allocated using
  105388. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  105389. ** with equality constraints that use NONE affinity are set to
  105390. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  105391. **
  105392. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  105393. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  105394. **
  105395. ** In the example above, the index on t1(a) has TEXT affinity. But since
  105396. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  105397. ** no conversion should be attempted before using a t2.b value as part of
  105398. ** a key to search the index. Hence the first byte in the returned affinity
  105399. ** string in this example would be set to SQLITE_AFF_NONE.
  105400. */
  105401. static int codeAllEqualityTerms(
  105402. Parse *pParse, /* Parsing context */
  105403. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  105404. int bRev, /* Reverse the order of IN operators */
  105405. int nExtraReg, /* Number of extra registers to allocate */
  105406. char **pzAff /* OUT: Set to point to affinity string */
  105407. ){
  105408. int nEq; /* The number of == or IN constraints to code */
  105409. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  105410. Index *pIdx; /* The index being used for this loop */
  105411. WhereTerm *pTerm; /* A single constraint term */
  105412. WhereLoop *pLoop; /* The WhereLoop object */
  105413. int j; /* Loop counter */
  105414. int regBase; /* Base register */
  105415. int nReg; /* Number of registers to allocate */
  105416. char *zAff; /* Affinity string to return */
  105417. /* This module is only called on query plans that use an index. */
  105418. pLoop = pLevel->pWLoop;
  105419. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  105420. nEq = pLoop->u.btree.nEq;
  105421. pIdx = pLoop->u.btree.pIndex;
  105422. assert( pIdx!=0 );
  105423. /* Figure out how many memory cells we will need then allocate them.
  105424. */
  105425. regBase = pParse->nMem + 1;
  105426. nReg = pLoop->u.btree.nEq + nExtraReg;
  105427. pParse->nMem += nReg;
  105428. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  105429. if( !zAff ){
  105430. pParse->db->mallocFailed = 1;
  105431. }
  105432. /* Evaluate the equality constraints
  105433. */
  105434. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  105435. for(j=0; j<nEq; j++){
  105436. int r1;
  105437. pTerm = pLoop->aLTerm[j];
  105438. assert( pTerm!=0 );
  105439. /* The following true for indices with redundant columns.
  105440. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  105441. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  105442. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  105443. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  105444. if( r1!=regBase+j ){
  105445. if( nReg==1 ){
  105446. sqlite3ReleaseTempReg(pParse, regBase);
  105447. regBase = r1;
  105448. }else{
  105449. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  105450. }
  105451. }
  105452. testcase( pTerm->eOperator & WO_ISNULL );
  105453. testcase( pTerm->eOperator & WO_IN );
  105454. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  105455. Expr *pRight = pTerm->pExpr->pRight;
  105456. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  105457. if( zAff ){
  105458. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  105459. zAff[j] = SQLITE_AFF_NONE;
  105460. }
  105461. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  105462. zAff[j] = SQLITE_AFF_NONE;
  105463. }
  105464. }
  105465. }
  105466. }
  105467. *pzAff = zAff;
  105468. return regBase;
  105469. }
  105470. #ifndef SQLITE_OMIT_EXPLAIN
  105471. /*
  105472. ** This routine is a helper for explainIndexRange() below
  105473. **
  105474. ** pStr holds the text of an expression that we are building up one term
  105475. ** at a time. This routine adds a new term to the end of the expression.
  105476. ** Terms are separated by AND so add the "AND" text for second and subsequent
  105477. ** terms only.
  105478. */
  105479. static void explainAppendTerm(
  105480. StrAccum *pStr, /* The text expression being built */
  105481. int iTerm, /* Index of this term. First is zero */
  105482. const char *zColumn, /* Name of the column */
  105483. const char *zOp /* Name of the operator */
  105484. ){
  105485. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  105486. sqlite3StrAccumAppend(pStr, zColumn, -1);
  105487. sqlite3StrAccumAppend(pStr, zOp, 1);
  105488. sqlite3StrAccumAppend(pStr, "?", 1);
  105489. }
  105490. /*
  105491. ** Argument pLevel describes a strategy for scanning table pTab. This
  105492. ** function returns a pointer to a string buffer containing a description
  105493. ** of the subset of table rows scanned by the strategy in the form of an
  105494. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  105495. **
  105496. ** For example, if the query:
  105497. **
  105498. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  105499. **
  105500. ** is run and there is an index on (a, b), then this function returns a
  105501. ** string similar to:
  105502. **
  105503. ** "a=? AND b>?"
  105504. **
  105505. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  105506. ** It is the responsibility of the caller to free the buffer when it is
  105507. ** no longer required.
  105508. */
  105509. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  105510. Index *pIndex = pLoop->u.btree.pIndex;
  105511. int nEq = pLoop->u.btree.nEq;
  105512. int i, j;
  105513. Column *aCol = pTab->aCol;
  105514. int *aiColumn = pIndex->aiColumn;
  105515. StrAccum txt;
  105516. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  105517. return 0;
  105518. }
  105519. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  105520. txt.db = db;
  105521. sqlite3StrAccumAppend(&txt, " (", 2);
  105522. for(i=0; i<nEq; i++){
  105523. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  105524. explainAppendTerm(&txt, i, z, "=");
  105525. }
  105526. j = i;
  105527. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  105528. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  105529. explainAppendTerm(&txt, i++, z, ">");
  105530. }
  105531. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  105532. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  105533. explainAppendTerm(&txt, i, z, "<");
  105534. }
  105535. sqlite3StrAccumAppend(&txt, ")", 1);
  105536. return sqlite3StrAccumFinish(&txt);
  105537. }
  105538. /*
  105539. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  105540. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  105541. ** record is added to the output to describe the table scan strategy in
  105542. ** pLevel.
  105543. */
  105544. static void explainOneScan(
  105545. Parse *pParse, /* Parse context */
  105546. SrcList *pTabList, /* Table list this loop refers to */
  105547. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  105548. int iLevel, /* Value for "level" column of output */
  105549. int iFrom, /* Value for "from" column of output */
  105550. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  105551. ){
  105552. if( pParse->explain==2 ){
  105553. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  105554. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  105555. sqlite3 *db = pParse->db; /* Database handle */
  105556. char *zMsg; /* Text to add to EQP output */
  105557. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  105558. int isSearch; /* True for a SEARCH. False for SCAN. */
  105559. WhereLoop *pLoop; /* The controlling WhereLoop object */
  105560. u32 flags; /* Flags that describe this loop */
  105561. pLoop = pLevel->pWLoop;
  105562. flags = pLoop->wsFlags;
  105563. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  105564. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  105565. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  105566. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  105567. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  105568. if( pItem->pSelect ){
  105569. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  105570. }else{
  105571. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  105572. }
  105573. if( pItem->zAlias ){
  105574. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  105575. }
  105576. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  105577. && ALWAYS(pLoop->u.btree.pIndex!=0)
  105578. ){
  105579. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  105580. zMsg = sqlite3MAppendf(db, zMsg,
  105581. ((flags & WHERE_AUTO_INDEX) ?
  105582. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  105583. "%s USING %sINDEX %s%s"),
  105584. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  105585. pLoop->u.btree.pIndex->zName, zWhere);
  105586. sqlite3DbFree(db, zWhere);
  105587. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  105588. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  105589. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  105590. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  105591. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  105592. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  105593. }else if( flags&WHERE_BTM_LIMIT ){
  105594. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  105595. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  105596. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  105597. }
  105598. }
  105599. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105600. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  105601. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  105602. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  105603. }
  105604. #endif
  105605. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  105606. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  105607. }
  105608. }
  105609. #else
  105610. # define explainOneScan(u,v,w,x,y,z)
  105611. #endif /* SQLITE_OMIT_EXPLAIN */
  105612. /*
  105613. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  105614. ** implementation described by pWInfo.
  105615. */
  105616. static Bitmask codeOneLoopStart(
  105617. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  105618. int iLevel, /* Which level of pWInfo->a[] should be coded */
  105619. Bitmask notReady /* Which tables are currently available */
  105620. ){
  105621. int j, k; /* Loop counters */
  105622. int iCur; /* The VDBE cursor for the table */
  105623. int addrNxt; /* Where to jump to continue with the next IN case */
  105624. int omitTable; /* True if we use the index only */
  105625. int bRev; /* True if we need to scan in reverse order */
  105626. WhereLevel *pLevel; /* The where level to be coded */
  105627. WhereLoop *pLoop; /* The WhereLoop object being coded */
  105628. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  105629. WhereTerm *pTerm; /* A WHERE clause term */
  105630. Parse *pParse; /* Parsing context */
  105631. sqlite3 *db; /* Database connection */
  105632. Vdbe *v; /* The prepared stmt under constructions */
  105633. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  105634. int addrBrk; /* Jump here to break out of the loop */
  105635. int addrCont; /* Jump here to continue with next cycle */
  105636. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  105637. int iReleaseReg = 0; /* Temp register to free before returning */
  105638. pParse = pWInfo->pParse;
  105639. v = pParse->pVdbe;
  105640. pWC = &pWInfo->sWC;
  105641. db = pParse->db;
  105642. pLevel = &pWInfo->a[iLevel];
  105643. pLoop = pLevel->pWLoop;
  105644. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  105645. iCur = pTabItem->iCursor;
  105646. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  105647. bRev = (pWInfo->revMask>>iLevel)&1;
  105648. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  105649. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  105650. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  105651. /* Create labels for the "break" and "continue" instructions
  105652. ** for the current loop. Jump to addrBrk to break out of a loop.
  105653. ** Jump to cont to go immediately to the next iteration of the
  105654. ** loop.
  105655. **
  105656. ** When there is an IN operator, we also have a "addrNxt" label that
  105657. ** means to continue with the next IN value combination. When
  105658. ** there are no IN operators in the constraints, the "addrNxt" label
  105659. ** is the same as "addrBrk".
  105660. */
  105661. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  105662. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  105663. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  105664. ** initialize a memory cell that records if this table matches any
  105665. ** row of the left table of the join.
  105666. */
  105667. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  105668. pLevel->iLeftJoin = ++pParse->nMem;
  105669. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  105670. VdbeComment((v, "init LEFT JOIN no-match flag"));
  105671. }
  105672. /* Special case of a FROM clause subquery implemented as a co-routine */
  105673. if( pTabItem->viaCoroutine ){
  105674. int regYield = pTabItem->regReturn;
  105675. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  105676. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  105677. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  105678. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  105679. pLevel->op = OP_Goto;
  105680. }else
  105681. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105682. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  105683. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  105684. ** to access the data.
  105685. */
  105686. int iReg; /* P3 Value for OP_VFilter */
  105687. int addrNotFound;
  105688. int nConstraint = pLoop->nLTerm;
  105689. sqlite3ExprCachePush(pParse);
  105690. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  105691. addrNotFound = pLevel->addrBrk;
  105692. for(j=0; j<nConstraint; j++){
  105693. int iTarget = iReg+j+2;
  105694. pTerm = pLoop->aLTerm[j];
  105695. if( pTerm==0 ) continue;
  105696. if( pTerm->eOperator & WO_IN ){
  105697. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  105698. addrNotFound = pLevel->addrNxt;
  105699. }else{
  105700. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  105701. }
  105702. }
  105703. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  105704. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  105705. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  105706. pLoop->u.vtab.idxStr,
  105707. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  105708. pLoop->u.vtab.needFree = 0;
  105709. for(j=0; j<nConstraint && j<16; j++){
  105710. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  105711. disableTerm(pLevel, pLoop->aLTerm[j]);
  105712. }
  105713. }
  105714. pLevel->op = OP_VNext;
  105715. pLevel->p1 = iCur;
  105716. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  105717. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  105718. sqlite3ExprCachePop(pParse, 1);
  105719. }else
  105720. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  105721. if( (pLoop->wsFlags & WHERE_IPK)!=0
  105722. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  105723. ){
  105724. /* Case 2: We can directly reference a single row using an
  105725. ** equality comparison against the ROWID field. Or
  105726. ** we reference multiple rows using a "rowid IN (...)"
  105727. ** construct.
  105728. */
  105729. assert( pLoop->u.btree.nEq==1 );
  105730. iReleaseReg = sqlite3GetTempReg(pParse);
  105731. pTerm = pLoop->aLTerm[0];
  105732. assert( pTerm!=0 );
  105733. assert( pTerm->pExpr!=0 );
  105734. assert( omitTable==0 );
  105735. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  105736. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  105737. addrNxt = pLevel->addrNxt;
  105738. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  105739. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  105740. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  105741. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  105742. VdbeComment((v, "pk"));
  105743. pLevel->op = OP_Noop;
  105744. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  105745. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  105746. ){
  105747. /* Case 3: We have an inequality comparison against the ROWID field.
  105748. */
  105749. int testOp = OP_Noop;
  105750. int start;
  105751. int memEndValue = 0;
  105752. WhereTerm *pStart, *pEnd;
  105753. assert( omitTable==0 );
  105754. j = 0;
  105755. pStart = pEnd = 0;
  105756. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  105757. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  105758. assert( pStart!=0 || pEnd!=0 );
  105759. if( bRev ){
  105760. pTerm = pStart;
  105761. pStart = pEnd;
  105762. pEnd = pTerm;
  105763. }
  105764. if( pStart ){
  105765. Expr *pX; /* The expression that defines the start bound */
  105766. int r1, rTemp; /* Registers for holding the start boundary */
  105767. /* The following constant maps TK_xx codes into corresponding
  105768. ** seek opcodes. It depends on a particular ordering of TK_xx
  105769. */
  105770. const u8 aMoveOp[] = {
  105771. /* TK_GT */ OP_SeekGt,
  105772. /* TK_LE */ OP_SeekLe,
  105773. /* TK_LT */ OP_SeekLt,
  105774. /* TK_GE */ OP_SeekGe
  105775. };
  105776. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  105777. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  105778. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  105779. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  105780. testcase( pStart->wtFlags & TERM_VIRTUAL );
  105781. pX = pStart->pExpr;
  105782. assert( pX!=0 );
  105783. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  105784. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  105785. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  105786. VdbeComment((v, "pk"));
  105787. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  105788. sqlite3ReleaseTempReg(pParse, rTemp);
  105789. disableTerm(pLevel, pStart);
  105790. }else{
  105791. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  105792. }
  105793. if( pEnd ){
  105794. Expr *pX;
  105795. pX = pEnd->pExpr;
  105796. assert( pX!=0 );
  105797. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  105798. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  105799. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  105800. memEndValue = ++pParse->nMem;
  105801. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  105802. if( pX->op==TK_LT || pX->op==TK_GT ){
  105803. testOp = bRev ? OP_Le : OP_Ge;
  105804. }else{
  105805. testOp = bRev ? OP_Lt : OP_Gt;
  105806. }
  105807. disableTerm(pLevel, pEnd);
  105808. }
  105809. start = sqlite3VdbeCurrentAddr(v);
  105810. pLevel->op = bRev ? OP_Prev : OP_Next;
  105811. pLevel->p1 = iCur;
  105812. pLevel->p2 = start;
  105813. assert( pLevel->p5==0 );
  105814. if( testOp!=OP_Noop ){
  105815. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  105816. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  105817. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  105818. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  105819. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  105820. }
  105821. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  105822. /* Case 4: A scan using an index.
  105823. **
  105824. ** The WHERE clause may contain zero or more equality
  105825. ** terms ("==" or "IN" operators) that refer to the N
  105826. ** left-most columns of the index. It may also contain
  105827. ** inequality constraints (>, <, >= or <=) on the indexed
  105828. ** column that immediately follows the N equalities. Only
  105829. ** the right-most column can be an inequality - the rest must
  105830. ** use the "==" and "IN" operators. For example, if the
  105831. ** index is on (x,y,z), then the following clauses are all
  105832. ** optimized:
  105833. **
  105834. ** x=5
  105835. ** x=5 AND y=10
  105836. ** x=5 AND y<10
  105837. ** x=5 AND y>5 AND y<10
  105838. ** x=5 AND y=5 AND z<=10
  105839. **
  105840. ** The z<10 term of the following cannot be used, only
  105841. ** the x=5 term:
  105842. **
  105843. ** x=5 AND z<10
  105844. **
  105845. ** N may be zero if there are inequality constraints.
  105846. ** If there are no inequality constraints, then N is at
  105847. ** least one.
  105848. **
  105849. ** This case is also used when there are no WHERE clause
  105850. ** constraints but an index is selected anyway, in order
  105851. ** to force the output order to conform to an ORDER BY.
  105852. */
  105853. static const u8 aStartOp[] = {
  105854. 0,
  105855. 0,
  105856. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  105857. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  105858. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  105859. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  105860. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  105861. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  105862. };
  105863. static const u8 aEndOp[] = {
  105864. OP_Noop, /* 0: (!end_constraints) */
  105865. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  105866. OP_IdxLT /* 2: (end_constraints && bRev) */
  105867. };
  105868. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  105869. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  105870. int regBase; /* Base register holding constraint values */
  105871. int r1; /* Temp register */
  105872. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  105873. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  105874. int startEq; /* True if range start uses ==, >= or <= */
  105875. int endEq; /* True if range end uses ==, >= or <= */
  105876. int start_constraints; /* Start of range is constrained */
  105877. int nConstraint; /* Number of constraint terms */
  105878. Index *pIdx; /* The index we will be using */
  105879. int iIdxCur; /* The VDBE cursor for the index */
  105880. int nExtraReg = 0; /* Number of extra registers needed */
  105881. int op; /* Instruction opcode */
  105882. char *zStartAff; /* Affinity for start of range constraint */
  105883. char *zEndAff; /* Affinity for end of range constraint */
  105884. pIdx = pLoop->u.btree.pIndex;
  105885. iIdxCur = pLevel->iIdxCur;
  105886. /* If this loop satisfies a sort order (pOrderBy) request that
  105887. ** was passed to this function to implement a "SELECT min(x) ..."
  105888. ** query, then the caller will only allow the loop to run for
  105889. ** a single iteration. This means that the first row returned
  105890. ** should not have a NULL value stored in 'x'. If column 'x' is
  105891. ** the first one after the nEq equality constraints in the index,
  105892. ** this requires some special handling.
  105893. */
  105894. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  105895. && (pWInfo->bOBSat!=0)
  105896. && (pIdx->nColumn>nEq)
  105897. ){
  105898. /* assert( pOrderBy->nExpr==1 ); */
  105899. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  105900. isMinQuery = 1;
  105901. nExtraReg = 1;
  105902. }
  105903. /* Find any inequality constraint terms for the start and end
  105904. ** of the range.
  105905. */
  105906. j = nEq;
  105907. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  105908. pRangeStart = pLoop->aLTerm[j++];
  105909. nExtraReg = 1;
  105910. }
  105911. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  105912. pRangeEnd = pLoop->aLTerm[j++];
  105913. nExtraReg = 1;
  105914. }
  105915. /* Generate code to evaluate all constraint terms using == or IN
  105916. ** and store the values of those terms in an array of registers
  105917. ** starting at regBase.
  105918. */
  105919. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  105920. zEndAff = sqlite3DbStrDup(db, zStartAff);
  105921. addrNxt = pLevel->addrNxt;
  105922. /* If we are doing a reverse order scan on an ascending index, or
  105923. ** a forward order scan on a descending index, interchange the
  105924. ** start and end terms (pRangeStart and pRangeEnd).
  105925. */
  105926. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  105927. || (bRev && pIdx->nColumn==nEq)
  105928. ){
  105929. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  105930. }
  105931. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  105932. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  105933. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  105934. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  105935. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  105936. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  105937. start_constraints = pRangeStart || nEq>0;
  105938. /* Seek the index cursor to the start of the range. */
  105939. nConstraint = nEq;
  105940. if( pRangeStart ){
  105941. Expr *pRight = pRangeStart->pExpr->pRight;
  105942. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  105943. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  105944. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  105945. }
  105946. if( zStartAff ){
  105947. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  105948. /* Since the comparison is to be performed with no conversions
  105949. ** applied to the operands, set the affinity to apply to pRight to
  105950. ** SQLITE_AFF_NONE. */
  105951. zStartAff[nEq] = SQLITE_AFF_NONE;
  105952. }
  105953. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  105954. zStartAff[nEq] = SQLITE_AFF_NONE;
  105955. }
  105956. }
  105957. nConstraint++;
  105958. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  105959. }else if( isMinQuery ){
  105960. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  105961. nConstraint++;
  105962. startEq = 0;
  105963. start_constraints = 1;
  105964. }
  105965. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  105966. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  105967. assert( op!=0 );
  105968. testcase( op==OP_Rewind );
  105969. testcase( op==OP_Last );
  105970. testcase( op==OP_SeekGt );
  105971. testcase( op==OP_SeekGe );
  105972. testcase( op==OP_SeekLe );
  105973. testcase( op==OP_SeekLt );
  105974. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  105975. /* Load the value for the inequality constraint at the end of the
  105976. ** range (if any).
  105977. */
  105978. nConstraint = nEq;
  105979. if( pRangeEnd ){
  105980. Expr *pRight = pRangeEnd->pExpr->pRight;
  105981. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  105982. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  105983. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  105984. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  105985. }
  105986. if( zEndAff ){
  105987. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  105988. /* Since the comparison is to be performed with no conversions
  105989. ** applied to the operands, set the affinity to apply to pRight to
  105990. ** SQLITE_AFF_NONE. */
  105991. zEndAff[nEq] = SQLITE_AFF_NONE;
  105992. }
  105993. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  105994. zEndAff[nEq] = SQLITE_AFF_NONE;
  105995. }
  105996. }
  105997. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  105998. nConstraint++;
  105999. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  106000. }
  106001. sqlite3DbFree(db, zStartAff);
  106002. sqlite3DbFree(db, zEndAff);
  106003. /* Top of the loop body */
  106004. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  106005. /* Check if the index cursor is past the end of the range. */
  106006. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  106007. testcase( op==OP_Noop );
  106008. testcase( op==OP_IdxGE );
  106009. testcase( op==OP_IdxLT );
  106010. if( op!=OP_Noop ){
  106011. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  106012. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  106013. }
  106014. /* If there are inequality constraints, check that the value
  106015. ** of the table column that the inequality contrains is not NULL.
  106016. ** If it is, jump to the next iteration of the loop.
  106017. */
  106018. r1 = sqlite3GetTempReg(pParse);
  106019. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  106020. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  106021. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  106022. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  106023. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  106024. }
  106025. sqlite3ReleaseTempReg(pParse, r1);
  106026. /* Seek the table cursor, if required */
  106027. disableTerm(pLevel, pRangeStart);
  106028. disableTerm(pLevel, pRangeEnd);
  106029. if( !omitTable ){
  106030. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  106031. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  106032. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  106033. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  106034. }
  106035. /* Record the instruction used to terminate the loop. Disable
  106036. ** WHERE clause terms made redundant by the index range scan.
  106037. */
  106038. if( pLoop->wsFlags & WHERE_ONEROW ){
  106039. pLevel->op = OP_Noop;
  106040. }else if( bRev ){
  106041. pLevel->op = OP_Prev;
  106042. }else{
  106043. pLevel->op = OP_Next;
  106044. }
  106045. pLevel->p1 = iIdxCur;
  106046. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  106047. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  106048. }else{
  106049. assert( pLevel->p5==0 );
  106050. }
  106051. }else
  106052. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  106053. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  106054. /* Case 5: Two or more separately indexed terms connected by OR
  106055. **
  106056. ** Example:
  106057. **
  106058. ** CREATE TABLE t1(a,b,c,d);
  106059. ** CREATE INDEX i1 ON t1(a);
  106060. ** CREATE INDEX i2 ON t1(b);
  106061. ** CREATE INDEX i3 ON t1(c);
  106062. **
  106063. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  106064. **
  106065. ** In the example, there are three indexed terms connected by OR.
  106066. ** The top of the loop looks like this:
  106067. **
  106068. ** Null 1 # Zero the rowset in reg 1
  106069. **
  106070. ** Then, for each indexed term, the following. The arguments to
  106071. ** RowSetTest are such that the rowid of the current row is inserted
  106072. ** into the RowSet. If it is already present, control skips the
  106073. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  106074. **
  106075. ** sqlite3WhereBegin(<term>)
  106076. ** RowSetTest # Insert rowid into rowset
  106077. ** Gosub 2 A
  106078. ** sqlite3WhereEnd()
  106079. **
  106080. ** Following the above, code to terminate the loop. Label A, the target
  106081. ** of the Gosub above, jumps to the instruction right after the Goto.
  106082. **
  106083. ** Null 1 # Zero the rowset in reg 1
  106084. ** Goto B # The loop is finished.
  106085. **
  106086. ** A: <loop body> # Return data, whatever.
  106087. **
  106088. ** Return 2 # Jump back to the Gosub
  106089. **
  106090. ** B: <after the loop>
  106091. **
  106092. */
  106093. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  106094. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  106095. Index *pCov = 0; /* Potential covering index (or NULL) */
  106096. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  106097. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  106098. int regRowset = 0; /* Register for RowSet object */
  106099. int regRowid = 0; /* Register holding rowid */
  106100. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  106101. int iRetInit; /* Address of regReturn init */
  106102. int untestedTerms = 0; /* Some terms not completely tested */
  106103. int ii; /* Loop counter */
  106104. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  106105. pTerm = pLoop->aLTerm[0];
  106106. assert( pTerm!=0 );
  106107. assert( pTerm->eOperator & WO_OR );
  106108. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  106109. pOrWc = &pTerm->u.pOrInfo->wc;
  106110. pLevel->op = OP_Return;
  106111. pLevel->p1 = regReturn;
  106112. /* Set up a new SrcList in pOrTab containing the table being scanned
  106113. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  106114. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  106115. */
  106116. if( pWInfo->nLevel>1 ){
  106117. int nNotReady; /* The number of notReady tables */
  106118. struct SrcList_item *origSrc; /* Original list of tables */
  106119. nNotReady = pWInfo->nLevel - iLevel - 1;
  106120. pOrTab = sqlite3StackAllocRaw(db,
  106121. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  106122. if( pOrTab==0 ) return notReady;
  106123. pOrTab->nAlloc = (u8)(nNotReady + 1);
  106124. pOrTab->nSrc = pOrTab->nAlloc;
  106125. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  106126. origSrc = pWInfo->pTabList->a;
  106127. for(k=1; k<=nNotReady; k++){
  106128. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  106129. }
  106130. }else{
  106131. pOrTab = pWInfo->pTabList;
  106132. }
  106133. /* Initialize the rowset register to contain NULL. An SQL NULL is
  106134. ** equivalent to an empty rowset.
  106135. **
  106136. ** Also initialize regReturn to contain the address of the instruction
  106137. ** immediately following the OP_Return at the bottom of the loop. This
  106138. ** is required in a few obscure LEFT JOIN cases where control jumps
  106139. ** over the top of the loop into the body of it. In this case the
  106140. ** correct response for the end-of-loop code (the OP_Return) is to
  106141. ** fall through to the next instruction, just as an OP_Next does if
  106142. ** called on an uninitialized cursor.
  106143. */
  106144. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  106145. regRowset = ++pParse->nMem;
  106146. regRowid = ++pParse->nMem;
  106147. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  106148. }
  106149. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  106150. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  106151. ** Then for every term xN, evaluate as the subexpression: xN AND z
  106152. ** That way, terms in y that are factored into the disjunction will
  106153. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  106154. **
  106155. ** Actually, each subexpression is converted to "xN AND w" where w is
  106156. ** the "interesting" terms of z - terms that did not originate in the
  106157. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  106158. ** indices.
  106159. **
  106160. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  106161. ** is not contained in the ON clause of a LEFT JOIN.
  106162. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  106163. */
  106164. if( pWC->nTerm>1 ){
  106165. int iTerm;
  106166. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  106167. Expr *pExpr = pWC->a[iTerm].pExpr;
  106168. if( &pWC->a[iTerm] == pTerm ) continue;
  106169. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  106170. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  106171. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  106172. pExpr = sqlite3ExprDup(db, pExpr, 0);
  106173. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  106174. }
  106175. if( pAndExpr ){
  106176. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  106177. }
  106178. }
  106179. for(ii=0; ii<pOrWc->nTerm; ii++){
  106180. WhereTerm *pOrTerm = &pOrWc->a[ii];
  106181. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  106182. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  106183. Expr *pOrExpr = pOrTerm->pExpr;
  106184. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  106185. pAndExpr->pLeft = pOrExpr;
  106186. pOrExpr = pAndExpr;
  106187. }
  106188. /* Loop through table entries that match term pOrTerm. */
  106189. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  106190. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  106191. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  106192. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  106193. if( pSubWInfo ){
  106194. WhereLoop *pSubLoop;
  106195. explainOneScan(
  106196. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  106197. );
  106198. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  106199. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  106200. int r;
  106201. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  106202. regRowid, 0);
  106203. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  106204. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  106205. }
  106206. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  106207. /* The pSubWInfo->untestedTerms flag means that this OR term
  106208. ** contained one or more AND term from a notReady table. The
  106209. ** terms from the notReady table could not be tested and will
  106210. ** need to be tested later.
  106211. */
  106212. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  106213. /* If all of the OR-connected terms are optimized using the same
  106214. ** index, and the index is opened using the same cursor number
  106215. ** by each call to sqlite3WhereBegin() made by this loop, it may
  106216. ** be possible to use that index as a covering index.
  106217. **
  106218. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  106219. ** uses an index, and this is either the first OR-connected term
  106220. ** processed or the index is the same as that used by all previous
  106221. ** terms, set pCov to the candidate covering index. Otherwise, set
  106222. ** pCov to NULL to indicate that no candidate covering index will
  106223. ** be available.
  106224. */
  106225. pSubLoop = pSubWInfo->a[0].pWLoop;
  106226. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  106227. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  106228. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  106229. ){
  106230. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  106231. pCov = pSubLoop->u.btree.pIndex;
  106232. }else{
  106233. pCov = 0;
  106234. }
  106235. /* Finish the loop through table entries that match term pOrTerm. */
  106236. sqlite3WhereEnd(pSubWInfo);
  106237. }
  106238. }
  106239. }
  106240. pLevel->u.pCovidx = pCov;
  106241. if( pCov ) pLevel->iIdxCur = iCovCur;
  106242. if( pAndExpr ){
  106243. pAndExpr->pLeft = 0;
  106244. sqlite3ExprDelete(db, pAndExpr);
  106245. }
  106246. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  106247. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  106248. sqlite3VdbeResolveLabel(v, iLoopBody);
  106249. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  106250. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  106251. }else
  106252. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  106253. {
  106254. /* Case 6: There is no usable index. We must do a complete
  106255. ** scan of the entire table.
  106256. */
  106257. static const u8 aStep[] = { OP_Next, OP_Prev };
  106258. static const u8 aStart[] = { OP_Rewind, OP_Last };
  106259. assert( bRev==0 || bRev==1 );
  106260. pLevel->op = aStep[bRev];
  106261. pLevel->p1 = iCur;
  106262. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  106263. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  106264. }
  106265. /* Insert code to test every subexpression that can be completely
  106266. ** computed using the current set of tables.
  106267. */
  106268. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  106269. Expr *pE;
  106270. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  106271. testcase( pTerm->wtFlags & TERM_CODED );
  106272. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106273. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  106274. testcase( pWInfo->untestedTerms==0
  106275. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  106276. pWInfo->untestedTerms = 1;
  106277. continue;
  106278. }
  106279. pE = pTerm->pExpr;
  106280. assert( pE!=0 );
  106281. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  106282. continue;
  106283. }
  106284. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  106285. pTerm->wtFlags |= TERM_CODED;
  106286. }
  106287. /* Insert code to test for implied constraints based on transitivity
  106288. ** of the "==" operator.
  106289. **
  106290. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  106291. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  106292. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  106293. ** the implied "t1.a=123" constraint.
  106294. */
  106295. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  106296. Expr *pE, *pEAlt;
  106297. WhereTerm *pAlt;
  106298. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106299. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  106300. if( pTerm->leftCursor!=iCur ) continue;
  106301. if( pLevel->iLeftJoin ) continue;
  106302. pE = pTerm->pExpr;
  106303. assert( !ExprHasProperty(pE, EP_FromJoin) );
  106304. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  106305. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  106306. if( pAlt==0 ) continue;
  106307. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  106308. testcase( pAlt->eOperator & WO_EQ );
  106309. testcase( pAlt->eOperator & WO_IN );
  106310. VdbeNoopComment((v, "begin transitive constraint"));
  106311. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  106312. if( pEAlt ){
  106313. *pEAlt = *pAlt->pExpr;
  106314. pEAlt->pLeft = pE->pLeft;
  106315. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  106316. sqlite3StackFree(db, pEAlt);
  106317. }
  106318. }
  106319. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  106320. ** at least one row of the right table has matched the left table.
  106321. */
  106322. if( pLevel->iLeftJoin ){
  106323. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  106324. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  106325. VdbeComment((v, "record LEFT JOIN hit"));
  106326. sqlite3ExprCacheClear(pParse);
  106327. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  106328. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  106329. testcase( pTerm->wtFlags & TERM_CODED );
  106330. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106331. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  106332. assert( pWInfo->untestedTerms );
  106333. continue;
  106334. }
  106335. assert( pTerm->pExpr );
  106336. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  106337. pTerm->wtFlags |= TERM_CODED;
  106338. }
  106339. }
  106340. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  106341. return pLevel->notReady;
  106342. }
  106343. #ifdef WHERETRACE_ENABLED
  106344. /*
  106345. ** Print a WhereLoop object for debugging purposes
  106346. */
  106347. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  106348. int nb = 1+(pTabList->nSrc+7)/8;
  106349. struct SrcList_item *pItem = pTabList->a + p->iTab;
  106350. Table *pTab = pItem->pTab;
  106351. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  106352. p->iTab, nb, p->maskSelf, nb, p->prereq);
  106353. sqlite3DebugPrintf(" %12s",
  106354. pItem->zAlias ? pItem->zAlias : pTab->zName);
  106355. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  106356. if( p->u.btree.pIndex ){
  106357. const char *zName = p->u.btree.pIndex->zName;
  106358. if( zName==0 ) zName = "ipk";
  106359. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  106360. int i = sqlite3Strlen30(zName) - 1;
  106361. while( zName[i]!='_' ) i--;
  106362. zName += i;
  106363. }
  106364. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  106365. }else{
  106366. sqlite3DebugPrintf("%20s","");
  106367. }
  106368. }else{
  106369. char *z;
  106370. if( p->u.vtab.idxStr ){
  106371. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  106372. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  106373. }else{
  106374. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  106375. }
  106376. sqlite3DebugPrintf(" %-19s", z);
  106377. sqlite3_free(z);
  106378. }
  106379. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  106380. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  106381. }
  106382. #endif
  106383. /*
  106384. ** Convert bulk memory into a valid WhereLoop that can be passed
  106385. ** to whereLoopClear harmlessly.
  106386. */
  106387. static void whereLoopInit(WhereLoop *p){
  106388. p->aLTerm = p->aLTermSpace;
  106389. p->nLTerm = 0;
  106390. p->nLSlot = ArraySize(p->aLTermSpace);
  106391. p->wsFlags = 0;
  106392. }
  106393. /*
  106394. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  106395. */
  106396. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  106397. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  106398. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  106399. sqlite3_free(p->u.vtab.idxStr);
  106400. p->u.vtab.needFree = 0;
  106401. p->u.vtab.idxStr = 0;
  106402. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  106403. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  106404. sqlite3DbFree(db, p->u.btree.pIndex);
  106405. p->u.btree.pIndex = 0;
  106406. }
  106407. }
  106408. }
  106409. /*
  106410. ** Deallocate internal memory used by a WhereLoop object
  106411. */
  106412. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  106413. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  106414. whereLoopClearUnion(db, p);
  106415. whereLoopInit(p);
  106416. }
  106417. /*
  106418. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  106419. */
  106420. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  106421. WhereTerm **paNew;
  106422. if( p->nLSlot>=n ) return SQLITE_OK;
  106423. n = (n+7)&~7;
  106424. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  106425. if( paNew==0 ) return SQLITE_NOMEM;
  106426. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  106427. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  106428. p->aLTerm = paNew;
  106429. p->nLSlot = n;
  106430. return SQLITE_OK;
  106431. }
  106432. /*
  106433. ** Transfer content from the second pLoop into the first.
  106434. */
  106435. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  106436. whereLoopClearUnion(db, pTo);
  106437. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  106438. memset(&pTo->u, 0, sizeof(pTo->u));
  106439. return SQLITE_NOMEM;
  106440. }
  106441. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  106442. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  106443. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  106444. pFrom->u.vtab.needFree = 0;
  106445. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  106446. pFrom->u.btree.pIndex = 0;
  106447. }
  106448. return SQLITE_OK;
  106449. }
  106450. /*
  106451. ** Delete a WhereLoop object
  106452. */
  106453. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  106454. whereLoopClear(db, p);
  106455. sqlite3DbFree(db, p);
  106456. }
  106457. /*
  106458. ** Free a WhereInfo structure
  106459. */
  106460. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  106461. if( ALWAYS(pWInfo) ){
  106462. whereClauseClear(&pWInfo->sWC);
  106463. while( pWInfo->pLoops ){
  106464. WhereLoop *p = pWInfo->pLoops;
  106465. pWInfo->pLoops = p->pNextLoop;
  106466. whereLoopDelete(db, p);
  106467. }
  106468. sqlite3DbFree(db, pWInfo);
  106469. }
  106470. }
  106471. /*
  106472. ** Insert or replace a WhereLoop entry using the template supplied.
  106473. **
  106474. ** An existing WhereLoop entry might be overwritten if the new template
  106475. ** is better and has fewer dependencies. Or the template will be ignored
  106476. ** and no insert will occur if an existing WhereLoop is faster and has
  106477. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  106478. ** added based on the template.
  106479. **
  106480. ** If pBuilder->pOrSet is not NULL then we only care about only the
  106481. ** prerequisites and rRun and nOut costs of the N best loops. That
  106482. ** information is gathered in the pBuilder->pOrSet object. This special
  106483. ** processing mode is used only for OR clause processing.
  106484. **
  106485. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  106486. ** still might overwrite similar loops with the new template if the
  106487. ** template is better. Loops may be overwritten if the following
  106488. ** conditions are met:
  106489. **
  106490. ** (1) They have the same iTab.
  106491. ** (2) They have the same iSortIdx.
  106492. ** (3) The template has same or fewer dependencies than the current loop
  106493. ** (4) The template has the same or lower cost than the current loop
  106494. ** (5) The template uses more terms of the same index but has no additional
  106495. ** dependencies
  106496. */
  106497. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  106498. WhereLoop **ppPrev, *p, *pNext = 0;
  106499. WhereInfo *pWInfo = pBuilder->pWInfo;
  106500. sqlite3 *db = pWInfo->pParse->db;
  106501. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  106502. ** and prereqs.
  106503. */
  106504. if( pBuilder->pOrSet!=0 ){
  106505. #if WHERETRACE_ENABLED
  106506. u16 n = pBuilder->pOrSet->n;
  106507. int x =
  106508. #endif
  106509. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  106510. pTemplate->nOut);
  106511. #if WHERETRACE_ENABLED
  106512. if( sqlite3WhereTrace & 0x8 ){
  106513. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  106514. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106515. }
  106516. #endif
  106517. return SQLITE_OK;
  106518. }
  106519. /* Search for an existing WhereLoop to overwrite, or which takes
  106520. ** priority over pTemplate.
  106521. */
  106522. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  106523. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  106524. /* If either the iTab or iSortIdx values for two WhereLoop are different
  106525. ** then those WhereLoops need to be considered separately. Neither is
  106526. ** a candidate to replace the other. */
  106527. continue;
  106528. }
  106529. /* In the current implementation, the rSetup value is either zero
  106530. ** or the cost of building an automatic index (NlogN) and the NlogN
  106531. ** is the same for compatible WhereLoops. */
  106532. assert( p->rSetup==0 || pTemplate->rSetup==0
  106533. || p->rSetup==pTemplate->rSetup );
  106534. /* whereLoopAddBtree() always generates and inserts the automatic index
  106535. ** case first. Hence compatible candidate WhereLoops never have a larger
  106536. ** rSetup. Call this SETUP-INVARIANT */
  106537. assert( p->rSetup>=pTemplate->rSetup );
  106538. if( (p->prereq & pTemplate->prereq)==p->prereq
  106539. && p->rSetup<=pTemplate->rSetup
  106540. && p->rRun<=pTemplate->rRun
  106541. && p->nOut<=pTemplate->nOut
  106542. ){
  106543. /* This branch taken when p is equal or better than pTemplate in
  106544. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  106545. ** (4) number of output rows. */
  106546. assert( p->rSetup==pTemplate->rSetup );
  106547. if( p->prereq==pTemplate->prereq
  106548. && p->nLTerm<pTemplate->nLTerm
  106549. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  106550. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  106551. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  106552. ){
  106553. /* Overwrite an existing WhereLoop with an similar one that uses
  106554. ** more terms of the index */
  106555. pNext = p->pNextLoop;
  106556. break;
  106557. }else{
  106558. /* pTemplate is not helpful.
  106559. ** Return without changing or adding anything */
  106560. goto whereLoopInsert_noop;
  106561. }
  106562. }
  106563. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  106564. && p->rRun>=pTemplate->rRun
  106565. && p->nOut>=pTemplate->nOut
  106566. ){
  106567. /* Overwrite an existing WhereLoop with a better one: one that is
  106568. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  106569. ** or (4) number of output rows, and is no worse in any of those
  106570. ** categories. */
  106571. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  106572. pNext = p->pNextLoop;
  106573. break;
  106574. }
  106575. }
  106576. /* If we reach this point it means that either p[] should be overwritten
  106577. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  106578. ** WhereLoop and insert it.
  106579. */
  106580. #if WHERETRACE_ENABLED
  106581. if( sqlite3WhereTrace & 0x8 ){
  106582. if( p!=0 ){
  106583. sqlite3DebugPrintf("ins-del: ");
  106584. whereLoopPrint(p, pWInfo->pTabList);
  106585. }
  106586. sqlite3DebugPrintf("ins-new: ");
  106587. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106588. }
  106589. #endif
  106590. if( p==0 ){
  106591. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  106592. if( p==0 ) return SQLITE_NOMEM;
  106593. whereLoopInit(p);
  106594. }
  106595. whereLoopXfer(db, p, pTemplate);
  106596. p->pNextLoop = pNext;
  106597. *ppPrev = p;
  106598. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  106599. Index *pIndex = p->u.btree.pIndex;
  106600. if( pIndex && pIndex->tnum==0 ){
  106601. p->u.btree.pIndex = 0;
  106602. }
  106603. }
  106604. return SQLITE_OK;
  106605. /* Jump here if the insert is a no-op */
  106606. whereLoopInsert_noop:
  106607. #if WHERETRACE_ENABLED
  106608. if( sqlite3WhereTrace & 0x8 ){
  106609. sqlite3DebugPrintf("ins-noop: ");
  106610. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106611. }
  106612. #endif
  106613. return SQLITE_OK;
  106614. }
  106615. /*
  106616. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  106617. ** WHERE clause that reference the loop but which are not used by an
  106618. ** index.
  106619. **
  106620. ** In the current implementation, the first extra WHERE clause term reduces
  106621. ** the number of output rows by a factor of 10 and each additional term
  106622. ** reduces the number of output rows by sqrt(2).
  106623. */
  106624. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  106625. WhereTerm *pTerm, *pX;
  106626. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  106627. int i, j;
  106628. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  106629. return;
  106630. }
  106631. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  106632. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  106633. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  106634. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  106635. for(j=pLoop->nLTerm-1; j>=0; j--){
  106636. pX = pLoop->aLTerm[j];
  106637. if( pX==pTerm ) break;
  106638. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  106639. }
  106640. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  106641. }
  106642. }
  106643. /*
  106644. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  106645. ** Try to match one more.
  106646. **
  106647. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  106648. ** INTEGER PRIMARY KEY.
  106649. */
  106650. static int whereLoopAddBtreeIndex(
  106651. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  106652. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  106653. Index *pProbe, /* An index on pSrc */
  106654. LogEst nInMul /* log(Number of iterations due to IN) */
  106655. ){
  106656. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  106657. Parse *pParse = pWInfo->pParse; /* Parsing context */
  106658. sqlite3 *db = pParse->db; /* Database connection malloc context */
  106659. WhereLoop *pNew; /* Template WhereLoop under construction */
  106660. WhereTerm *pTerm; /* A WhereTerm under consideration */
  106661. int opMask; /* Valid operators for constraints */
  106662. WhereScan scan; /* Iterator for WHERE terms */
  106663. Bitmask saved_prereq; /* Original value of pNew->prereq */
  106664. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  106665. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  106666. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  106667. LogEst saved_nOut; /* Original value of pNew->nOut */
  106668. int iCol; /* Index of the column in the table */
  106669. int rc = SQLITE_OK; /* Return code */
  106670. LogEst nRowEst; /* Estimated index selectivity */
  106671. LogEst rLogSize; /* Logarithm of table size */
  106672. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  106673. pNew = pBuilder->pNew;
  106674. if( db->mallocFailed ) return SQLITE_NOMEM;
  106675. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  106676. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  106677. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  106678. opMask = WO_LT|WO_LE;
  106679. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  106680. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  106681. }else{
  106682. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  106683. }
  106684. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  106685. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  106686. if( pNew->u.btree.nEq < pProbe->nColumn ){
  106687. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  106688. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  106689. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  106690. }else{
  106691. iCol = -1;
  106692. nRowEst = 0;
  106693. }
  106694. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  106695. opMask, pProbe);
  106696. saved_nEq = pNew->u.btree.nEq;
  106697. saved_nLTerm = pNew->nLTerm;
  106698. saved_wsFlags = pNew->wsFlags;
  106699. saved_prereq = pNew->prereq;
  106700. saved_nOut = pNew->nOut;
  106701. pNew->rSetup = 0;
  106702. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  106703. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  106704. int nIn = 0;
  106705. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106706. int nRecValid = pBuilder->nRecValid;
  106707. #endif
  106708. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  106709. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  106710. ){
  106711. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  106712. }
  106713. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  106714. assert( pNew->nOut==saved_nOut );
  106715. pNew->wsFlags = saved_wsFlags;
  106716. pNew->u.btree.nEq = saved_nEq;
  106717. pNew->nLTerm = saved_nLTerm;
  106718. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  106719. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  106720. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  106721. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  106722. if( pTerm->eOperator & WO_IN ){
  106723. Expr *pExpr = pTerm->pExpr;
  106724. pNew->wsFlags |= WHERE_COLUMN_IN;
  106725. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  106726. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  106727. nIn = 46; assert( 46==sqlite3LogEst(25) );
  106728. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  106729. /* "x IN (value, value, ...)" */
  106730. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  106731. }
  106732. pNew->rRun += nIn;
  106733. pNew->u.btree.nEq++;
  106734. pNew->nOut = nRowEst + nInMul + nIn;
  106735. }else if( pTerm->eOperator & (WO_EQ) ){
  106736. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  106737. || nInMul==0 );
  106738. pNew->wsFlags |= WHERE_COLUMN_EQ;
  106739. if( iCol<0
  106740. || (pProbe->onError!=OE_None && nInMul==0
  106741. && pNew->u.btree.nEq==pProbe->nColumn-1)
  106742. ){
  106743. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  106744. pNew->wsFlags |= WHERE_ONEROW;
  106745. }
  106746. pNew->u.btree.nEq++;
  106747. pNew->nOut = nRowEst + nInMul;
  106748. }else if( pTerm->eOperator & (WO_ISNULL) ){
  106749. pNew->wsFlags |= WHERE_COLUMN_NULL;
  106750. pNew->u.btree.nEq++;
  106751. /* TUNING: IS NULL selects 2 rows */
  106752. nIn = 10; assert( 10==sqlite3LogEst(2) );
  106753. pNew->nOut = nRowEst + nInMul + nIn;
  106754. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  106755. testcase( pTerm->eOperator & WO_GT );
  106756. testcase( pTerm->eOperator & WO_GE );
  106757. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  106758. pBtm = pTerm;
  106759. pTop = 0;
  106760. }else{
  106761. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  106762. testcase( pTerm->eOperator & WO_LT );
  106763. testcase( pTerm->eOperator & WO_LE );
  106764. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  106765. pTop = pTerm;
  106766. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  106767. pNew->aLTerm[pNew->nLTerm-2] : 0;
  106768. }
  106769. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  106770. /* Adjust nOut and rRun for STAT3 range values */
  106771. assert( pNew->nOut==saved_nOut );
  106772. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  106773. }
  106774. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106775. if( nInMul==0
  106776. && pProbe->nSample
  106777. && pNew->u.btree.nEq<=pProbe->nSampleCol
  106778. && OptimizationEnabled(db, SQLITE_Stat3)
  106779. ){
  106780. Expr *pExpr = pTerm->pExpr;
  106781. tRowcnt nOut = 0;
  106782. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  106783. testcase( pTerm->eOperator & WO_EQ );
  106784. testcase( pTerm->eOperator & WO_ISNULL );
  106785. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  106786. }else if( (pTerm->eOperator & WO_IN)
  106787. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  106788. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  106789. }
  106790. assert( nOut==0 || rc==SQLITE_OK );
  106791. if( nOut ){
  106792. pNew->nOut = sqlite3LogEst(nOut);
  106793. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  106794. }
  106795. }
  106796. #endif
  106797. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  106798. /* Each row involves a step of the index, then a binary search of
  106799. ** the main table */
  106800. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  106801. }
  106802. /* Step cost for each output row */
  106803. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  106804. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  106805. rc = whereLoopInsert(pBuilder, pNew);
  106806. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  106807. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  106808. ){
  106809. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  106810. }
  106811. pNew->nOut = saved_nOut;
  106812. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106813. pBuilder->nRecValid = nRecValid;
  106814. #endif
  106815. }
  106816. pNew->prereq = saved_prereq;
  106817. pNew->u.btree.nEq = saved_nEq;
  106818. pNew->wsFlags = saved_wsFlags;
  106819. pNew->nOut = saved_nOut;
  106820. pNew->nLTerm = saved_nLTerm;
  106821. return rc;
  106822. }
  106823. /*
  106824. ** Return True if it is possible that pIndex might be useful in
  106825. ** implementing the ORDER BY clause in pBuilder.
  106826. **
  106827. ** Return False if pBuilder does not contain an ORDER BY clause or
  106828. ** if there is no way for pIndex to be useful in implementing that
  106829. ** ORDER BY clause.
  106830. */
  106831. static int indexMightHelpWithOrderBy(
  106832. WhereLoopBuilder *pBuilder,
  106833. Index *pIndex,
  106834. int iCursor
  106835. ){
  106836. ExprList *pOB;
  106837. int ii, jj;
  106838. if( pIndex->bUnordered ) return 0;
  106839. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  106840. for(ii=0; ii<pOB->nExpr; ii++){
  106841. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  106842. if( pExpr->op!=TK_COLUMN ) return 0;
  106843. if( pExpr->iTable==iCursor ){
  106844. for(jj=0; jj<pIndex->nColumn; jj++){
  106845. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  106846. }
  106847. }
  106848. }
  106849. return 0;
  106850. }
  106851. /*
  106852. ** Return a bitmask where 1s indicate that the corresponding column of
  106853. ** the table is used by an index. Only the first 63 columns are considered.
  106854. */
  106855. static Bitmask columnsInIndex(Index *pIdx){
  106856. Bitmask m = 0;
  106857. int j;
  106858. for(j=pIdx->nColumn-1; j>=0; j--){
  106859. int x = pIdx->aiColumn[j];
  106860. assert( x>=0 );
  106861. testcase( x==BMS-1 );
  106862. testcase( x==BMS-2 );
  106863. if( x<BMS-1 ) m |= MASKBIT(x);
  106864. }
  106865. return m;
  106866. }
  106867. /* Check to see if a partial index with pPartIndexWhere can be used
  106868. ** in the current query. Return true if it can be and false if not.
  106869. */
  106870. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  106871. int i;
  106872. WhereTerm *pTerm;
  106873. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  106874. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  106875. }
  106876. return 0;
  106877. }
  106878. /*
  106879. ** Add all WhereLoop objects for a single table of the join where the table
  106880. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  106881. ** a b-tree table, not a virtual table.
  106882. */
  106883. static int whereLoopAddBtree(
  106884. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  106885. Bitmask mExtra /* Extra prerequesites for using this table */
  106886. ){
  106887. WhereInfo *pWInfo; /* WHERE analysis context */
  106888. Index *pProbe; /* An index we are evaluating */
  106889. Index sPk; /* A fake index object for the primary key */
  106890. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  106891. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  106892. SrcList *pTabList; /* The FROM clause */
  106893. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  106894. WhereLoop *pNew; /* Template WhereLoop object */
  106895. int rc = SQLITE_OK; /* Return code */
  106896. int iSortIdx = 1; /* Index number */
  106897. int b; /* A boolean value */
  106898. LogEst rSize; /* number of rows in the table */
  106899. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  106900. WhereClause *pWC; /* The parsed WHERE clause */
  106901. Table *pTab; /* Table being queried */
  106902. pNew = pBuilder->pNew;
  106903. pWInfo = pBuilder->pWInfo;
  106904. pTabList = pWInfo->pTabList;
  106905. pSrc = pTabList->a + pNew->iTab;
  106906. pTab = pSrc->pTab;
  106907. pWC = pBuilder->pWC;
  106908. assert( !IsVirtual(pSrc->pTab) );
  106909. if( pSrc->pIndex ){
  106910. /* An INDEXED BY clause specifies a particular index to use */
  106911. pProbe = pSrc->pIndex;
  106912. }else{
  106913. /* There is no INDEXED BY clause. Create a fake Index object in local
  106914. ** variable sPk to represent the rowid primary key index. Make this
  106915. ** fake index the first in a chain of Index objects with all of the real
  106916. ** indices to follow */
  106917. Index *pFirst; /* First of real indices on the table */
  106918. memset(&sPk, 0, sizeof(Index));
  106919. sPk.nColumn = 1;
  106920. sPk.aiColumn = &aiColumnPk;
  106921. sPk.aiRowEst = aiRowEstPk;
  106922. sPk.onError = OE_Replace;
  106923. sPk.pTable = pTab;
  106924. aiRowEstPk[0] = pTab->nRowEst;
  106925. aiRowEstPk[1] = 1;
  106926. pFirst = pSrc->pTab->pIndex;
  106927. if( pSrc->notIndexed==0 ){
  106928. /* The real indices of the table are only considered if the
  106929. ** NOT INDEXED qualifier is omitted from the FROM clause */
  106930. sPk.pNext = pFirst;
  106931. }
  106932. pProbe = &sPk;
  106933. }
  106934. rSize = sqlite3LogEst(pTab->nRowEst);
  106935. rLogSize = estLog(rSize);
  106936. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  106937. /* Automatic indexes */
  106938. if( !pBuilder->pOrSet
  106939. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  106940. && pSrc->pIndex==0
  106941. && !pSrc->viaCoroutine
  106942. && !pSrc->notIndexed
  106943. && !pSrc->isCorrelated
  106944. ){
  106945. /* Generate auto-index WhereLoops */
  106946. WhereTerm *pTerm;
  106947. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  106948. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  106949. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  106950. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  106951. pNew->u.btree.nEq = 1;
  106952. pNew->u.btree.pIndex = 0;
  106953. pNew->nLTerm = 1;
  106954. pNew->aLTerm[0] = pTerm;
  106955. /* TUNING: One-time cost for computing the automatic index is
  106956. ** approximately 7*N*log2(N) where N is the number of rows in
  106957. ** the table being indexed. */
  106958. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  106959. /* TUNING: Each index lookup yields 20 rows in the table. This
  106960. ** is more than the usual guess of 10 rows, since we have no way
  106961. ** of knowning how selective the index will ultimately be. It would
  106962. ** not be unreasonable to make this value much larger. */
  106963. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  106964. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  106965. pNew->wsFlags = WHERE_AUTO_INDEX;
  106966. pNew->prereq = mExtra | pTerm->prereqRight;
  106967. rc = whereLoopInsert(pBuilder, pNew);
  106968. }
  106969. }
  106970. }
  106971. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  106972. /* Loop over all indices
  106973. */
  106974. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  106975. if( pProbe->pPartIdxWhere!=0
  106976. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  106977. continue; /* Partial index inappropriate for this query */
  106978. }
  106979. pNew->u.btree.nEq = 0;
  106980. pNew->nLTerm = 0;
  106981. pNew->iSortIdx = 0;
  106982. pNew->rSetup = 0;
  106983. pNew->prereq = mExtra;
  106984. pNew->nOut = rSize;
  106985. pNew->u.btree.pIndex = pProbe;
  106986. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  106987. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  106988. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  106989. if( pProbe->tnum<=0 ){
  106990. /* Integer primary key index */
  106991. pNew->wsFlags = WHERE_IPK;
  106992. /* Full table scan */
  106993. pNew->iSortIdx = b ? iSortIdx : 0;
  106994. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  106995. ** + The extra 3 factor is to encourage the use of indexed lookups
  106996. ** over full scans. FIXME */
  106997. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  106998. whereLoopOutputAdjust(pWC, pNew);
  106999. rc = whereLoopInsert(pBuilder, pNew);
  107000. pNew->nOut = rSize;
  107001. if( rc ) break;
  107002. }else{
  107003. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  107004. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  107005. /* Full scan via index */
  107006. if( b
  107007. || ( m==0
  107008. && pProbe->bUnordered==0
  107009. && pProbe->szIdxRow<pTab->szTabRow
  107010. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  107011. && sqlite3GlobalConfig.bUseCis
  107012. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  107013. )
  107014. ){
  107015. pNew->iSortIdx = b ? iSortIdx : 0;
  107016. if( m==0 ){
  107017. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  107018. ** + The extra factor K of between 1.1 and 3.0 that depends
  107019. ** on the relative sizes of the table and the index. K
  107020. ** is smaller for smaller indices, thus favoring them.
  107021. */
  107022. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  107023. (15*pProbe->szIdxRow)/pTab->szTabRow;
  107024. }else{
  107025. assert( b!=0 );
  107026. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  107027. ** which we will simplify to just N*log2(N) */
  107028. pNew->rRun = rSize + rLogSize;
  107029. }
  107030. whereLoopOutputAdjust(pWC, pNew);
  107031. rc = whereLoopInsert(pBuilder, pNew);
  107032. pNew->nOut = rSize;
  107033. if( rc ) break;
  107034. }
  107035. }
  107036. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  107037. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  107038. sqlite3Stat4ProbeFree(pBuilder->pRec);
  107039. pBuilder->nRecValid = 0;
  107040. pBuilder->pRec = 0;
  107041. #endif
  107042. /* If there was an INDEXED BY clause, then only that one index is
  107043. ** considered. */
  107044. if( pSrc->pIndex ) break;
  107045. }
  107046. return rc;
  107047. }
  107048. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107049. /*
  107050. ** Add all WhereLoop objects for a table of the join identified by
  107051. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  107052. */
  107053. static int whereLoopAddVirtual(
  107054. WhereLoopBuilder *pBuilder /* WHERE clause information */
  107055. ){
  107056. WhereInfo *pWInfo; /* WHERE analysis context */
  107057. Parse *pParse; /* The parsing context */
  107058. WhereClause *pWC; /* The WHERE clause */
  107059. struct SrcList_item *pSrc; /* The FROM clause term to search */
  107060. Table *pTab;
  107061. sqlite3 *db;
  107062. sqlite3_index_info *pIdxInfo;
  107063. struct sqlite3_index_constraint *pIdxCons;
  107064. struct sqlite3_index_constraint_usage *pUsage;
  107065. WhereTerm *pTerm;
  107066. int i, j;
  107067. int iTerm, mxTerm;
  107068. int nConstraint;
  107069. int seenIn = 0; /* True if an IN operator is seen */
  107070. int seenVar = 0; /* True if a non-constant constraint is seen */
  107071. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  107072. WhereLoop *pNew;
  107073. int rc = SQLITE_OK;
  107074. pWInfo = pBuilder->pWInfo;
  107075. pParse = pWInfo->pParse;
  107076. db = pParse->db;
  107077. pWC = pBuilder->pWC;
  107078. pNew = pBuilder->pNew;
  107079. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  107080. pTab = pSrc->pTab;
  107081. assert( IsVirtual(pTab) );
  107082. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  107083. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  107084. pNew->prereq = 0;
  107085. pNew->rSetup = 0;
  107086. pNew->wsFlags = WHERE_VIRTUALTABLE;
  107087. pNew->nLTerm = 0;
  107088. pNew->u.vtab.needFree = 0;
  107089. pUsage = pIdxInfo->aConstraintUsage;
  107090. nConstraint = pIdxInfo->nConstraint;
  107091. if( whereLoopResize(db, pNew, nConstraint) ){
  107092. sqlite3DbFree(db, pIdxInfo);
  107093. return SQLITE_NOMEM;
  107094. }
  107095. for(iPhase=0; iPhase<=3; iPhase++){
  107096. if( !seenIn && (iPhase&1)!=0 ){
  107097. iPhase++;
  107098. if( iPhase>3 ) break;
  107099. }
  107100. if( !seenVar && iPhase>1 ) break;
  107101. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  107102. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  107103. j = pIdxCons->iTermOffset;
  107104. pTerm = &pWC->a[j];
  107105. switch( iPhase ){
  107106. case 0: /* Constants without IN operator */
  107107. pIdxCons->usable = 0;
  107108. if( (pTerm->eOperator & WO_IN)!=0 ){
  107109. seenIn = 1;
  107110. }
  107111. if( pTerm->prereqRight!=0 ){
  107112. seenVar = 1;
  107113. }else if( (pTerm->eOperator & WO_IN)==0 ){
  107114. pIdxCons->usable = 1;
  107115. }
  107116. break;
  107117. case 1: /* Constants with IN operators */
  107118. assert( seenIn );
  107119. pIdxCons->usable = (pTerm->prereqRight==0);
  107120. break;
  107121. case 2: /* Variables without IN */
  107122. assert( seenVar );
  107123. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  107124. break;
  107125. default: /* Variables with IN */
  107126. assert( seenVar && seenIn );
  107127. pIdxCons->usable = 1;
  107128. break;
  107129. }
  107130. }
  107131. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  107132. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  107133. pIdxInfo->idxStr = 0;
  107134. pIdxInfo->idxNum = 0;
  107135. pIdxInfo->needToFreeIdxStr = 0;
  107136. pIdxInfo->orderByConsumed = 0;
  107137. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  107138. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  107139. if( rc ) goto whereLoopAddVtab_exit;
  107140. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  107141. pNew->prereq = 0;
  107142. mxTerm = -1;
  107143. assert( pNew->nLSlot>=nConstraint );
  107144. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  107145. pNew->u.vtab.omitMask = 0;
  107146. for(i=0; i<nConstraint; i++, pIdxCons++){
  107147. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  107148. j = pIdxCons->iTermOffset;
  107149. if( iTerm>=nConstraint
  107150. || j<0
  107151. || j>=pWC->nTerm
  107152. || pNew->aLTerm[iTerm]!=0
  107153. ){
  107154. rc = SQLITE_ERROR;
  107155. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  107156. goto whereLoopAddVtab_exit;
  107157. }
  107158. testcase( iTerm==nConstraint-1 );
  107159. testcase( j==0 );
  107160. testcase( j==pWC->nTerm-1 );
  107161. pTerm = &pWC->a[j];
  107162. pNew->prereq |= pTerm->prereqRight;
  107163. assert( iTerm<pNew->nLSlot );
  107164. pNew->aLTerm[iTerm] = pTerm;
  107165. if( iTerm>mxTerm ) mxTerm = iTerm;
  107166. testcase( iTerm==15 );
  107167. testcase( iTerm==16 );
  107168. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  107169. if( (pTerm->eOperator & WO_IN)!=0 ){
  107170. if( pUsage[i].omit==0 ){
  107171. /* Do not attempt to use an IN constraint if the virtual table
  107172. ** says that the equivalent EQ constraint cannot be safely omitted.
  107173. ** If we do attempt to use such a constraint, some rows might be
  107174. ** repeated in the output. */
  107175. break;
  107176. }
  107177. /* A virtual table that is constrained by an IN clause may not
  107178. ** consume the ORDER BY clause because (1) the order of IN terms
  107179. ** is not necessarily related to the order of output terms and
  107180. ** (2) Multiple outputs from a single IN value will not merge
  107181. ** together. */
  107182. pIdxInfo->orderByConsumed = 0;
  107183. }
  107184. }
  107185. }
  107186. if( i>=nConstraint ){
  107187. pNew->nLTerm = mxTerm+1;
  107188. assert( pNew->nLTerm<=pNew->nLSlot );
  107189. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  107190. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  107191. pIdxInfo->needToFreeIdxStr = 0;
  107192. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  107193. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  107194. && pIdxInfo->orderByConsumed);
  107195. pNew->rSetup = 0;
  107196. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  107197. /* TUNING: Every virtual table query returns 25 rows */
  107198. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  107199. whereLoopInsert(pBuilder, pNew);
  107200. if( pNew->u.vtab.needFree ){
  107201. sqlite3_free(pNew->u.vtab.idxStr);
  107202. pNew->u.vtab.needFree = 0;
  107203. }
  107204. }
  107205. }
  107206. whereLoopAddVtab_exit:
  107207. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  107208. sqlite3DbFree(db, pIdxInfo);
  107209. return rc;
  107210. }
  107211. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107212. /*
  107213. ** Add WhereLoop entries to handle OR terms. This works for either
  107214. ** btrees or virtual tables.
  107215. */
  107216. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  107217. WhereInfo *pWInfo = pBuilder->pWInfo;
  107218. WhereClause *pWC;
  107219. WhereLoop *pNew;
  107220. WhereTerm *pTerm, *pWCEnd;
  107221. int rc = SQLITE_OK;
  107222. int iCur;
  107223. WhereClause tempWC;
  107224. WhereLoopBuilder sSubBuild;
  107225. WhereOrSet sSum, sCur, sPrev;
  107226. struct SrcList_item *pItem;
  107227. pWC = pBuilder->pWC;
  107228. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  107229. pWCEnd = pWC->a + pWC->nTerm;
  107230. pNew = pBuilder->pNew;
  107231. memset(&sSum, 0, sizeof(sSum));
  107232. pItem = pWInfo->pTabList->a + pNew->iTab;
  107233. iCur = pItem->iCursor;
  107234. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  107235. if( (pTerm->eOperator & WO_OR)!=0
  107236. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  107237. ){
  107238. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  107239. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  107240. WhereTerm *pOrTerm;
  107241. int once = 1;
  107242. int i, j;
  107243. sSubBuild = *pBuilder;
  107244. sSubBuild.pOrderBy = 0;
  107245. sSubBuild.pOrSet = &sCur;
  107246. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  107247. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  107248. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  107249. }else if( pOrTerm->leftCursor==iCur ){
  107250. tempWC.pWInfo = pWC->pWInfo;
  107251. tempWC.pOuter = pWC;
  107252. tempWC.op = TK_AND;
  107253. tempWC.nTerm = 1;
  107254. tempWC.a = pOrTerm;
  107255. sSubBuild.pWC = &tempWC;
  107256. }else{
  107257. continue;
  107258. }
  107259. sCur.n = 0;
  107260. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107261. if( IsVirtual(pItem->pTab) ){
  107262. rc = whereLoopAddVirtual(&sSubBuild);
  107263. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  107264. }else
  107265. #endif
  107266. {
  107267. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  107268. }
  107269. assert( rc==SQLITE_OK || sCur.n==0 );
  107270. if( sCur.n==0 ){
  107271. sSum.n = 0;
  107272. break;
  107273. }else if( once ){
  107274. whereOrMove(&sSum, &sCur);
  107275. once = 0;
  107276. }else{
  107277. whereOrMove(&sPrev, &sSum);
  107278. sSum.n = 0;
  107279. for(i=0; i<sPrev.n; i++){
  107280. for(j=0; j<sCur.n; j++){
  107281. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  107282. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  107283. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  107284. }
  107285. }
  107286. }
  107287. }
  107288. pNew->nLTerm = 1;
  107289. pNew->aLTerm[0] = pTerm;
  107290. pNew->wsFlags = WHERE_MULTI_OR;
  107291. pNew->rSetup = 0;
  107292. pNew->iSortIdx = 0;
  107293. memset(&pNew->u, 0, sizeof(pNew->u));
  107294. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  107295. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  107296. pNew->rRun = sSum.a[i].rRun + 18;
  107297. pNew->nOut = sSum.a[i].nOut;
  107298. pNew->prereq = sSum.a[i].prereq;
  107299. rc = whereLoopInsert(pBuilder, pNew);
  107300. }
  107301. }
  107302. }
  107303. return rc;
  107304. }
  107305. /*
  107306. ** Add all WhereLoop objects for all tables
  107307. */
  107308. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  107309. WhereInfo *pWInfo = pBuilder->pWInfo;
  107310. Bitmask mExtra = 0;
  107311. Bitmask mPrior = 0;
  107312. int iTab;
  107313. SrcList *pTabList = pWInfo->pTabList;
  107314. struct SrcList_item *pItem;
  107315. sqlite3 *db = pWInfo->pParse->db;
  107316. int nTabList = pWInfo->nLevel;
  107317. int rc = SQLITE_OK;
  107318. u8 priorJoinType = 0;
  107319. WhereLoop *pNew;
  107320. /* Loop over the tables in the join, from left to right */
  107321. pNew = pBuilder->pNew;
  107322. whereLoopInit(pNew);
  107323. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  107324. pNew->iTab = iTab;
  107325. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  107326. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  107327. mExtra = mPrior;
  107328. }
  107329. priorJoinType = pItem->jointype;
  107330. if( IsVirtual(pItem->pTab) ){
  107331. rc = whereLoopAddVirtual(pBuilder);
  107332. }else{
  107333. rc = whereLoopAddBtree(pBuilder, mExtra);
  107334. }
  107335. if( rc==SQLITE_OK ){
  107336. rc = whereLoopAddOr(pBuilder, mExtra);
  107337. }
  107338. mPrior |= pNew->maskSelf;
  107339. if( rc || db->mallocFailed ) break;
  107340. }
  107341. whereLoopClear(db, pNew);
  107342. return rc;
  107343. }
  107344. /*
  107345. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  107346. ** parameters) to see if it outputs rows in the requested ORDER BY
  107347. ** (or GROUP BY) without requiring a separate sort operation. Return:
  107348. **
  107349. ** 0: ORDER BY is not satisfied. Sorting required
  107350. ** 1: ORDER BY is satisfied. Omit sorting
  107351. ** -1: Unknown at this time
  107352. **
  107353. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  107354. ** strict. With GROUP BY and DISTINCT the only requirement is that
  107355. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  107356. ** and DISTINT do not require rows to appear in any particular order as long
  107357. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  107358. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  107359. ** pOrderBy terms must be matched in strict left-to-right order.
  107360. */
  107361. static int wherePathSatisfiesOrderBy(
  107362. WhereInfo *pWInfo, /* The WHERE clause */
  107363. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  107364. WherePath *pPath, /* The WherePath to check */
  107365. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  107366. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  107367. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  107368. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  107369. ){
  107370. u8 revSet; /* True if rev is known */
  107371. u8 rev; /* Composite sort order */
  107372. u8 revIdx; /* Index sort order */
  107373. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  107374. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  107375. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  107376. u16 nColumn; /* Number of columns in pIndex */
  107377. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  107378. int iLoop; /* Index of WhereLoop in pPath being processed */
  107379. int i, j; /* Loop counters */
  107380. int iCur; /* Cursor number for current WhereLoop */
  107381. int iColumn; /* A column number within table iCur */
  107382. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  107383. WhereTerm *pTerm; /* A single term of the WHERE clause */
  107384. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  107385. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  107386. Index *pIndex; /* The index associated with pLoop */
  107387. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  107388. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  107389. Bitmask obDone; /* Mask of all ORDER BY terms */
  107390. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  107391. Bitmask ready; /* Mask of inner loops */
  107392. /*
  107393. ** We say the WhereLoop is "one-row" if it generates no more than one
  107394. ** row of output. A WhereLoop is one-row if all of the following are true:
  107395. ** (a) All index columns match with WHERE_COLUMN_EQ.
  107396. ** (b) The index is unique
  107397. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  107398. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  107399. **
  107400. ** We say the WhereLoop is "order-distinct" if the set of columns from
  107401. ** that WhereLoop that are in the ORDER BY clause are different for every
  107402. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  107403. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  107404. ** is not order-distinct. To be order-distinct is not quite the same as being
  107405. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  107406. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  107407. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  107408. **
  107409. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  107410. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  107411. ** automatically order-distinct.
  107412. */
  107413. assert( pOrderBy!=0 );
  107414. /* Sortability of virtual tables is determined by the xBestIndex method
  107415. ** of the virtual table itself */
  107416. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  107417. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  107418. ** no ORDER BY terms */
  107419. return pLast->u.vtab.isOrdered;
  107420. }
  107421. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  107422. nOrderBy = pOrderBy->nExpr;
  107423. testcase( nOrderBy==BMS-1 );
  107424. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  107425. isOrderDistinct = 1;
  107426. obDone = MASKBIT(nOrderBy)-1;
  107427. orderDistinctMask = 0;
  107428. ready = 0;
  107429. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  107430. if( iLoop>0 ) ready |= pLoop->maskSelf;
  107431. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  107432. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  107433. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  107434. /* Mark off any ORDER BY term X that is a column in the table of
  107435. ** the current loop for which there is term in the WHERE
  107436. ** clause of the form X IS NULL or X=? that reference only outer
  107437. ** loops.
  107438. */
  107439. for(i=0; i<nOrderBy; i++){
  107440. if( MASKBIT(i) & obSat ) continue;
  107441. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  107442. if( pOBExpr->op!=TK_COLUMN ) continue;
  107443. if( pOBExpr->iTable!=iCur ) continue;
  107444. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  107445. ~ready, WO_EQ|WO_ISNULL, 0);
  107446. if( pTerm==0 ) continue;
  107447. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  107448. const char *z1, *z2;
  107449. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  107450. if( !pColl ) pColl = db->pDfltColl;
  107451. z1 = pColl->zName;
  107452. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  107453. if( !pColl ) pColl = db->pDfltColl;
  107454. z2 = pColl->zName;
  107455. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  107456. }
  107457. obSat |= MASKBIT(i);
  107458. }
  107459. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  107460. if( pLoop->wsFlags & WHERE_IPK ){
  107461. pIndex = 0;
  107462. nColumn = 0;
  107463. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  107464. return 0;
  107465. }else{
  107466. nColumn = pIndex->nColumn;
  107467. isOrderDistinct = pIndex->onError!=OE_None;
  107468. }
  107469. /* Loop through all columns of the index and deal with the ones
  107470. ** that are not constrained by == or IN.
  107471. */
  107472. rev = revSet = 0;
  107473. distinctColumns = 0;
  107474. for(j=0; j<=nColumn; j++){
  107475. u8 bOnce; /* True to run the ORDER BY search loop */
  107476. /* Skip over == and IS NULL terms */
  107477. if( j<pLoop->u.btree.nEq
  107478. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  107479. ){
  107480. if( i & WO_ISNULL ){
  107481. testcase( isOrderDistinct );
  107482. isOrderDistinct = 0;
  107483. }
  107484. continue;
  107485. }
  107486. /* Get the column number in the table (iColumn) and sort order
  107487. ** (revIdx) for the j-th column of the index.
  107488. */
  107489. if( j<nColumn ){
  107490. /* Normal index columns */
  107491. iColumn = pIndex->aiColumn[j];
  107492. revIdx = pIndex->aSortOrder[j];
  107493. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  107494. }else{
  107495. /* The ROWID column at the end */
  107496. assert( j==nColumn );
  107497. iColumn = -1;
  107498. revIdx = 0;
  107499. }
  107500. /* An unconstrained column that might be NULL means that this
  107501. ** WhereLoop is not well-ordered
  107502. */
  107503. if( isOrderDistinct
  107504. && iColumn>=0
  107505. && j>=pLoop->u.btree.nEq
  107506. && pIndex->pTable->aCol[iColumn].notNull==0
  107507. ){
  107508. isOrderDistinct = 0;
  107509. }
  107510. /* Find the ORDER BY term that corresponds to the j-th column
  107511. ** of the index and and mark that ORDER BY term off
  107512. */
  107513. bOnce = 1;
  107514. isMatch = 0;
  107515. for(i=0; bOnce && i<nOrderBy; i++){
  107516. if( MASKBIT(i) & obSat ) continue;
  107517. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  107518. testcase( wctrlFlags & WHERE_GROUPBY );
  107519. testcase( wctrlFlags & WHERE_DISTINCTBY );
  107520. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  107521. if( pOBExpr->op!=TK_COLUMN ) continue;
  107522. if( pOBExpr->iTable!=iCur ) continue;
  107523. if( pOBExpr->iColumn!=iColumn ) continue;
  107524. if( iColumn>=0 ){
  107525. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  107526. if( !pColl ) pColl = db->pDfltColl;
  107527. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  107528. }
  107529. isMatch = 1;
  107530. break;
  107531. }
  107532. if( isMatch ){
  107533. if( iColumn<0 ){
  107534. testcase( distinctColumns==0 );
  107535. distinctColumns = 1;
  107536. }
  107537. obSat |= MASKBIT(i);
  107538. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  107539. /* Make sure the sort order is compatible in an ORDER BY clause.
  107540. ** Sort order is irrelevant for a GROUP BY clause. */
  107541. if( revSet ){
  107542. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  107543. }else{
  107544. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  107545. if( rev ) *pRevMask |= MASKBIT(iLoop);
  107546. revSet = 1;
  107547. }
  107548. }
  107549. }else{
  107550. /* No match found */
  107551. if( j==0 || j<nColumn ){
  107552. testcase( isOrderDistinct!=0 );
  107553. isOrderDistinct = 0;
  107554. }
  107555. break;
  107556. }
  107557. } /* end Loop over all index columns */
  107558. if( distinctColumns ){
  107559. testcase( isOrderDistinct==0 );
  107560. isOrderDistinct = 1;
  107561. }
  107562. } /* end-if not one-row */
  107563. /* Mark off any other ORDER BY terms that reference pLoop */
  107564. if( isOrderDistinct ){
  107565. orderDistinctMask |= pLoop->maskSelf;
  107566. for(i=0; i<nOrderBy; i++){
  107567. Expr *p;
  107568. if( MASKBIT(i) & obSat ) continue;
  107569. p = pOrderBy->a[i].pExpr;
  107570. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  107571. obSat |= MASKBIT(i);
  107572. }
  107573. }
  107574. }
  107575. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  107576. if( obSat==obDone ) return 1;
  107577. if( !isOrderDistinct ) return 0;
  107578. return -1;
  107579. }
  107580. #ifdef WHERETRACE_ENABLED
  107581. /* For debugging use only: */
  107582. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  107583. static char zName[65];
  107584. int i;
  107585. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  107586. if( pLast ) zName[i++] = pLast->cId;
  107587. zName[i] = 0;
  107588. return zName;
  107589. }
  107590. #endif
  107591. /*
  107592. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  107593. ** attempts to find the lowest cost path that visits each WhereLoop
  107594. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  107595. **
  107596. ** Assume that the total number of output rows that will need to be sorted
  107597. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  107598. ** costs if nRowEst==0.
  107599. **
  107600. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  107601. ** error occurs.
  107602. */
  107603. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  107604. int mxChoice; /* Maximum number of simultaneous paths tracked */
  107605. int nLoop; /* Number of terms in the join */
  107606. Parse *pParse; /* Parsing context */
  107607. sqlite3 *db; /* The database connection */
  107608. int iLoop; /* Loop counter over the terms of the join */
  107609. int ii, jj; /* Loop counters */
  107610. int mxI = 0; /* Index of next entry to replace */
  107611. LogEst rCost; /* Cost of a path */
  107612. LogEst nOut; /* Number of outputs */
  107613. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  107614. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  107615. LogEst rSortCost; /* Cost to do a sort */
  107616. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  107617. WherePath *aFrom; /* All nFrom paths at the previous level */
  107618. WherePath *aTo; /* The nTo best paths at the current level */
  107619. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  107620. WherePath *pTo; /* An element of aTo[] that we are working on */
  107621. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  107622. WhereLoop **pX; /* Used to divy up the pSpace memory */
  107623. char *pSpace; /* Temporary memory used by this routine */
  107624. pParse = pWInfo->pParse;
  107625. db = pParse->db;
  107626. nLoop = pWInfo->nLevel;
  107627. /* TUNING: For simple queries, only the best path is tracked.
  107628. ** For 2-way joins, the 5 best paths are followed.
  107629. ** For joins of 3 or more tables, track the 10 best paths */
  107630. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  107631. assert( nLoop<=pWInfo->pTabList->nSrc );
  107632. WHERETRACE(0x002, ("---- begin solver\n"));
  107633. /* Allocate and initialize space for aTo and aFrom */
  107634. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  107635. pSpace = sqlite3DbMallocRaw(db, ii);
  107636. if( pSpace==0 ) return SQLITE_NOMEM;
  107637. aTo = (WherePath*)pSpace;
  107638. aFrom = aTo+mxChoice;
  107639. memset(aFrom, 0, sizeof(aFrom[0]));
  107640. pX = (WhereLoop**)(aFrom+mxChoice);
  107641. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  107642. pFrom->aLoop = pX;
  107643. }
  107644. /* Seed the search with a single WherePath containing zero WhereLoops.
  107645. **
  107646. ** TUNING: Do not let the number of iterations go above 25. If the cost
  107647. ** of computing an automatic index is not paid back within the first 25
  107648. ** rows, then do not use the automatic index. */
  107649. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  107650. nFrom = 1;
  107651. /* Precompute the cost of sorting the final result set, if the caller
  107652. ** to sqlite3WhereBegin() was concerned about sorting */
  107653. rSortCost = 0;
  107654. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  107655. aFrom[0].isOrderedValid = 1;
  107656. }else{
  107657. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  107658. ** number of output rows. The 48 is the expected size of a row to sort.
  107659. ** FIXME: compute a better estimate of the 48 multiplier based on the
  107660. ** result set expressions. */
  107661. rSortCost = nRowEst + estLog(nRowEst);
  107662. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  107663. }
  107664. /* Compute successively longer WherePaths using the previous generation
  107665. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  107666. ** best paths at each generation */
  107667. for(iLoop=0; iLoop<nLoop; iLoop++){
  107668. nTo = 0;
  107669. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  107670. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  107671. Bitmask maskNew;
  107672. Bitmask revMask = 0;
  107673. u8 isOrderedValid = pFrom->isOrderedValid;
  107674. u8 isOrdered = pFrom->isOrdered;
  107675. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  107676. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  107677. /* At this point, pWLoop is a candidate to be the next loop.
  107678. ** Compute its cost */
  107679. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  107680. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  107681. nOut = pFrom->nRow + pWLoop->nOut;
  107682. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  107683. if( !isOrderedValid ){
  107684. switch( wherePathSatisfiesOrderBy(pWInfo,
  107685. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  107686. iLoop, pWLoop, &revMask) ){
  107687. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  107688. isOrdered = 1;
  107689. isOrderedValid = 1;
  107690. break;
  107691. case 0: /* No. pFrom+pWLoop will require a separate sort */
  107692. isOrdered = 0;
  107693. isOrderedValid = 1;
  107694. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  107695. break;
  107696. default: /* Cannot tell yet. Try again on the next iteration */
  107697. break;
  107698. }
  107699. }else{
  107700. revMask = pFrom->revLoop;
  107701. }
  107702. /* Check to see if pWLoop should be added to the mxChoice best so far */
  107703. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  107704. if( pTo->maskLoop==maskNew
  107705. && pTo->isOrderedValid==isOrderedValid
  107706. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  107707. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  107708. ){
  107709. testcase( jj==nTo-1 );
  107710. break;
  107711. }
  107712. }
  107713. if( jj>=nTo ){
  107714. if( nTo>=mxChoice && rCost>=mxCost ){
  107715. #ifdef WHERETRACE_ENABLED
  107716. if( sqlite3WhereTrace&0x4 ){
  107717. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  107718. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107719. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107720. }
  107721. #endif
  107722. continue;
  107723. }
  107724. /* Add a new Path to the aTo[] set */
  107725. if( nTo<mxChoice ){
  107726. /* Increase the size of the aTo set by one */
  107727. jj = nTo++;
  107728. }else{
  107729. /* New path replaces the prior worst to keep count below mxChoice */
  107730. jj = mxI;
  107731. }
  107732. pTo = &aTo[jj];
  107733. #ifdef WHERETRACE_ENABLED
  107734. if( sqlite3WhereTrace&0x4 ){
  107735. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  107736. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107737. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107738. }
  107739. #endif
  107740. }else{
  107741. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  107742. #ifdef WHERETRACE_ENABLED
  107743. if( sqlite3WhereTrace&0x4 ){
  107744. sqlite3DebugPrintf(
  107745. "Skip %s cost=%-3d,%3d order=%c",
  107746. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107747. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107748. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  107749. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107750. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107751. }
  107752. #endif
  107753. testcase( pTo->rCost==rCost );
  107754. continue;
  107755. }
  107756. testcase( pTo->rCost==rCost+1 );
  107757. /* A new and better score for a previously created equivalent path */
  107758. #ifdef WHERETRACE_ENABLED
  107759. if( sqlite3WhereTrace&0x4 ){
  107760. sqlite3DebugPrintf(
  107761. "Update %s cost=%-3d,%3d order=%c",
  107762. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107763. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107764. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  107765. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107766. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107767. }
  107768. #endif
  107769. }
  107770. /* pWLoop is a winner. Add it to the set of best so far */
  107771. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  107772. pTo->revLoop = revMask;
  107773. pTo->nRow = nOut;
  107774. pTo->rCost = rCost;
  107775. pTo->isOrderedValid = isOrderedValid;
  107776. pTo->isOrdered = isOrdered;
  107777. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  107778. pTo->aLoop[iLoop] = pWLoop;
  107779. if( nTo>=mxChoice ){
  107780. mxI = 0;
  107781. mxCost = aTo[0].rCost;
  107782. mxOut = aTo[0].nRow;
  107783. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  107784. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  107785. mxCost = pTo->rCost;
  107786. mxOut = pTo->nRow;
  107787. mxI = jj;
  107788. }
  107789. }
  107790. }
  107791. }
  107792. }
  107793. #ifdef WHERETRACE_ENABLED
  107794. if( sqlite3WhereTrace>=2 ){
  107795. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  107796. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  107797. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  107798. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107799. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107800. if( pTo->isOrderedValid && pTo->isOrdered ){
  107801. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  107802. }else{
  107803. sqlite3DebugPrintf("\n");
  107804. }
  107805. }
  107806. }
  107807. #endif
  107808. /* Swap the roles of aFrom and aTo for the next generation */
  107809. pFrom = aTo;
  107810. aTo = aFrom;
  107811. aFrom = pFrom;
  107812. nFrom = nTo;
  107813. }
  107814. if( nFrom==0 ){
  107815. sqlite3ErrorMsg(pParse, "no query solution");
  107816. sqlite3DbFree(db, pSpace);
  107817. return SQLITE_ERROR;
  107818. }
  107819. /* Find the lowest cost path. pFrom will be left pointing to that path */
  107820. pFrom = aFrom;
  107821. for(ii=1; ii<nFrom; ii++){
  107822. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  107823. }
  107824. assert( pWInfo->nLevel==nLoop );
  107825. /* Load the lowest cost path into pWInfo */
  107826. for(iLoop=0; iLoop<nLoop; iLoop++){
  107827. WhereLevel *pLevel = pWInfo->a + iLoop;
  107828. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  107829. pLevel->iFrom = pWLoop->iTab;
  107830. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  107831. }
  107832. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  107833. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  107834. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  107835. && nRowEst
  107836. ){
  107837. Bitmask notUsed;
  107838. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  107839. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  107840. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  107841. }
  107842. if( pFrom->isOrdered ){
  107843. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  107844. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  107845. }else{
  107846. pWInfo->bOBSat = 1;
  107847. pWInfo->revMask = pFrom->revLoop;
  107848. }
  107849. }
  107850. pWInfo->nRowOut = pFrom->nRow;
  107851. /* Free temporary memory and return success */
  107852. sqlite3DbFree(db, pSpace);
  107853. return SQLITE_OK;
  107854. }
  107855. /*
  107856. ** Most queries use only a single table (they are not joins) and have
  107857. ** simple == constraints against indexed fields. This routine attempts
  107858. ** to plan those simple cases using much less ceremony than the
  107859. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  107860. ** times for the common case.
  107861. **
  107862. ** Return non-zero on success, if this query can be handled by this
  107863. ** no-frills query planner. Return zero if this query needs the
  107864. ** general-purpose query planner.
  107865. */
  107866. static int whereShortCut(WhereLoopBuilder *pBuilder){
  107867. WhereInfo *pWInfo;
  107868. struct SrcList_item *pItem;
  107869. WhereClause *pWC;
  107870. WhereTerm *pTerm;
  107871. WhereLoop *pLoop;
  107872. int iCur;
  107873. int j;
  107874. Table *pTab;
  107875. Index *pIdx;
  107876. pWInfo = pBuilder->pWInfo;
  107877. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  107878. assert( pWInfo->pTabList->nSrc>=1 );
  107879. pItem = pWInfo->pTabList->a;
  107880. pTab = pItem->pTab;
  107881. if( IsVirtual(pTab) ) return 0;
  107882. if( pItem->zIndex ) return 0;
  107883. iCur = pItem->iCursor;
  107884. pWC = &pWInfo->sWC;
  107885. pLoop = pBuilder->pNew;
  107886. pLoop->wsFlags = 0;
  107887. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  107888. if( pTerm ){
  107889. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  107890. pLoop->aLTerm[0] = pTerm;
  107891. pLoop->nLTerm = 1;
  107892. pLoop->u.btree.nEq = 1;
  107893. /* TUNING: Cost of a rowid lookup is 10 */
  107894. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  107895. }else{
  107896. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107897. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  107898. assert( ArraySize(pLoop->aLTermSpace)==4 );
  107899. if( pIdx->onError==OE_None
  107900. || pIdx->pPartIdxWhere!=0
  107901. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  107902. ) continue;
  107903. for(j=0; j<pIdx->nColumn; j++){
  107904. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  107905. if( pTerm==0 ) break;
  107906. pLoop->aLTerm[j] = pTerm;
  107907. }
  107908. if( j!=pIdx->nColumn ) continue;
  107909. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  107910. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  107911. pLoop->wsFlags |= WHERE_IDX_ONLY;
  107912. }
  107913. pLoop->nLTerm = j;
  107914. pLoop->u.btree.nEq = j;
  107915. pLoop->u.btree.pIndex = pIdx;
  107916. /* TUNING: Cost of a unique index lookup is 15 */
  107917. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  107918. break;
  107919. }
  107920. }
  107921. if( pLoop->wsFlags ){
  107922. pLoop->nOut = (LogEst)1;
  107923. pWInfo->a[0].pWLoop = pLoop;
  107924. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  107925. pWInfo->a[0].iTabCur = iCur;
  107926. pWInfo->nRowOut = 1;
  107927. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  107928. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  107929. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  107930. }
  107931. #ifdef SQLITE_DEBUG
  107932. pLoop->cId = '0';
  107933. #endif
  107934. return 1;
  107935. }
  107936. return 0;
  107937. }
  107938. /*
  107939. ** Generate the beginning of the loop used for WHERE clause processing.
  107940. ** The return value is a pointer to an opaque structure that contains
  107941. ** information needed to terminate the loop. Later, the calling routine
  107942. ** should invoke sqlite3WhereEnd() with the return value of this function
  107943. ** in order to complete the WHERE clause processing.
  107944. **
  107945. ** If an error occurs, this routine returns NULL.
  107946. **
  107947. ** The basic idea is to do a nested loop, one loop for each table in
  107948. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  107949. ** same as a SELECT with only a single table in the FROM clause.) For
  107950. ** example, if the SQL is this:
  107951. **
  107952. ** SELECT * FROM t1, t2, t3 WHERE ...;
  107953. **
  107954. ** Then the code generated is conceptually like the following:
  107955. **
  107956. ** foreach row1 in t1 do \ Code generated
  107957. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  107958. ** foreach row3 in t3 do /
  107959. ** ...
  107960. ** end \ Code generated
  107961. ** end |-- by sqlite3WhereEnd()
  107962. ** end /
  107963. **
  107964. ** Note that the loops might not be nested in the order in which they
  107965. ** appear in the FROM clause if a different order is better able to make
  107966. ** use of indices. Note also that when the IN operator appears in
  107967. ** the WHERE clause, it might result in additional nested loops for
  107968. ** scanning through all values on the right-hand side of the IN.
  107969. **
  107970. ** There are Btree cursors associated with each table. t1 uses cursor
  107971. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  107972. ** And so forth. This routine generates code to open those VDBE cursors
  107973. ** and sqlite3WhereEnd() generates the code to close them.
  107974. **
  107975. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  107976. ** in pTabList pointing at their appropriate entries. The [...] code
  107977. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  107978. ** data from the various tables of the loop.
  107979. **
  107980. ** If the WHERE clause is empty, the foreach loops must each scan their
  107981. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  107982. ** the tables have indices and there are terms in the WHERE clause that
  107983. ** refer to those indices, a complete table scan can be avoided and the
  107984. ** code will run much faster. Most of the work of this routine is checking
  107985. ** to see if there are indices that can be used to speed up the loop.
  107986. **
  107987. ** Terms of the WHERE clause are also used to limit which rows actually
  107988. ** make it to the "..." in the middle of the loop. After each "foreach",
  107989. ** terms of the WHERE clause that use only terms in that loop and outer
  107990. ** loops are evaluated and if false a jump is made around all subsequent
  107991. ** inner loops (or around the "..." if the test occurs within the inner-
  107992. ** most loop)
  107993. **
  107994. ** OUTER JOINS
  107995. **
  107996. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  107997. **
  107998. ** foreach row1 in t1 do
  107999. ** flag = 0
  108000. ** foreach row2 in t2 do
  108001. ** start:
  108002. ** ...
  108003. ** flag = 1
  108004. ** end
  108005. ** if flag==0 then
  108006. ** move the row2 cursor to a null row
  108007. ** goto start
  108008. ** fi
  108009. ** end
  108010. **
  108011. ** ORDER BY CLAUSE PROCESSING
  108012. **
  108013. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  108014. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  108015. ** if there is one. If there is no ORDER BY clause or if this routine
  108016. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  108017. */
  108018. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  108019. Parse *pParse, /* The parser context */
  108020. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  108021. Expr *pWhere, /* The WHERE clause */
  108022. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  108023. ExprList *pResultSet, /* Result set of the query */
  108024. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  108025. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  108026. ){
  108027. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  108028. int nTabList; /* Number of elements in pTabList */
  108029. WhereInfo *pWInfo; /* Will become the return value of this function */
  108030. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  108031. Bitmask notReady; /* Cursors that are not yet positioned */
  108032. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  108033. WhereMaskSet *pMaskSet; /* The expression mask set */
  108034. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  108035. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  108036. int ii; /* Loop counter */
  108037. sqlite3 *db; /* Database connection */
  108038. int rc; /* Return code */
  108039. /* Variable initialization */
  108040. db = pParse->db;
  108041. memset(&sWLB, 0, sizeof(sWLB));
  108042. sWLB.pOrderBy = pOrderBy;
  108043. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  108044. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  108045. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  108046. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  108047. }
  108048. /* The number of tables in the FROM clause is limited by the number of
  108049. ** bits in a Bitmask
  108050. */
  108051. testcase( pTabList->nSrc==BMS );
  108052. if( pTabList->nSrc>BMS ){
  108053. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  108054. return 0;
  108055. }
  108056. /* This function normally generates a nested loop for all tables in
  108057. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  108058. ** only generate code for the first table in pTabList and assume that
  108059. ** any cursors associated with subsequent tables are uninitialized.
  108060. */
  108061. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  108062. /* Allocate and initialize the WhereInfo structure that will become the
  108063. ** return value. A single allocation is used to store the WhereInfo
  108064. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  108065. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  108066. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  108067. ** some architectures. Hence the ROUND8() below.
  108068. */
  108069. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  108070. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  108071. if( db->mallocFailed ){
  108072. sqlite3DbFree(db, pWInfo);
  108073. pWInfo = 0;
  108074. goto whereBeginError;
  108075. }
  108076. pWInfo->nLevel = nTabList;
  108077. pWInfo->pParse = pParse;
  108078. pWInfo->pTabList = pTabList;
  108079. pWInfo->pOrderBy = pOrderBy;
  108080. pWInfo->pResultSet = pResultSet;
  108081. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  108082. pWInfo->wctrlFlags = wctrlFlags;
  108083. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  108084. pMaskSet = &pWInfo->sMaskSet;
  108085. sWLB.pWInfo = pWInfo;
  108086. sWLB.pWC = &pWInfo->sWC;
  108087. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  108088. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  108089. whereLoopInit(sWLB.pNew);
  108090. #ifdef SQLITE_DEBUG
  108091. sWLB.pNew->cId = '*';
  108092. #endif
  108093. /* Split the WHERE clause into separate subexpressions where each
  108094. ** subexpression is separated by an AND operator.
  108095. */
  108096. initMaskSet(pMaskSet);
  108097. whereClauseInit(&pWInfo->sWC, pWInfo);
  108098. sqlite3ExprCodeConstants(pParse, pWhere);
  108099. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  108100. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  108101. /* Special case: a WHERE clause that is constant. Evaluate the
  108102. ** expression and either jump over all of the code or fall thru.
  108103. */
  108104. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  108105. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  108106. pWhere = 0;
  108107. }
  108108. /* Special case: No FROM clause
  108109. */
  108110. if( nTabList==0 ){
  108111. if( pOrderBy ) pWInfo->bOBSat = 1;
  108112. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  108113. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  108114. }
  108115. }
  108116. /* Assign a bit from the bitmask to every term in the FROM clause.
  108117. **
  108118. ** When assigning bitmask values to FROM clause cursors, it must be
  108119. ** the case that if X is the bitmask for the N-th FROM clause term then
  108120. ** the bitmask for all FROM clause terms to the left of the N-th term
  108121. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  108122. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  108123. ** of the join. Subtracting one from the right table bitmask gives a
  108124. ** bitmask for all tables to the left of the join. Knowing the bitmask
  108125. ** for all tables to the left of a left join is important. Ticket #3015.
  108126. **
  108127. ** Note that bitmasks are created for all pTabList->nSrc tables in
  108128. ** pTabList, not just the first nTabList tables. nTabList is normally
  108129. ** equal to pTabList->nSrc but might be shortened to 1 if the
  108130. ** WHERE_ONETABLE_ONLY flag is set.
  108131. */
  108132. for(ii=0; ii<pTabList->nSrc; ii++){
  108133. createMask(pMaskSet, pTabList->a[ii].iCursor);
  108134. }
  108135. #ifndef NDEBUG
  108136. {
  108137. Bitmask toTheLeft = 0;
  108138. for(ii=0; ii<pTabList->nSrc; ii++){
  108139. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  108140. assert( (m-1)==toTheLeft );
  108141. toTheLeft |= m;
  108142. }
  108143. }
  108144. #endif
  108145. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  108146. ** add new virtual terms onto the end of the WHERE clause. We do not
  108147. ** want to analyze these virtual terms, so start analyzing at the end
  108148. ** and work forward so that the added virtual terms are never processed.
  108149. */
  108150. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  108151. if( db->mallocFailed ){
  108152. goto whereBeginError;
  108153. }
  108154. /* If the ORDER BY (or GROUP BY) clause contains references to general
  108155. ** expressions, then we won't be able to satisfy it using indices, so
  108156. ** go ahead and disable it now.
  108157. */
  108158. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  108159. for(ii=0; ii<pOrderBy->nExpr; ii++){
  108160. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  108161. if( pExpr->op!=TK_COLUMN ){
  108162. pWInfo->pOrderBy = pOrderBy = 0;
  108163. break;
  108164. }else if( pExpr->iColumn<0 ){
  108165. break;
  108166. }
  108167. }
  108168. }
  108169. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  108170. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  108171. /* The DISTINCT marking is pointless. Ignore it. */
  108172. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  108173. }else if( pOrderBy==0 ){
  108174. /* Try to ORDER BY the result set to make distinct processing easier */
  108175. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  108176. pWInfo->pOrderBy = pResultSet;
  108177. }
  108178. }
  108179. /* Construct the WhereLoop objects */
  108180. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  108181. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  108182. rc = whereLoopAddAll(&sWLB);
  108183. if( rc ) goto whereBeginError;
  108184. /* Display all of the WhereLoop objects if wheretrace is enabled */
  108185. #ifdef WHERETRACE_ENABLED
  108186. if( sqlite3WhereTrace ){
  108187. WhereLoop *p;
  108188. int i;
  108189. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  108190. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  108191. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  108192. p->cId = zLabel[i%sizeof(zLabel)];
  108193. whereLoopPrint(p, pTabList);
  108194. }
  108195. }
  108196. #endif
  108197. wherePathSolver(pWInfo, 0);
  108198. if( db->mallocFailed ) goto whereBeginError;
  108199. if( pWInfo->pOrderBy ){
  108200. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  108201. if( db->mallocFailed ) goto whereBeginError;
  108202. }
  108203. }
  108204. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  108205. pWInfo->revMask = (Bitmask)(-1);
  108206. }
  108207. if( pParse->nErr || NEVER(db->mallocFailed) ){
  108208. goto whereBeginError;
  108209. }
  108210. #ifdef WHERETRACE_ENABLED
  108211. if( sqlite3WhereTrace ){
  108212. int ii;
  108213. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  108214. if( pWInfo->bOBSat ){
  108215. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  108216. }
  108217. switch( pWInfo->eDistinct ){
  108218. case WHERE_DISTINCT_UNIQUE: {
  108219. sqlite3DebugPrintf(" DISTINCT=unique");
  108220. break;
  108221. }
  108222. case WHERE_DISTINCT_ORDERED: {
  108223. sqlite3DebugPrintf(" DISTINCT=ordered");
  108224. break;
  108225. }
  108226. case WHERE_DISTINCT_UNORDERED: {
  108227. sqlite3DebugPrintf(" DISTINCT=unordered");
  108228. break;
  108229. }
  108230. }
  108231. sqlite3DebugPrintf("\n");
  108232. for(ii=0; ii<pWInfo->nLevel; ii++){
  108233. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  108234. }
  108235. }
  108236. #endif
  108237. /* Attempt to omit tables from the join that do not effect the result */
  108238. if( pWInfo->nLevel>=2
  108239. && pResultSet!=0
  108240. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  108241. ){
  108242. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  108243. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  108244. while( pWInfo->nLevel>=2 ){
  108245. WhereTerm *pTerm, *pEnd;
  108246. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  108247. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  108248. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  108249. && (pLoop->wsFlags & WHERE_ONEROW)==0
  108250. ){
  108251. break;
  108252. }
  108253. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  108254. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  108255. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  108256. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  108257. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  108258. ){
  108259. break;
  108260. }
  108261. }
  108262. if( pTerm<pEnd ) break;
  108263. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  108264. pWInfo->nLevel--;
  108265. nTabList--;
  108266. }
  108267. }
  108268. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  108269. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  108270. /* If the caller is an UPDATE or DELETE statement that is requesting
  108271. ** to use a one-pass algorithm, determine if this is appropriate.
  108272. ** The one-pass algorithm only works if the WHERE clause constrains
  108273. ** the statement to update a single row.
  108274. */
  108275. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  108276. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  108277. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  108278. pWInfo->okOnePass = 1;
  108279. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  108280. }
  108281. /* Open all tables in the pTabList and any indices selected for
  108282. ** searching those tables.
  108283. */
  108284. notReady = ~(Bitmask)0;
  108285. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  108286. Table *pTab; /* Table to open */
  108287. int iDb; /* Index of database containing table/index */
  108288. struct SrcList_item *pTabItem;
  108289. pTabItem = &pTabList->a[pLevel->iFrom];
  108290. pTab = pTabItem->pTab;
  108291. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108292. pLoop = pLevel->pWLoop;
  108293. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  108294. /* Do nothing */
  108295. }else
  108296. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108297. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  108298. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  108299. int iCur = pTabItem->iCursor;
  108300. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  108301. }else if( IsVirtual(pTab) ){
  108302. /* noop */
  108303. }else
  108304. #endif
  108305. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  108306. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  108307. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  108308. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  108309. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  108310. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  108311. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  108312. Bitmask b = pTabItem->colUsed;
  108313. int n = 0;
  108314. for(; b; b=b>>1, n++){}
  108315. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  108316. SQLITE_INT_TO_PTR(n), P4_INT32);
  108317. assert( n<=pTab->nCol );
  108318. }
  108319. }else{
  108320. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  108321. }
  108322. if( pLoop->wsFlags & WHERE_INDEXED ){
  108323. Index *pIx = pLoop->u.btree.pIndex;
  108324. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  108325. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  108326. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  108327. assert( pIx->pSchema==pTab->pSchema );
  108328. assert( iIndexCur>=0 );
  108329. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  108330. (char*)pKey, P4_KEYINFO_HANDOFF);
  108331. VdbeComment((v, "%s", pIx->zName));
  108332. }
  108333. sqlite3CodeVerifySchema(pParse, iDb);
  108334. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  108335. }
  108336. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  108337. if( db->mallocFailed ) goto whereBeginError;
  108338. /* Generate the code to do the search. Each iteration of the for
  108339. ** loop below generates code for a single nested loop of the VM
  108340. ** program.
  108341. */
  108342. notReady = ~(Bitmask)0;
  108343. for(ii=0; ii<nTabList; ii++){
  108344. pLevel = &pWInfo->a[ii];
  108345. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  108346. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  108347. constructAutomaticIndex(pParse, &pWInfo->sWC,
  108348. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  108349. if( db->mallocFailed ) goto whereBeginError;
  108350. }
  108351. #endif
  108352. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  108353. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  108354. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  108355. pWInfo->iContinue = pLevel->addrCont;
  108356. }
  108357. /* Done. */
  108358. return pWInfo;
  108359. /* Jump here if malloc fails */
  108360. whereBeginError:
  108361. if( pWInfo ){
  108362. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  108363. whereInfoFree(db, pWInfo);
  108364. }
  108365. return 0;
  108366. }
  108367. /*
  108368. ** Generate the end of the WHERE loop. See comments on
  108369. ** sqlite3WhereBegin() for additional information.
  108370. */
  108371. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  108372. Parse *pParse = pWInfo->pParse;
  108373. Vdbe *v = pParse->pVdbe;
  108374. int i;
  108375. WhereLevel *pLevel;
  108376. WhereLoop *pLoop;
  108377. SrcList *pTabList = pWInfo->pTabList;
  108378. sqlite3 *db = pParse->db;
  108379. /* Generate loop termination code.
  108380. */
  108381. sqlite3ExprCacheClear(pParse);
  108382. for(i=pWInfo->nLevel-1; i>=0; i--){
  108383. pLevel = &pWInfo->a[i];
  108384. pLoop = pLevel->pWLoop;
  108385. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  108386. if( pLevel->op!=OP_Noop ){
  108387. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  108388. sqlite3VdbeChangeP5(v, pLevel->p5);
  108389. }
  108390. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  108391. struct InLoop *pIn;
  108392. int j;
  108393. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  108394. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  108395. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  108396. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  108397. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  108398. }
  108399. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  108400. }
  108401. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  108402. if( pLevel->iLeftJoin ){
  108403. int addr;
  108404. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  108405. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  108406. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  108407. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  108408. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  108409. }
  108410. if( pLoop->wsFlags & WHERE_INDEXED ){
  108411. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  108412. }
  108413. if( pLevel->op==OP_Return ){
  108414. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  108415. }else{
  108416. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  108417. }
  108418. sqlite3VdbeJumpHere(v, addr);
  108419. }
  108420. }
  108421. /* The "break" point is here, just past the end of the outer loop.
  108422. ** Set it.
  108423. */
  108424. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  108425. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  108426. */
  108427. assert( pWInfo->nLevel<=pTabList->nSrc );
  108428. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  108429. Index *pIdx = 0;
  108430. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  108431. Table *pTab = pTabItem->pTab;
  108432. assert( pTab!=0 );
  108433. pLoop = pLevel->pWLoop;
  108434. if( (pTab->tabFlags & TF_Ephemeral)==0
  108435. && pTab->pSelect==0
  108436. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  108437. ){
  108438. int ws = pLoop->wsFlags;
  108439. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  108440. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  108441. }
  108442. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  108443. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  108444. }
  108445. }
  108446. /* If this scan uses an index, make VDBE code substitutions to read data
  108447. ** from the index instead of from the table where possible. In some cases
  108448. ** this optimization prevents the table from ever being read, which can
  108449. ** yield a significant performance boost.
  108450. **
  108451. ** Calls to the code generator in between sqlite3WhereBegin and
  108452. ** sqlite3WhereEnd will have created code that references the table
  108453. ** directly. This loop scans all that code looking for opcodes
  108454. ** that reference the table and converts them into opcodes that
  108455. ** reference the index.
  108456. */
  108457. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  108458. pIdx = pLoop->u.btree.pIndex;
  108459. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  108460. pIdx = pLevel->u.pCovidx;
  108461. }
  108462. if( pIdx && !db->mallocFailed ){
  108463. int k, j, last;
  108464. VdbeOp *pOp;
  108465. last = sqlite3VdbeCurrentAddr(v);
  108466. k = pLevel->addrBody;
  108467. pOp = sqlite3VdbeGetOp(v, k);
  108468. for(; k<last; k++, pOp++){
  108469. if( pOp->p1!=pLevel->iTabCur ) continue;
  108470. if( pOp->opcode==OP_Column ){
  108471. for(j=0; j<pIdx->nColumn; j++){
  108472. if( pOp->p2==pIdx->aiColumn[j] ){
  108473. pOp->p2 = j;
  108474. pOp->p1 = pLevel->iIdxCur;
  108475. break;
  108476. }
  108477. }
  108478. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  108479. }else if( pOp->opcode==OP_Rowid ){
  108480. pOp->p1 = pLevel->iIdxCur;
  108481. pOp->opcode = OP_IdxRowid;
  108482. }
  108483. }
  108484. }
  108485. }
  108486. /* Final cleanup
  108487. */
  108488. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  108489. whereInfoFree(db, pWInfo);
  108490. return;
  108491. }
  108492. /************** End of where.c ***********************************************/
  108493. /************** Begin file parse.c *******************************************/
  108494. /* Driver template for the LEMON parser generator.
  108495. ** The author disclaims copyright to this source code.
  108496. **
  108497. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  108498. ** The only modifications are the addition of a couple of NEVER()
  108499. ** macros to disable tests that are needed in the case of a general
  108500. ** LALR(1) grammar but which are always false in the
  108501. ** specific grammar used by SQLite.
  108502. */
  108503. /* First off, code is included that follows the "include" declaration
  108504. ** in the input grammar file. */
  108505. /* #include <stdio.h> */
  108506. /*
  108507. ** Disable all error recovery processing in the parser push-down
  108508. ** automaton.
  108509. */
  108510. #define YYNOERRORRECOVERY 1
  108511. /*
  108512. ** Make yytestcase() the same as testcase()
  108513. */
  108514. #define yytestcase(X) testcase(X)
  108515. /*
  108516. ** An instance of this structure holds information about the
  108517. ** LIMIT clause of a SELECT statement.
  108518. */
  108519. struct LimitVal {
  108520. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  108521. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  108522. };
  108523. /*
  108524. ** An instance of this structure is used to store the LIKE,
  108525. ** GLOB, NOT LIKE, and NOT GLOB operators.
  108526. */
  108527. struct LikeOp {
  108528. Token eOperator; /* "like" or "glob" or "regexp" */
  108529. int bNot; /* True if the NOT keyword is present */
  108530. };
  108531. /*
  108532. ** An instance of the following structure describes the event of a
  108533. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  108534. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  108535. **
  108536. ** UPDATE ON (a,b,c)
  108537. **
  108538. ** Then the "b" IdList records the list "a,b,c".
  108539. */
  108540. struct TrigEvent { int a; IdList * b; };
  108541. /*
  108542. ** An instance of this structure holds the ATTACH key and the key type.
  108543. */
  108544. struct AttachKey { int type; Token key; };
  108545. /*
  108546. ** One or more VALUES claues
  108547. */
  108548. struct ValueList {
  108549. ExprList *pList;
  108550. Select *pSelect;
  108551. };
  108552. /* This is a utility routine used to set the ExprSpan.zStart and
  108553. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  108554. ** range of text beginning with pStart and going to the end of pEnd.
  108555. */
  108556. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  108557. pOut->zStart = pStart->z;
  108558. pOut->zEnd = &pEnd->z[pEnd->n];
  108559. }
  108560. /* Construct a new Expr object from a single identifier. Use the
  108561. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  108562. ** that created the expression.
  108563. */
  108564. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  108565. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  108566. pOut->zStart = pValue->z;
  108567. pOut->zEnd = &pValue->z[pValue->n];
  108568. }
  108569. /* This routine constructs a binary expression node out of two ExprSpan
  108570. ** objects and uses the result to populate a new ExprSpan object.
  108571. */
  108572. static void spanBinaryExpr(
  108573. ExprSpan *pOut, /* Write the result here */
  108574. Parse *pParse, /* The parsing context. Errors accumulate here */
  108575. int op, /* The binary operation */
  108576. ExprSpan *pLeft, /* The left operand */
  108577. ExprSpan *pRight /* The right operand */
  108578. ){
  108579. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  108580. pOut->zStart = pLeft->zStart;
  108581. pOut->zEnd = pRight->zEnd;
  108582. }
  108583. /* Construct an expression node for a unary postfix operator
  108584. */
  108585. static void spanUnaryPostfix(
  108586. ExprSpan *pOut, /* Write the new expression node here */
  108587. Parse *pParse, /* Parsing context to record errors */
  108588. int op, /* The operator */
  108589. ExprSpan *pOperand, /* The operand */
  108590. Token *pPostOp /* The operand token for setting the span */
  108591. ){
  108592. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  108593. pOut->zStart = pOperand->zStart;
  108594. pOut->zEnd = &pPostOp->z[pPostOp->n];
  108595. }
  108596. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  108597. ** unary TK_ISNULL or TK_NOTNULL expression. */
  108598. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  108599. sqlite3 *db = pParse->db;
  108600. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  108601. pA->op = (u8)op;
  108602. sqlite3ExprDelete(db, pA->pRight);
  108603. pA->pRight = 0;
  108604. }
  108605. }
  108606. /* Construct an expression node for a unary prefix operator
  108607. */
  108608. static void spanUnaryPrefix(
  108609. ExprSpan *pOut, /* Write the new expression node here */
  108610. Parse *pParse, /* Parsing context to record errors */
  108611. int op, /* The operator */
  108612. ExprSpan *pOperand, /* The operand */
  108613. Token *pPreOp /* The operand token for setting the span */
  108614. ){
  108615. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  108616. pOut->zStart = pPreOp->z;
  108617. pOut->zEnd = pOperand->zEnd;
  108618. }
  108619. /* Next is all token values, in a form suitable for use by makeheaders.
  108620. ** This section will be null unless lemon is run with the -m switch.
  108621. */
  108622. /*
  108623. ** These constants (all generated automatically by the parser generator)
  108624. ** specify the various kinds of tokens (terminals) that the parser
  108625. ** understands.
  108626. **
  108627. ** Each symbol here is a terminal symbol in the grammar.
  108628. */
  108629. /* Make sure the INTERFACE macro is defined.
  108630. */
  108631. #ifndef INTERFACE
  108632. # define INTERFACE 1
  108633. #endif
  108634. /* The next thing included is series of defines which control
  108635. ** various aspects of the generated parser.
  108636. ** YYCODETYPE is the data type used for storing terminal
  108637. ** and nonterminal numbers. "unsigned char" is
  108638. ** used if there are fewer than 250 terminals
  108639. ** and nonterminals. "int" is used otherwise.
  108640. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  108641. ** to no legal terminal or nonterminal number. This
  108642. ** number is used to fill in empty slots of the hash
  108643. ** table.
  108644. ** YYFALLBACK If defined, this indicates that one or more tokens
  108645. ** have fall-back values which should be used if the
  108646. ** original value of the token will not parse.
  108647. ** YYACTIONTYPE is the data type used for storing terminal
  108648. ** and nonterminal numbers. "unsigned char" is
  108649. ** used if there are fewer than 250 rules and
  108650. ** states combined. "int" is used otherwise.
  108651. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  108652. ** directly to the parser from the tokenizer.
  108653. ** YYMINORTYPE is the data type used for all minor tokens.
  108654. ** This is typically a union of many types, one of
  108655. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  108656. ** for base tokens is called "yy0".
  108657. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  108658. ** zero the stack is dynamically sized using realloc()
  108659. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  108660. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  108661. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  108662. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  108663. ** YYNSTATE the combined number of states.
  108664. ** YYNRULE the number of rules in the grammar
  108665. ** YYERRORSYMBOL is the code number of the error symbol. If not
  108666. ** defined, then do no error processing.
  108667. */
  108668. #define YYCODETYPE unsigned char
  108669. #define YYNOCODE 251
  108670. #define YYACTIONTYPE unsigned short int
  108671. #define YYWILDCARD 67
  108672. #define sqlite3ParserTOKENTYPE Token
  108673. typedef union {
  108674. int yyinit;
  108675. sqlite3ParserTOKENTYPE yy0;
  108676. struct LimitVal yy64;
  108677. Expr* yy122;
  108678. Select* yy159;
  108679. IdList* yy180;
  108680. struct {int value; int mask;} yy207;
  108681. u8 yy258;
  108682. u16 yy305;
  108683. struct LikeOp yy318;
  108684. TriggerStep* yy327;
  108685. ExprSpan yy342;
  108686. SrcList* yy347;
  108687. int yy392;
  108688. struct TrigEvent yy410;
  108689. ExprList* yy442;
  108690. struct ValueList yy487;
  108691. } YYMINORTYPE;
  108692. #ifndef YYSTACKDEPTH
  108693. #define YYSTACKDEPTH 100
  108694. #endif
  108695. #define sqlite3ParserARG_SDECL Parse *pParse;
  108696. #define sqlite3ParserARG_PDECL ,Parse *pParse
  108697. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  108698. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  108699. #define YYNSTATE 628
  108700. #define YYNRULE 327
  108701. #define YYFALLBACK 1
  108702. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  108703. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  108704. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  108705. /* The yyzerominor constant is used to initialize instances of
  108706. ** YYMINORTYPE objects to zero. */
  108707. static const YYMINORTYPE yyzerominor = { 0 };
  108708. /* Define the yytestcase() macro to be a no-op if is not already defined
  108709. ** otherwise.
  108710. **
  108711. ** Applications can choose to define yytestcase() in the %include section
  108712. ** to a macro that can assist in verifying code coverage. For production
  108713. ** code the yytestcase() macro should be turned off. But it is useful
  108714. ** for testing.
  108715. */
  108716. #ifndef yytestcase
  108717. # define yytestcase(X)
  108718. #endif
  108719. /* Next are the tables used to determine what action to take based on the
  108720. ** current state and lookahead token. These tables are used to implement
  108721. ** functions that take a state number and lookahead value and return an
  108722. ** action integer.
  108723. **
  108724. ** Suppose the action integer is N. Then the action is determined as
  108725. ** follows
  108726. **
  108727. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  108728. ** token onto the stack and goto state N.
  108729. **
  108730. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  108731. **
  108732. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  108733. **
  108734. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  108735. **
  108736. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  108737. ** slots in the yy_action[] table.
  108738. **
  108739. ** The action table is constructed as a single large table named yy_action[].
  108740. ** Given state S and lookahead X, the action is computed as
  108741. **
  108742. ** yy_action[ yy_shift_ofst[S] + X ]
  108743. **
  108744. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  108745. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  108746. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  108747. ** and that yy_default[S] should be used instead.
  108748. **
  108749. ** The formula above is for computing the action when the lookahead is
  108750. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  108751. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  108752. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  108753. ** YY_SHIFT_USE_DFLT.
  108754. **
  108755. ** The following are the tables generated in this section:
  108756. **
  108757. ** yy_action[] A single table containing all actions.
  108758. ** yy_lookahead[] A table containing the lookahead for each entry in
  108759. ** yy_action. Used to detect hash collisions.
  108760. ** yy_shift_ofst[] For each state, the offset into yy_action for
  108761. ** shifting terminals.
  108762. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  108763. ** shifting non-terminals after a reduce.
  108764. ** yy_default[] Default action for each state.
  108765. */
  108766. #define YY_ACTTAB_COUNT (1564)
  108767. static const YYACTIONTYPE yy_action[] = {
  108768. /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
  108769. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  108770. /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
  108771. /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
  108772. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
  108773. /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108774. /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
  108775. /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
  108776. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108777. /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
  108778. /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
  108779. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  108780. /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
  108781. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  108782. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
  108783. /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
  108784. /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
  108785. /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
  108786. /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
  108787. /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
  108788. /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108789. /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108790. /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
  108791. /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
  108792. /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
  108793. /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
  108794. /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
  108795. /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  108796. /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
  108797. /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
  108798. /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
  108799. /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
  108800. /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
  108801. /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
  108802. /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
  108803. /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
  108804. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108805. /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
  108806. /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
  108807. /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
  108808. /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
  108809. /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
  108810. /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108811. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  108812. /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
  108813. /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
  108814. /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
  108815. /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
  108816. /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
  108817. /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
  108818. /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
  108819. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
  108820. /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
  108821. /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
  108822. /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
  108823. /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
  108824. /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
  108825. /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108826. /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108827. /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
  108828. /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
  108829. /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
  108830. /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
  108831. /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
  108832. /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  108833. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  108834. /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
  108835. /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
  108836. /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
  108837. /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
  108838. /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
  108839. /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
  108840. /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  108841. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108842. /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
  108843. /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
  108844. /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
  108845. /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
  108846. /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
  108847. /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108848. /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
  108849. /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
  108850. /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
  108851. /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
  108852. /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
  108853. /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
  108854. /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
  108855. /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
  108856. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
  108857. /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
  108858. /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
  108859. /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
  108860. /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
  108861. /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
  108862. /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108863. /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108864. /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
  108865. /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
  108866. /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
  108867. /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
  108868. /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
  108869. /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
  108870. /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
  108871. /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
  108872. /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
  108873. /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
  108874. /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
  108875. /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
  108876. /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
  108877. /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  108878. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108879. /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
  108880. /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
  108881. /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
  108882. /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
  108883. /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
  108884. /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108885. /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
  108886. /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
  108887. /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
  108888. /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
  108889. /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
  108890. /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
  108891. /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
  108892. /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
  108893. /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
  108894. /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
  108895. /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
  108896. /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
  108897. /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
  108898. /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
  108899. /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
  108900. /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
  108901. /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
  108902. /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
  108903. /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
  108904. /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
  108905. /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
  108906. /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
  108907. /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
  108908. /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
  108909. /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
  108910. /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
  108911. /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
  108912. /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
  108913. /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
  108914. /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
  108915. /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
  108916. /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
  108917. /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
  108918. /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
  108919. /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
  108920. /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
  108921. /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
  108922. /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
  108923. /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
  108924. /* 1560 */ 400, 499, 523, 233,
  108925. };
  108926. static const YYCODETYPE yy_lookahead[] = {
  108927. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  108928. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  108929. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  108930. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  108931. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  108932. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  108933. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  108934. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  108935. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108936. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  108937. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  108938. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  108939. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  108940. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  108941. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  108942. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  108943. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  108944. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  108945. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  108946. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  108947. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  108948. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108949. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  108950. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  108951. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  108952. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  108953. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  108954. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  108955. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  108956. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  108957. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  108958. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  108959. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  108960. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  108961. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  108962. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  108963. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  108964. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  108965. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  108966. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  108967. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  108968. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  108969. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  108970. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  108971. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  108972. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  108973. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  108974. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  108975. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  108976. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  108977. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  108978. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  108979. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  108980. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  108981. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  108982. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  108983. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  108984. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  108985. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108986. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  108987. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  108988. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  108989. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  108990. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  108991. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  108992. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  108993. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  108994. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  108995. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  108996. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  108997. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  108998. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  108999. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  109000. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  109001. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  109002. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  109003. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  109004. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  109005. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  109006. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  109007. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  109008. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  109009. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  109010. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  109011. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  109012. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  109013. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  109014. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  109015. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  109016. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  109017. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  109018. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  109019. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  109020. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  109021. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  109022. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  109023. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  109024. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  109025. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  109026. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  109027. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  109028. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  109029. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  109030. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  109031. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  109032. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  109033. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  109034. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  109035. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  109036. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  109037. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  109038. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  109039. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  109040. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  109041. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  109042. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  109043. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  109044. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  109045. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  109046. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  109047. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  109048. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  109049. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  109050. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  109051. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  109052. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  109053. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  109054. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  109055. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  109056. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  109057. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  109058. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  109059. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  109060. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  109061. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  109062. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  109063. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  109064. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  109065. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  109066. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  109067. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  109068. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  109069. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  109070. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  109071. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  109072. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  109073. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  109074. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  109075. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  109076. /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
  109077. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  109078. /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
  109079. /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
  109080. /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
  109081. /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
  109082. /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
  109083. /* 1560 */ 191, 182, 173, 92,
  109084. };
  109085. #define YY_SHIFT_USE_DFLT (-70)
  109086. #define YY_SHIFT_COUNT (417)
  109087. #define YY_SHIFT_MIN (-69)
  109088. #define YY_SHIFT_MAX (1487)
  109089. static const short yy_shift_ofst[] = {
  109090. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  109091. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  109092. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109093. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109094. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  109095. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109096. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  109097. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  109098. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  109099. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  109100. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  109101. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109102. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  109103. /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
  109104. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  109105. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109106. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109107. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109108. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  109109. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  109110. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  109111. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  109112. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  109113. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
  109114. /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
  109115. /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
  109116. /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
  109117. /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
  109118. /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
  109119. /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
  109120. /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
  109121. /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
  109122. /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
  109123. /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
  109124. /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
  109125. /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
  109126. /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
  109127. /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
  109128. /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
  109129. /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
  109130. /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
  109131. /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
  109132. };
  109133. #define YY_REDUCE_USE_DFLT (-169)
  109134. #define YY_REDUCE_COUNT (309)
  109135. #define YY_REDUCE_MIN (-168)
  109136. #define YY_REDUCE_MAX (1397)
  109137. static const short yy_reduce_ofst[] = {
  109138. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  109139. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  109140. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  109141. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  109142. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  109143. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  109144. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  109145. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109146. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109147. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109148. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  109149. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  109150. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  109151. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  109152. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  109153. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  109154. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  109155. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  109156. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  109157. /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
  109158. /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
  109159. /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
  109160. /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
  109161. /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
  109162. /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
  109163. /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
  109164. /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
  109165. /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
  109166. /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
  109167. /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
  109168. /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  109169. };
  109170. static const YYACTIONTYPE yy_default[] = {
  109171. /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
  109172. /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
  109173. /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109174. /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109175. /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109176. /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109177. /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
  109178. /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
  109179. /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
  109180. /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
  109181. /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
  109182. /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109183. /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
  109184. /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
  109185. /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109186. /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
  109187. /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109188. /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109189. /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
  109190. /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109191. /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
  109192. /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
  109193. /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
  109194. /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
  109195. /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
  109196. /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
  109197. /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
  109198. /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
  109199. /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
  109200. /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
  109201. /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
  109202. /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
  109203. /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109204. /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
  109205. /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109206. /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
  109207. /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
  109208. /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109209. /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109210. /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
  109211. /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
  109212. /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
  109213. /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
  109214. /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
  109215. /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
  109216. /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
  109217. /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
  109218. /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
  109219. /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
  109220. /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
  109221. /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
  109222. /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
  109223. /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
  109224. /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
  109225. /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
  109226. /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
  109227. /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
  109228. /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
  109229. /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
  109230. /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
  109231. /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
  109232. /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
  109233. /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
  109234. };
  109235. /* The next table maps tokens into fallback tokens. If a construct
  109236. ** like the following:
  109237. **
  109238. ** %fallback ID X Y Z.
  109239. **
  109240. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  109241. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  109242. ** but it does not parse, the type of the token is changed to ID and
  109243. ** the parse is retried before an error is thrown.
  109244. */
  109245. #ifdef YYFALLBACK
  109246. static const YYCODETYPE yyFallback[] = {
  109247. 0, /* $ => nothing */
  109248. 0, /* SEMI => nothing */
  109249. 26, /* EXPLAIN => ID */
  109250. 26, /* QUERY => ID */
  109251. 26, /* PLAN => ID */
  109252. 26, /* BEGIN => ID */
  109253. 0, /* TRANSACTION => nothing */
  109254. 26, /* DEFERRED => ID */
  109255. 26, /* IMMEDIATE => ID */
  109256. 26, /* EXCLUSIVE => ID */
  109257. 0, /* COMMIT => nothing */
  109258. 26, /* END => ID */
  109259. 26, /* ROLLBACK => ID */
  109260. 26, /* SAVEPOINT => ID */
  109261. 26, /* RELEASE => ID */
  109262. 0, /* TO => nothing */
  109263. 0, /* TABLE => nothing */
  109264. 0, /* CREATE => nothing */
  109265. 26, /* IF => ID */
  109266. 0, /* NOT => nothing */
  109267. 0, /* EXISTS => nothing */
  109268. 26, /* TEMP => ID */
  109269. 0, /* LP => nothing */
  109270. 0, /* RP => nothing */
  109271. 0, /* AS => nothing */
  109272. 0, /* COMMA => nothing */
  109273. 0, /* ID => nothing */
  109274. 0, /* INDEXED => nothing */
  109275. 26, /* ABORT => ID */
  109276. 26, /* ACTION => ID */
  109277. 26, /* AFTER => ID */
  109278. 26, /* ANALYZE => ID */
  109279. 26, /* ASC => ID */
  109280. 26, /* ATTACH => ID */
  109281. 26, /* BEFORE => ID */
  109282. 26, /* BY => ID */
  109283. 26, /* CASCADE => ID */
  109284. 26, /* CAST => ID */
  109285. 26, /* COLUMNKW => ID */
  109286. 26, /* CONFLICT => ID */
  109287. 26, /* DATABASE => ID */
  109288. 26, /* DESC => ID */
  109289. 26, /* DETACH => ID */
  109290. 26, /* EACH => ID */
  109291. 26, /* FAIL => ID */
  109292. 26, /* FOR => ID */
  109293. 26, /* IGNORE => ID */
  109294. 26, /* INITIALLY => ID */
  109295. 26, /* INSTEAD => ID */
  109296. 26, /* LIKE_KW => ID */
  109297. 26, /* MATCH => ID */
  109298. 26, /* NO => ID */
  109299. 26, /* KEY => ID */
  109300. 26, /* OF => ID */
  109301. 26, /* OFFSET => ID */
  109302. 26, /* PRAGMA => ID */
  109303. 26, /* RAISE => ID */
  109304. 26, /* REPLACE => ID */
  109305. 26, /* RESTRICT => ID */
  109306. 26, /* ROW => ID */
  109307. 26, /* TRIGGER => ID */
  109308. 26, /* VACUUM => ID */
  109309. 26, /* VIEW => ID */
  109310. 26, /* VIRTUAL => ID */
  109311. 26, /* REINDEX => ID */
  109312. 26, /* RENAME => ID */
  109313. 26, /* CTIME_KW => ID */
  109314. };
  109315. #endif /* YYFALLBACK */
  109316. /* The following structure represents a single element of the
  109317. ** parser's stack. Information stored includes:
  109318. **
  109319. ** + The state number for the parser at this level of the stack.
  109320. **
  109321. ** + The value of the token stored at this level of the stack.
  109322. ** (In other words, the "major" token.)
  109323. **
  109324. ** + The semantic value stored at this level of the stack. This is
  109325. ** the information used by the action routines in the grammar.
  109326. ** It is sometimes called the "minor" token.
  109327. */
  109328. struct yyStackEntry {
  109329. YYACTIONTYPE stateno; /* The state-number */
  109330. YYCODETYPE major; /* The major token value. This is the code
  109331. ** number for the token at this stack level */
  109332. YYMINORTYPE minor; /* The user-supplied minor token value. This
  109333. ** is the value of the token */
  109334. };
  109335. typedef struct yyStackEntry yyStackEntry;
  109336. /* The state of the parser is completely contained in an instance of
  109337. ** the following structure */
  109338. struct yyParser {
  109339. int yyidx; /* Index of top element in stack */
  109340. #ifdef YYTRACKMAXSTACKDEPTH
  109341. int yyidxMax; /* Maximum value of yyidx */
  109342. #endif
  109343. int yyerrcnt; /* Shifts left before out of the error */
  109344. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  109345. #if YYSTACKDEPTH<=0
  109346. int yystksz; /* Current side of the stack */
  109347. yyStackEntry *yystack; /* The parser's stack */
  109348. #else
  109349. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  109350. #endif
  109351. };
  109352. typedef struct yyParser yyParser;
  109353. #ifndef NDEBUG
  109354. /* #include <stdio.h> */
  109355. static FILE *yyTraceFILE = 0;
  109356. static char *yyTracePrompt = 0;
  109357. #endif /* NDEBUG */
  109358. #ifndef NDEBUG
  109359. /*
  109360. ** Turn parser tracing on by giving a stream to which to write the trace
  109361. ** and a prompt to preface each trace message. Tracing is turned off
  109362. ** by making either argument NULL
  109363. **
  109364. ** Inputs:
  109365. ** <ul>
  109366. ** <li> A FILE* to which trace output should be written.
  109367. ** If NULL, then tracing is turned off.
  109368. ** <li> A prefix string written at the beginning of every
  109369. ** line of trace output. If NULL, then tracing is
  109370. ** turned off.
  109371. ** </ul>
  109372. **
  109373. ** Outputs:
  109374. ** None.
  109375. */
  109376. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  109377. yyTraceFILE = TraceFILE;
  109378. yyTracePrompt = zTracePrompt;
  109379. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  109380. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  109381. }
  109382. #endif /* NDEBUG */
  109383. #ifndef NDEBUG
  109384. /* For tracing shifts, the names of all terminals and nonterminals
  109385. ** are required. The following table supplies these names */
  109386. static const char *const yyTokenName[] = {
  109387. "$", "SEMI", "EXPLAIN", "QUERY",
  109388. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  109389. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  109390. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  109391. "TABLE", "CREATE", "IF", "NOT",
  109392. "EXISTS", "TEMP", "LP", "RP",
  109393. "AS", "COMMA", "ID", "INDEXED",
  109394. "ABORT", "ACTION", "AFTER", "ANALYZE",
  109395. "ASC", "ATTACH", "BEFORE", "BY",
  109396. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  109397. "DATABASE", "DESC", "DETACH", "EACH",
  109398. "FAIL", "FOR", "IGNORE", "INITIALLY",
  109399. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  109400. "KEY", "OF", "OFFSET", "PRAGMA",
  109401. "RAISE", "REPLACE", "RESTRICT", "ROW",
  109402. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  109403. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  109404. "OR", "AND", "IS", "BETWEEN",
  109405. "IN", "ISNULL", "NOTNULL", "NE",
  109406. "EQ", "GT", "LE", "LT",
  109407. "GE", "ESCAPE", "BITAND", "BITOR",
  109408. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  109409. "STAR", "SLASH", "REM", "CONCAT",
  109410. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  109411. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  109412. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  109413. "ON", "INSERT", "DELETE", "UPDATE",
  109414. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  109415. "UNION", "ALL", "EXCEPT", "INTERSECT",
  109416. "SELECT", "DISTINCT", "DOT", "FROM",
  109417. "JOIN", "USING", "ORDER", "GROUP",
  109418. "HAVING", "LIMIT", "WHERE", "INTO",
  109419. "VALUES", "INTEGER", "FLOAT", "BLOB",
  109420. "REGISTER", "VARIABLE", "CASE", "WHEN",
  109421. "THEN", "ELSE", "INDEX", "ALTER",
  109422. "ADD", "error", "input", "cmdlist",
  109423. "ecmd", "explain", "cmdx", "cmd",
  109424. "transtype", "trans_opt", "nm", "savepoint_opt",
  109425. "create_table", "create_table_args", "createkw", "temp",
  109426. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  109427. "select", "column", "columnid", "type",
  109428. "carglist", "id", "ids", "typetoken",
  109429. "typename", "signed", "plus_num", "minus_num",
  109430. "ccons", "term", "expr", "onconf",
  109431. "sortorder", "autoinc", "idxlist_opt", "refargs",
  109432. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  109433. "conslist", "tconscomma", "tcons", "idxlist",
  109434. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  109435. "ifexists", "fullname", "oneselect", "multiselect_op",
  109436. "distinct", "selcollist", "from", "where_opt",
  109437. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  109438. "sclp", "as", "seltablist", "stl_prefix",
  109439. "joinop", "indexed_opt", "on_opt", "using_opt",
  109440. "joinop2", "inscollist", "sortlist", "nexprlist",
  109441. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  109442. "exprlist", "likeop", "between_op", "in_op",
  109443. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  109444. "collate", "nmnum", "number", "trigger_decl",
  109445. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  109446. "when_clause", "trigger_cmd", "trnm", "tridxby",
  109447. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  109448. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  109449. "lp", "anylist",
  109450. };
  109451. #endif /* NDEBUG */
  109452. #ifndef NDEBUG
  109453. /* For tracing reduce actions, the names of all rules are required.
  109454. */
  109455. static const char *const yyRuleName[] = {
  109456. /* 0 */ "input ::= cmdlist",
  109457. /* 1 */ "cmdlist ::= cmdlist ecmd",
  109458. /* 2 */ "cmdlist ::= ecmd",
  109459. /* 3 */ "ecmd ::= SEMI",
  109460. /* 4 */ "ecmd ::= explain cmdx SEMI",
  109461. /* 5 */ "explain ::=",
  109462. /* 6 */ "explain ::= EXPLAIN",
  109463. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  109464. /* 8 */ "cmdx ::= cmd",
  109465. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  109466. /* 10 */ "trans_opt ::=",
  109467. /* 11 */ "trans_opt ::= TRANSACTION",
  109468. /* 12 */ "trans_opt ::= TRANSACTION nm",
  109469. /* 13 */ "transtype ::=",
  109470. /* 14 */ "transtype ::= DEFERRED",
  109471. /* 15 */ "transtype ::= IMMEDIATE",
  109472. /* 16 */ "transtype ::= EXCLUSIVE",
  109473. /* 17 */ "cmd ::= COMMIT trans_opt",
  109474. /* 18 */ "cmd ::= END trans_opt",
  109475. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  109476. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  109477. /* 21 */ "savepoint_opt ::=",
  109478. /* 22 */ "cmd ::= SAVEPOINT nm",
  109479. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  109480. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  109481. /* 25 */ "cmd ::= create_table create_table_args",
  109482. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  109483. /* 27 */ "createkw ::= CREATE",
  109484. /* 28 */ "ifnotexists ::=",
  109485. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  109486. /* 30 */ "temp ::= TEMP",
  109487. /* 31 */ "temp ::=",
  109488. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  109489. /* 33 */ "create_table_args ::= AS select",
  109490. /* 34 */ "columnlist ::= columnlist COMMA column",
  109491. /* 35 */ "columnlist ::= column",
  109492. /* 36 */ "column ::= columnid type carglist",
  109493. /* 37 */ "columnid ::= nm",
  109494. /* 38 */ "id ::= ID",
  109495. /* 39 */ "id ::= INDEXED",
  109496. /* 40 */ "ids ::= ID|STRING",
  109497. /* 41 */ "nm ::= id",
  109498. /* 42 */ "nm ::= STRING",
  109499. /* 43 */ "nm ::= JOIN_KW",
  109500. /* 44 */ "type ::=",
  109501. /* 45 */ "type ::= typetoken",
  109502. /* 46 */ "typetoken ::= typename",
  109503. /* 47 */ "typetoken ::= typename LP signed RP",
  109504. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  109505. /* 49 */ "typename ::= ids",
  109506. /* 50 */ "typename ::= typename ids",
  109507. /* 51 */ "signed ::= plus_num",
  109508. /* 52 */ "signed ::= minus_num",
  109509. /* 53 */ "carglist ::= carglist ccons",
  109510. /* 54 */ "carglist ::=",
  109511. /* 55 */ "ccons ::= CONSTRAINT nm",
  109512. /* 56 */ "ccons ::= DEFAULT term",
  109513. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  109514. /* 58 */ "ccons ::= DEFAULT PLUS term",
  109515. /* 59 */ "ccons ::= DEFAULT MINUS term",
  109516. /* 60 */ "ccons ::= DEFAULT id",
  109517. /* 61 */ "ccons ::= NULL onconf",
  109518. /* 62 */ "ccons ::= NOT NULL onconf",
  109519. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  109520. /* 64 */ "ccons ::= UNIQUE onconf",
  109521. /* 65 */ "ccons ::= CHECK LP expr RP",
  109522. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  109523. /* 67 */ "ccons ::= defer_subclause",
  109524. /* 68 */ "ccons ::= COLLATE ids",
  109525. /* 69 */ "autoinc ::=",
  109526. /* 70 */ "autoinc ::= AUTOINCR",
  109527. /* 71 */ "refargs ::=",
  109528. /* 72 */ "refargs ::= refargs refarg",
  109529. /* 73 */ "refarg ::= MATCH nm",
  109530. /* 74 */ "refarg ::= ON INSERT refact",
  109531. /* 75 */ "refarg ::= ON DELETE refact",
  109532. /* 76 */ "refarg ::= ON UPDATE refact",
  109533. /* 77 */ "refact ::= SET NULL",
  109534. /* 78 */ "refact ::= SET DEFAULT",
  109535. /* 79 */ "refact ::= CASCADE",
  109536. /* 80 */ "refact ::= RESTRICT",
  109537. /* 81 */ "refact ::= NO ACTION",
  109538. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  109539. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  109540. /* 84 */ "init_deferred_pred_opt ::=",
  109541. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  109542. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  109543. /* 87 */ "conslist_opt ::=",
  109544. /* 88 */ "conslist_opt ::= COMMA conslist",
  109545. /* 89 */ "conslist ::= conslist tconscomma tcons",
  109546. /* 90 */ "conslist ::= tcons",
  109547. /* 91 */ "tconscomma ::= COMMA",
  109548. /* 92 */ "tconscomma ::=",
  109549. /* 93 */ "tcons ::= CONSTRAINT nm",
  109550. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  109551. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  109552. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  109553. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  109554. /* 98 */ "defer_subclause_opt ::=",
  109555. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  109556. /* 100 */ "onconf ::=",
  109557. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  109558. /* 102 */ "orconf ::=",
  109559. /* 103 */ "orconf ::= OR resolvetype",
  109560. /* 104 */ "resolvetype ::= raisetype",
  109561. /* 105 */ "resolvetype ::= IGNORE",
  109562. /* 106 */ "resolvetype ::= REPLACE",
  109563. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  109564. /* 108 */ "ifexists ::= IF EXISTS",
  109565. /* 109 */ "ifexists ::=",
  109566. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  109567. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  109568. /* 112 */ "cmd ::= select",
  109569. /* 113 */ "select ::= oneselect",
  109570. /* 114 */ "select ::= select multiselect_op oneselect",
  109571. /* 115 */ "multiselect_op ::= UNION",
  109572. /* 116 */ "multiselect_op ::= UNION ALL",
  109573. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  109574. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  109575. /* 119 */ "distinct ::= DISTINCT",
  109576. /* 120 */ "distinct ::= ALL",
  109577. /* 121 */ "distinct ::=",
  109578. /* 122 */ "sclp ::= selcollist COMMA",
  109579. /* 123 */ "sclp ::=",
  109580. /* 124 */ "selcollist ::= sclp expr as",
  109581. /* 125 */ "selcollist ::= sclp STAR",
  109582. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  109583. /* 127 */ "as ::= AS nm",
  109584. /* 128 */ "as ::= ids",
  109585. /* 129 */ "as ::=",
  109586. /* 130 */ "from ::=",
  109587. /* 131 */ "from ::= FROM seltablist",
  109588. /* 132 */ "stl_prefix ::= seltablist joinop",
  109589. /* 133 */ "stl_prefix ::=",
  109590. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  109591. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  109592. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  109593. /* 137 */ "dbnm ::=",
  109594. /* 138 */ "dbnm ::= DOT nm",
  109595. /* 139 */ "fullname ::= nm dbnm",
  109596. /* 140 */ "joinop ::= COMMA|JOIN",
  109597. /* 141 */ "joinop ::= JOIN_KW JOIN",
  109598. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  109599. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  109600. /* 144 */ "on_opt ::= ON expr",
  109601. /* 145 */ "on_opt ::=",
  109602. /* 146 */ "indexed_opt ::=",
  109603. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  109604. /* 148 */ "indexed_opt ::= NOT INDEXED",
  109605. /* 149 */ "using_opt ::= USING LP inscollist RP",
  109606. /* 150 */ "using_opt ::=",
  109607. /* 151 */ "orderby_opt ::=",
  109608. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  109609. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  109610. /* 154 */ "sortlist ::= expr sortorder",
  109611. /* 155 */ "sortorder ::= ASC",
  109612. /* 156 */ "sortorder ::= DESC",
  109613. /* 157 */ "sortorder ::=",
  109614. /* 158 */ "groupby_opt ::=",
  109615. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  109616. /* 160 */ "having_opt ::=",
  109617. /* 161 */ "having_opt ::= HAVING expr",
  109618. /* 162 */ "limit_opt ::=",
  109619. /* 163 */ "limit_opt ::= LIMIT expr",
  109620. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  109621. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  109622. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  109623. /* 167 */ "where_opt ::=",
  109624. /* 168 */ "where_opt ::= WHERE expr",
  109625. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  109626. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  109627. /* 171 */ "setlist ::= nm EQ expr",
  109628. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  109629. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  109630. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  109631. /* 175 */ "insert_cmd ::= INSERT orconf",
  109632. /* 176 */ "insert_cmd ::= REPLACE",
  109633. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  109634. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  109635. /* 179 */ "inscollist_opt ::=",
  109636. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  109637. /* 181 */ "inscollist ::= inscollist COMMA nm",
  109638. /* 182 */ "inscollist ::= nm",
  109639. /* 183 */ "expr ::= term",
  109640. /* 184 */ "expr ::= LP expr RP",
  109641. /* 185 */ "term ::= NULL",
  109642. /* 186 */ "expr ::= id",
  109643. /* 187 */ "expr ::= JOIN_KW",
  109644. /* 188 */ "expr ::= nm DOT nm",
  109645. /* 189 */ "expr ::= nm DOT nm DOT nm",
  109646. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  109647. /* 191 */ "term ::= STRING",
  109648. /* 192 */ "expr ::= REGISTER",
  109649. /* 193 */ "expr ::= VARIABLE",
  109650. /* 194 */ "expr ::= expr COLLATE ids",
  109651. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  109652. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  109653. /* 197 */ "expr ::= ID LP STAR RP",
  109654. /* 198 */ "term ::= CTIME_KW",
  109655. /* 199 */ "expr ::= expr AND expr",
  109656. /* 200 */ "expr ::= expr OR expr",
  109657. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  109658. /* 202 */ "expr ::= expr EQ|NE expr",
  109659. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  109660. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  109661. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  109662. /* 206 */ "expr ::= expr CONCAT expr",
  109663. /* 207 */ "likeop ::= LIKE_KW",
  109664. /* 208 */ "likeop ::= NOT LIKE_KW",
  109665. /* 209 */ "likeop ::= MATCH",
  109666. /* 210 */ "likeop ::= NOT MATCH",
  109667. /* 211 */ "expr ::= expr likeop expr",
  109668. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  109669. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  109670. /* 214 */ "expr ::= expr NOT NULL",
  109671. /* 215 */ "expr ::= expr IS expr",
  109672. /* 216 */ "expr ::= expr IS NOT expr",
  109673. /* 217 */ "expr ::= NOT expr",
  109674. /* 218 */ "expr ::= BITNOT expr",
  109675. /* 219 */ "expr ::= MINUS expr",
  109676. /* 220 */ "expr ::= PLUS expr",
  109677. /* 221 */ "between_op ::= BETWEEN",
  109678. /* 222 */ "between_op ::= NOT BETWEEN",
  109679. /* 223 */ "expr ::= expr between_op expr AND expr",
  109680. /* 224 */ "in_op ::= IN",
  109681. /* 225 */ "in_op ::= NOT IN",
  109682. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  109683. /* 227 */ "expr ::= LP select RP",
  109684. /* 228 */ "expr ::= expr in_op LP select RP",
  109685. /* 229 */ "expr ::= expr in_op nm dbnm",
  109686. /* 230 */ "expr ::= EXISTS LP select RP",
  109687. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  109688. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  109689. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  109690. /* 234 */ "case_else ::= ELSE expr",
  109691. /* 235 */ "case_else ::=",
  109692. /* 236 */ "case_operand ::= expr",
  109693. /* 237 */ "case_operand ::=",
  109694. /* 238 */ "exprlist ::= nexprlist",
  109695. /* 239 */ "exprlist ::=",
  109696. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  109697. /* 241 */ "nexprlist ::= expr",
  109698. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  109699. /* 243 */ "uniqueflag ::= UNIQUE",
  109700. /* 244 */ "uniqueflag ::=",
  109701. /* 245 */ "idxlist_opt ::=",
  109702. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  109703. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  109704. /* 248 */ "idxlist ::= nm collate sortorder",
  109705. /* 249 */ "collate ::=",
  109706. /* 250 */ "collate ::= COLLATE ids",
  109707. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  109708. /* 252 */ "cmd ::= VACUUM",
  109709. /* 253 */ "cmd ::= VACUUM nm",
  109710. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  109711. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  109712. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  109713. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  109714. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  109715. /* 259 */ "nmnum ::= plus_num",
  109716. /* 260 */ "nmnum ::= nm",
  109717. /* 261 */ "nmnum ::= ON",
  109718. /* 262 */ "nmnum ::= DELETE",
  109719. /* 263 */ "nmnum ::= DEFAULT",
  109720. /* 264 */ "plus_num ::= PLUS number",
  109721. /* 265 */ "plus_num ::= number",
  109722. /* 266 */ "minus_num ::= MINUS number",
  109723. /* 267 */ "number ::= INTEGER|FLOAT",
  109724. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  109725. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  109726. /* 270 */ "trigger_time ::= BEFORE",
  109727. /* 271 */ "trigger_time ::= AFTER",
  109728. /* 272 */ "trigger_time ::= INSTEAD OF",
  109729. /* 273 */ "trigger_time ::=",
  109730. /* 274 */ "trigger_event ::= DELETE|INSERT",
  109731. /* 275 */ "trigger_event ::= UPDATE",
  109732. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  109733. /* 277 */ "foreach_clause ::=",
  109734. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  109735. /* 279 */ "when_clause ::=",
  109736. /* 280 */ "when_clause ::= WHEN expr",
  109737. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  109738. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  109739. /* 283 */ "trnm ::= nm",
  109740. /* 284 */ "trnm ::= nm DOT nm",
  109741. /* 285 */ "tridxby ::=",
  109742. /* 286 */ "tridxby ::= INDEXED BY nm",
  109743. /* 287 */ "tridxby ::= NOT INDEXED",
  109744. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  109745. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  109746. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  109747. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  109748. /* 292 */ "trigger_cmd ::= select",
  109749. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  109750. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  109751. /* 295 */ "raisetype ::= ROLLBACK",
  109752. /* 296 */ "raisetype ::= ABORT",
  109753. /* 297 */ "raisetype ::= FAIL",
  109754. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  109755. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  109756. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  109757. /* 301 */ "key_opt ::=",
  109758. /* 302 */ "key_opt ::= KEY expr",
  109759. /* 303 */ "database_kw_opt ::= DATABASE",
  109760. /* 304 */ "database_kw_opt ::=",
  109761. /* 305 */ "cmd ::= REINDEX",
  109762. /* 306 */ "cmd ::= REINDEX nm dbnm",
  109763. /* 307 */ "cmd ::= ANALYZE",
  109764. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  109765. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  109766. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  109767. /* 311 */ "add_column_fullname ::= fullname",
  109768. /* 312 */ "kwcolumn_opt ::=",
  109769. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  109770. /* 314 */ "cmd ::= create_vtab",
  109771. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  109772. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  109773. /* 317 */ "vtabarglist ::= vtabarg",
  109774. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  109775. /* 319 */ "vtabarg ::=",
  109776. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  109777. /* 321 */ "vtabargtoken ::= ANY",
  109778. /* 322 */ "vtabargtoken ::= lp anylist RP",
  109779. /* 323 */ "lp ::= LP",
  109780. /* 324 */ "anylist ::=",
  109781. /* 325 */ "anylist ::= anylist LP anylist RP",
  109782. /* 326 */ "anylist ::= anylist ANY",
  109783. };
  109784. #endif /* NDEBUG */
  109785. #if YYSTACKDEPTH<=0
  109786. /*
  109787. ** Try to increase the size of the parser stack.
  109788. */
  109789. static void yyGrowStack(yyParser *p){
  109790. int newSize;
  109791. yyStackEntry *pNew;
  109792. newSize = p->yystksz*2 + 100;
  109793. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  109794. if( pNew ){
  109795. p->yystack = pNew;
  109796. p->yystksz = newSize;
  109797. #ifndef NDEBUG
  109798. if( yyTraceFILE ){
  109799. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  109800. yyTracePrompt, p->yystksz);
  109801. }
  109802. #endif
  109803. }
  109804. }
  109805. #endif
  109806. /*
  109807. ** This function allocates a new parser.
  109808. ** The only argument is a pointer to a function which works like
  109809. ** malloc.
  109810. **
  109811. ** Inputs:
  109812. ** A pointer to the function used to allocate memory.
  109813. **
  109814. ** Outputs:
  109815. ** A pointer to a parser. This pointer is used in subsequent calls
  109816. ** to sqlite3Parser and sqlite3ParserFree.
  109817. */
  109818. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  109819. yyParser *pParser;
  109820. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  109821. if( pParser ){
  109822. pParser->yyidx = -1;
  109823. #ifdef YYTRACKMAXSTACKDEPTH
  109824. pParser->yyidxMax = 0;
  109825. #endif
  109826. #if YYSTACKDEPTH<=0
  109827. pParser->yystack = NULL;
  109828. pParser->yystksz = 0;
  109829. yyGrowStack(pParser);
  109830. #endif
  109831. }
  109832. return pParser;
  109833. }
  109834. /* The following function deletes the value associated with a
  109835. ** symbol. The symbol can be either a terminal or nonterminal.
  109836. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  109837. ** the value.
  109838. */
  109839. static void yy_destructor(
  109840. yyParser *yypParser, /* The parser */
  109841. YYCODETYPE yymajor, /* Type code for object to destroy */
  109842. YYMINORTYPE *yypminor /* The object to be destroyed */
  109843. ){
  109844. sqlite3ParserARG_FETCH;
  109845. switch( yymajor ){
  109846. /* Here is inserted the actions which take place when a
  109847. ** terminal or non-terminal is destroyed. This can happen
  109848. ** when the symbol is popped from the stack during a
  109849. ** reduce or during error processing or when a parser is
  109850. ** being destroyed before it is finished parsing.
  109851. **
  109852. ** Note: during a reduce, the only symbols destroyed are those
  109853. ** which appear on the RHS of the rule, but which are not used
  109854. ** inside the C code.
  109855. */
  109856. case 160: /* select */
  109857. case 194: /* oneselect */
  109858. {
  109859. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  109860. }
  109861. break;
  109862. case 173: /* term */
  109863. case 174: /* expr */
  109864. {
  109865. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  109866. }
  109867. break;
  109868. case 178: /* idxlist_opt */
  109869. case 187: /* idxlist */
  109870. case 197: /* selcollist */
  109871. case 200: /* groupby_opt */
  109872. case 202: /* orderby_opt */
  109873. case 204: /* sclp */
  109874. case 214: /* sortlist */
  109875. case 215: /* nexprlist */
  109876. case 216: /* setlist */
  109877. case 220: /* exprlist */
  109878. case 225: /* case_exprlist */
  109879. {
  109880. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  109881. }
  109882. break;
  109883. case 193: /* fullname */
  109884. case 198: /* from */
  109885. case 206: /* seltablist */
  109886. case 207: /* stl_prefix */
  109887. {
  109888. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  109889. }
  109890. break;
  109891. case 199: /* where_opt */
  109892. case 201: /* having_opt */
  109893. case 210: /* on_opt */
  109894. case 224: /* case_operand */
  109895. case 226: /* case_else */
  109896. case 236: /* when_clause */
  109897. case 241: /* key_opt */
  109898. {
  109899. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  109900. }
  109901. break;
  109902. case 211: /* using_opt */
  109903. case 213: /* inscollist */
  109904. case 218: /* inscollist_opt */
  109905. {
  109906. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  109907. }
  109908. break;
  109909. case 219: /* valuelist */
  109910. {
  109911. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  109912. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  109913. }
  109914. break;
  109915. case 232: /* trigger_cmd_list */
  109916. case 237: /* trigger_cmd */
  109917. {
  109918. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  109919. }
  109920. break;
  109921. case 234: /* trigger_event */
  109922. {
  109923. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  109924. }
  109925. break;
  109926. default: break; /* If no destructor action specified: do nothing */
  109927. }
  109928. }
  109929. /*
  109930. ** Pop the parser's stack once.
  109931. **
  109932. ** If there is a destructor routine associated with the token which
  109933. ** is popped from the stack, then call it.
  109934. **
  109935. ** Return the major token number for the symbol popped.
  109936. */
  109937. static int yy_pop_parser_stack(yyParser *pParser){
  109938. YYCODETYPE yymajor;
  109939. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  109940. /* There is no mechanism by which the parser stack can be popped below
  109941. ** empty in SQLite. */
  109942. if( NEVER(pParser->yyidx<0) ) return 0;
  109943. #ifndef NDEBUG
  109944. if( yyTraceFILE && pParser->yyidx>=0 ){
  109945. fprintf(yyTraceFILE,"%sPopping %s\n",
  109946. yyTracePrompt,
  109947. yyTokenName[yytos->major]);
  109948. }
  109949. #endif
  109950. yymajor = yytos->major;
  109951. yy_destructor(pParser, yymajor, &yytos->minor);
  109952. pParser->yyidx--;
  109953. return yymajor;
  109954. }
  109955. /*
  109956. ** Deallocate and destroy a parser. Destructors are all called for
  109957. ** all stack elements before shutting the parser down.
  109958. **
  109959. ** Inputs:
  109960. ** <ul>
  109961. ** <li> A pointer to the parser. This should be a pointer
  109962. ** obtained from sqlite3ParserAlloc.
  109963. ** <li> A pointer to a function used to reclaim memory obtained
  109964. ** from malloc.
  109965. ** </ul>
  109966. */
  109967. SQLITE_PRIVATE void sqlite3ParserFree(
  109968. void *p, /* The parser to be deleted */
  109969. void (*freeProc)(void*) /* Function used to reclaim memory */
  109970. ){
  109971. yyParser *pParser = (yyParser*)p;
  109972. /* In SQLite, we never try to destroy a parser that was not successfully
  109973. ** created in the first place. */
  109974. if( NEVER(pParser==0) ) return;
  109975. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  109976. #if YYSTACKDEPTH<=0
  109977. free(pParser->yystack);
  109978. #endif
  109979. (*freeProc)((void*)pParser);
  109980. }
  109981. /*
  109982. ** Return the peak depth of the stack for a parser.
  109983. */
  109984. #ifdef YYTRACKMAXSTACKDEPTH
  109985. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  109986. yyParser *pParser = (yyParser*)p;
  109987. return pParser->yyidxMax;
  109988. }
  109989. #endif
  109990. /*
  109991. ** Find the appropriate action for a parser given the terminal
  109992. ** look-ahead token iLookAhead.
  109993. **
  109994. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  109995. ** independent of the look-ahead. If it is, return the action, otherwise
  109996. ** return YY_NO_ACTION.
  109997. */
  109998. static int yy_find_shift_action(
  109999. yyParser *pParser, /* The parser */
  110000. YYCODETYPE iLookAhead /* The look-ahead token */
  110001. ){
  110002. int i;
  110003. int stateno = pParser->yystack[pParser->yyidx].stateno;
  110004. if( stateno>YY_SHIFT_COUNT
  110005. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  110006. return yy_default[stateno];
  110007. }
  110008. assert( iLookAhead!=YYNOCODE );
  110009. i += iLookAhead;
  110010. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  110011. if( iLookAhead>0 ){
  110012. #ifdef YYFALLBACK
  110013. YYCODETYPE iFallback; /* Fallback token */
  110014. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  110015. && (iFallback = yyFallback[iLookAhead])!=0 ){
  110016. #ifndef NDEBUG
  110017. if( yyTraceFILE ){
  110018. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  110019. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  110020. }
  110021. #endif
  110022. return yy_find_shift_action(pParser, iFallback);
  110023. }
  110024. #endif
  110025. #ifdef YYWILDCARD
  110026. {
  110027. int j = i - iLookAhead + YYWILDCARD;
  110028. if(
  110029. #if YY_SHIFT_MIN+YYWILDCARD<0
  110030. j>=0 &&
  110031. #endif
  110032. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  110033. j<YY_ACTTAB_COUNT &&
  110034. #endif
  110035. yy_lookahead[j]==YYWILDCARD
  110036. ){
  110037. #ifndef NDEBUG
  110038. if( yyTraceFILE ){
  110039. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  110040. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  110041. }
  110042. #endif /* NDEBUG */
  110043. return yy_action[j];
  110044. }
  110045. }
  110046. #endif /* YYWILDCARD */
  110047. }
  110048. return yy_default[stateno];
  110049. }else{
  110050. return yy_action[i];
  110051. }
  110052. }
  110053. /*
  110054. ** Find the appropriate action for a parser given the non-terminal
  110055. ** look-ahead token iLookAhead.
  110056. **
  110057. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  110058. ** independent of the look-ahead. If it is, return the action, otherwise
  110059. ** return YY_NO_ACTION.
  110060. */
  110061. static int yy_find_reduce_action(
  110062. int stateno, /* Current state number */
  110063. YYCODETYPE iLookAhead /* The look-ahead token */
  110064. ){
  110065. int i;
  110066. #ifdef YYERRORSYMBOL
  110067. if( stateno>YY_REDUCE_COUNT ){
  110068. return yy_default[stateno];
  110069. }
  110070. #else
  110071. assert( stateno<=YY_REDUCE_COUNT );
  110072. #endif
  110073. i = yy_reduce_ofst[stateno];
  110074. assert( i!=YY_REDUCE_USE_DFLT );
  110075. assert( iLookAhead!=YYNOCODE );
  110076. i += iLookAhead;
  110077. #ifdef YYERRORSYMBOL
  110078. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  110079. return yy_default[stateno];
  110080. }
  110081. #else
  110082. assert( i>=0 && i<YY_ACTTAB_COUNT );
  110083. assert( yy_lookahead[i]==iLookAhead );
  110084. #endif
  110085. return yy_action[i];
  110086. }
  110087. /*
  110088. ** The following routine is called if the stack overflows.
  110089. */
  110090. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  110091. sqlite3ParserARG_FETCH;
  110092. yypParser->yyidx--;
  110093. #ifndef NDEBUG
  110094. if( yyTraceFILE ){
  110095. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  110096. }
  110097. #endif
  110098. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  110099. /* Here code is inserted which will execute if the parser
  110100. ** stack every overflows */
  110101. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  110102. sqlite3ErrorMsg(pParse, "parser stack overflow");
  110103. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  110104. }
  110105. /*
  110106. ** Perform a shift action.
  110107. */
  110108. static void yy_shift(
  110109. yyParser *yypParser, /* The parser to be shifted */
  110110. int yyNewState, /* The new state to shift in */
  110111. int yyMajor, /* The major token to shift in */
  110112. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  110113. ){
  110114. yyStackEntry *yytos;
  110115. yypParser->yyidx++;
  110116. #ifdef YYTRACKMAXSTACKDEPTH
  110117. if( yypParser->yyidx>yypParser->yyidxMax ){
  110118. yypParser->yyidxMax = yypParser->yyidx;
  110119. }
  110120. #endif
  110121. #if YYSTACKDEPTH>0
  110122. if( yypParser->yyidx>=YYSTACKDEPTH ){
  110123. yyStackOverflow(yypParser, yypMinor);
  110124. return;
  110125. }
  110126. #else
  110127. if( yypParser->yyidx>=yypParser->yystksz ){
  110128. yyGrowStack(yypParser);
  110129. if( yypParser->yyidx>=yypParser->yystksz ){
  110130. yyStackOverflow(yypParser, yypMinor);
  110131. return;
  110132. }
  110133. }
  110134. #endif
  110135. yytos = &yypParser->yystack[yypParser->yyidx];
  110136. yytos->stateno = (YYACTIONTYPE)yyNewState;
  110137. yytos->major = (YYCODETYPE)yyMajor;
  110138. yytos->minor = *yypMinor;
  110139. #ifndef NDEBUG
  110140. if( yyTraceFILE && yypParser->yyidx>0 ){
  110141. int i;
  110142. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  110143. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  110144. for(i=1; i<=yypParser->yyidx; i++)
  110145. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  110146. fprintf(yyTraceFILE,"\n");
  110147. }
  110148. #endif
  110149. }
  110150. /* The following table contains information about every rule that
  110151. ** is used during the reduce.
  110152. */
  110153. static const struct {
  110154. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  110155. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  110156. } yyRuleInfo[] = {
  110157. { 142, 1 },
  110158. { 143, 2 },
  110159. { 143, 1 },
  110160. { 144, 1 },
  110161. { 144, 3 },
  110162. { 145, 0 },
  110163. { 145, 1 },
  110164. { 145, 3 },
  110165. { 146, 1 },
  110166. { 147, 3 },
  110167. { 149, 0 },
  110168. { 149, 1 },
  110169. { 149, 2 },
  110170. { 148, 0 },
  110171. { 148, 1 },
  110172. { 148, 1 },
  110173. { 148, 1 },
  110174. { 147, 2 },
  110175. { 147, 2 },
  110176. { 147, 2 },
  110177. { 151, 1 },
  110178. { 151, 0 },
  110179. { 147, 2 },
  110180. { 147, 3 },
  110181. { 147, 5 },
  110182. { 147, 2 },
  110183. { 152, 6 },
  110184. { 154, 1 },
  110185. { 156, 0 },
  110186. { 156, 3 },
  110187. { 155, 1 },
  110188. { 155, 0 },
  110189. { 153, 4 },
  110190. { 153, 2 },
  110191. { 158, 3 },
  110192. { 158, 1 },
  110193. { 161, 3 },
  110194. { 162, 1 },
  110195. { 165, 1 },
  110196. { 165, 1 },
  110197. { 166, 1 },
  110198. { 150, 1 },
  110199. { 150, 1 },
  110200. { 150, 1 },
  110201. { 163, 0 },
  110202. { 163, 1 },
  110203. { 167, 1 },
  110204. { 167, 4 },
  110205. { 167, 6 },
  110206. { 168, 1 },
  110207. { 168, 2 },
  110208. { 169, 1 },
  110209. { 169, 1 },
  110210. { 164, 2 },
  110211. { 164, 0 },
  110212. { 172, 2 },
  110213. { 172, 2 },
  110214. { 172, 4 },
  110215. { 172, 3 },
  110216. { 172, 3 },
  110217. { 172, 2 },
  110218. { 172, 2 },
  110219. { 172, 3 },
  110220. { 172, 5 },
  110221. { 172, 2 },
  110222. { 172, 4 },
  110223. { 172, 4 },
  110224. { 172, 1 },
  110225. { 172, 2 },
  110226. { 177, 0 },
  110227. { 177, 1 },
  110228. { 179, 0 },
  110229. { 179, 2 },
  110230. { 181, 2 },
  110231. { 181, 3 },
  110232. { 181, 3 },
  110233. { 181, 3 },
  110234. { 182, 2 },
  110235. { 182, 2 },
  110236. { 182, 1 },
  110237. { 182, 1 },
  110238. { 182, 2 },
  110239. { 180, 3 },
  110240. { 180, 2 },
  110241. { 183, 0 },
  110242. { 183, 2 },
  110243. { 183, 2 },
  110244. { 159, 0 },
  110245. { 159, 2 },
  110246. { 184, 3 },
  110247. { 184, 1 },
  110248. { 185, 1 },
  110249. { 185, 0 },
  110250. { 186, 2 },
  110251. { 186, 7 },
  110252. { 186, 5 },
  110253. { 186, 5 },
  110254. { 186, 10 },
  110255. { 188, 0 },
  110256. { 188, 1 },
  110257. { 175, 0 },
  110258. { 175, 3 },
  110259. { 189, 0 },
  110260. { 189, 2 },
  110261. { 190, 1 },
  110262. { 190, 1 },
  110263. { 190, 1 },
  110264. { 147, 4 },
  110265. { 192, 2 },
  110266. { 192, 0 },
  110267. { 147, 8 },
  110268. { 147, 4 },
  110269. { 147, 1 },
  110270. { 160, 1 },
  110271. { 160, 3 },
  110272. { 195, 1 },
  110273. { 195, 2 },
  110274. { 195, 1 },
  110275. { 194, 9 },
  110276. { 196, 1 },
  110277. { 196, 1 },
  110278. { 196, 0 },
  110279. { 204, 2 },
  110280. { 204, 0 },
  110281. { 197, 3 },
  110282. { 197, 2 },
  110283. { 197, 4 },
  110284. { 205, 2 },
  110285. { 205, 1 },
  110286. { 205, 0 },
  110287. { 198, 0 },
  110288. { 198, 2 },
  110289. { 207, 2 },
  110290. { 207, 0 },
  110291. { 206, 7 },
  110292. { 206, 7 },
  110293. { 206, 7 },
  110294. { 157, 0 },
  110295. { 157, 2 },
  110296. { 193, 2 },
  110297. { 208, 1 },
  110298. { 208, 2 },
  110299. { 208, 3 },
  110300. { 208, 4 },
  110301. { 210, 2 },
  110302. { 210, 0 },
  110303. { 209, 0 },
  110304. { 209, 3 },
  110305. { 209, 2 },
  110306. { 211, 4 },
  110307. { 211, 0 },
  110308. { 202, 0 },
  110309. { 202, 3 },
  110310. { 214, 4 },
  110311. { 214, 2 },
  110312. { 176, 1 },
  110313. { 176, 1 },
  110314. { 176, 0 },
  110315. { 200, 0 },
  110316. { 200, 3 },
  110317. { 201, 0 },
  110318. { 201, 2 },
  110319. { 203, 0 },
  110320. { 203, 2 },
  110321. { 203, 4 },
  110322. { 203, 4 },
  110323. { 147, 5 },
  110324. { 199, 0 },
  110325. { 199, 2 },
  110326. { 147, 7 },
  110327. { 216, 5 },
  110328. { 216, 3 },
  110329. { 147, 5 },
  110330. { 147, 5 },
  110331. { 147, 6 },
  110332. { 217, 2 },
  110333. { 217, 1 },
  110334. { 219, 4 },
  110335. { 219, 5 },
  110336. { 218, 0 },
  110337. { 218, 3 },
  110338. { 213, 3 },
  110339. { 213, 1 },
  110340. { 174, 1 },
  110341. { 174, 3 },
  110342. { 173, 1 },
  110343. { 174, 1 },
  110344. { 174, 1 },
  110345. { 174, 3 },
  110346. { 174, 5 },
  110347. { 173, 1 },
  110348. { 173, 1 },
  110349. { 174, 1 },
  110350. { 174, 1 },
  110351. { 174, 3 },
  110352. { 174, 6 },
  110353. { 174, 5 },
  110354. { 174, 4 },
  110355. { 173, 1 },
  110356. { 174, 3 },
  110357. { 174, 3 },
  110358. { 174, 3 },
  110359. { 174, 3 },
  110360. { 174, 3 },
  110361. { 174, 3 },
  110362. { 174, 3 },
  110363. { 174, 3 },
  110364. { 221, 1 },
  110365. { 221, 2 },
  110366. { 221, 1 },
  110367. { 221, 2 },
  110368. { 174, 3 },
  110369. { 174, 5 },
  110370. { 174, 2 },
  110371. { 174, 3 },
  110372. { 174, 3 },
  110373. { 174, 4 },
  110374. { 174, 2 },
  110375. { 174, 2 },
  110376. { 174, 2 },
  110377. { 174, 2 },
  110378. { 222, 1 },
  110379. { 222, 2 },
  110380. { 174, 5 },
  110381. { 223, 1 },
  110382. { 223, 2 },
  110383. { 174, 5 },
  110384. { 174, 3 },
  110385. { 174, 5 },
  110386. { 174, 4 },
  110387. { 174, 4 },
  110388. { 174, 5 },
  110389. { 225, 5 },
  110390. { 225, 4 },
  110391. { 226, 2 },
  110392. { 226, 0 },
  110393. { 224, 1 },
  110394. { 224, 0 },
  110395. { 220, 1 },
  110396. { 220, 0 },
  110397. { 215, 3 },
  110398. { 215, 1 },
  110399. { 147, 12 },
  110400. { 227, 1 },
  110401. { 227, 0 },
  110402. { 178, 0 },
  110403. { 178, 3 },
  110404. { 187, 5 },
  110405. { 187, 3 },
  110406. { 228, 0 },
  110407. { 228, 2 },
  110408. { 147, 4 },
  110409. { 147, 1 },
  110410. { 147, 2 },
  110411. { 147, 3 },
  110412. { 147, 5 },
  110413. { 147, 6 },
  110414. { 147, 5 },
  110415. { 147, 6 },
  110416. { 229, 1 },
  110417. { 229, 1 },
  110418. { 229, 1 },
  110419. { 229, 1 },
  110420. { 229, 1 },
  110421. { 170, 2 },
  110422. { 170, 1 },
  110423. { 171, 2 },
  110424. { 230, 1 },
  110425. { 147, 5 },
  110426. { 231, 11 },
  110427. { 233, 1 },
  110428. { 233, 1 },
  110429. { 233, 2 },
  110430. { 233, 0 },
  110431. { 234, 1 },
  110432. { 234, 1 },
  110433. { 234, 3 },
  110434. { 235, 0 },
  110435. { 235, 3 },
  110436. { 236, 0 },
  110437. { 236, 2 },
  110438. { 232, 3 },
  110439. { 232, 2 },
  110440. { 238, 1 },
  110441. { 238, 3 },
  110442. { 239, 0 },
  110443. { 239, 3 },
  110444. { 239, 2 },
  110445. { 237, 7 },
  110446. { 237, 5 },
  110447. { 237, 5 },
  110448. { 237, 5 },
  110449. { 237, 1 },
  110450. { 174, 4 },
  110451. { 174, 6 },
  110452. { 191, 1 },
  110453. { 191, 1 },
  110454. { 191, 1 },
  110455. { 147, 4 },
  110456. { 147, 6 },
  110457. { 147, 3 },
  110458. { 241, 0 },
  110459. { 241, 2 },
  110460. { 240, 1 },
  110461. { 240, 0 },
  110462. { 147, 1 },
  110463. { 147, 3 },
  110464. { 147, 1 },
  110465. { 147, 3 },
  110466. { 147, 6 },
  110467. { 147, 6 },
  110468. { 242, 1 },
  110469. { 243, 0 },
  110470. { 243, 1 },
  110471. { 147, 1 },
  110472. { 147, 4 },
  110473. { 244, 8 },
  110474. { 245, 1 },
  110475. { 245, 3 },
  110476. { 246, 0 },
  110477. { 246, 2 },
  110478. { 247, 1 },
  110479. { 247, 3 },
  110480. { 248, 1 },
  110481. { 249, 0 },
  110482. { 249, 4 },
  110483. { 249, 2 },
  110484. };
  110485. static void yy_accept(yyParser*); /* Forward Declaration */
  110486. /*
  110487. ** Perform a reduce action and the shift that must immediately
  110488. ** follow the reduce.
  110489. */
  110490. static void yy_reduce(
  110491. yyParser *yypParser, /* The parser */
  110492. int yyruleno /* Number of the rule by which to reduce */
  110493. ){
  110494. int yygoto; /* The next state */
  110495. int yyact; /* The next action */
  110496. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  110497. yyStackEntry *yymsp; /* The top of the parser's stack */
  110498. int yysize; /* Amount to pop the stack */
  110499. sqlite3ParserARG_FETCH;
  110500. yymsp = &yypParser->yystack[yypParser->yyidx];
  110501. #ifndef NDEBUG
  110502. if( yyTraceFILE && yyruleno>=0
  110503. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  110504. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  110505. yyRuleName[yyruleno]);
  110506. }
  110507. #endif /* NDEBUG */
  110508. /* Silence complaints from purify about yygotominor being uninitialized
  110509. ** in some cases when it is copied into the stack after the following
  110510. ** switch. yygotominor is uninitialized when a rule reduces that does
  110511. ** not set the value of its left-hand side nonterminal. Leaving the
  110512. ** value of the nonterminal uninitialized is utterly harmless as long
  110513. ** as the value is never used. So really the only thing this code
  110514. ** accomplishes is to quieten purify.
  110515. **
  110516. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  110517. ** without this code, their parser segfaults. I'm not sure what there
  110518. ** parser is doing to make this happen. This is the second bug report
  110519. ** from wireshark this week. Clearly they are stressing Lemon in ways
  110520. ** that it has not been previously stressed... (SQLite ticket #2172)
  110521. */
  110522. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  110523. yygotominor = yyzerominor;
  110524. switch( yyruleno ){
  110525. /* Beginning here are the reduction cases. A typical example
  110526. ** follows:
  110527. ** case 0:
  110528. ** #line <lineno> <grammarfile>
  110529. ** { ... } // User supplied code
  110530. ** #line <lineno> <thisfile>
  110531. ** break;
  110532. */
  110533. case 5: /* explain ::= */
  110534. { sqlite3BeginParse(pParse, 0); }
  110535. break;
  110536. case 6: /* explain ::= EXPLAIN */
  110537. { sqlite3BeginParse(pParse, 1); }
  110538. break;
  110539. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  110540. { sqlite3BeginParse(pParse, 2); }
  110541. break;
  110542. case 8: /* cmdx ::= cmd */
  110543. { sqlite3FinishCoding(pParse); }
  110544. break;
  110545. case 9: /* cmd ::= BEGIN transtype trans_opt */
  110546. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  110547. break;
  110548. case 13: /* transtype ::= */
  110549. {yygotominor.yy392 = TK_DEFERRED;}
  110550. break;
  110551. case 14: /* transtype ::= DEFERRED */
  110552. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  110553. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  110554. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  110555. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  110556. {yygotominor.yy392 = yymsp[0].major;}
  110557. break;
  110558. case 17: /* cmd ::= COMMIT trans_opt */
  110559. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  110560. {sqlite3CommitTransaction(pParse);}
  110561. break;
  110562. case 19: /* cmd ::= ROLLBACK trans_opt */
  110563. {sqlite3RollbackTransaction(pParse);}
  110564. break;
  110565. case 22: /* cmd ::= SAVEPOINT nm */
  110566. {
  110567. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  110568. }
  110569. break;
  110570. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  110571. {
  110572. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  110573. }
  110574. break;
  110575. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  110576. {
  110577. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  110578. }
  110579. break;
  110580. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  110581. {
  110582. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  110583. }
  110584. break;
  110585. case 27: /* createkw ::= CREATE */
  110586. {
  110587. pParse->db->lookaside.bEnabled = 0;
  110588. yygotominor.yy0 = yymsp[0].minor.yy0;
  110589. }
  110590. break;
  110591. case 28: /* ifnotexists ::= */
  110592. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  110593. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  110594. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  110595. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  110596. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  110597. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  110598. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  110599. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  110600. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  110601. {yygotominor.yy392 = 0;}
  110602. break;
  110603. case 29: /* ifnotexists ::= IF NOT EXISTS */
  110604. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  110605. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  110606. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  110607. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  110608. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  110609. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  110610. {yygotominor.yy392 = 1;}
  110611. break;
  110612. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  110613. {
  110614. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  110615. }
  110616. break;
  110617. case 33: /* create_table_args ::= AS select */
  110618. {
  110619. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  110620. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  110621. }
  110622. break;
  110623. case 36: /* column ::= columnid type carglist */
  110624. {
  110625. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  110626. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  110627. }
  110628. break;
  110629. case 37: /* columnid ::= nm */
  110630. {
  110631. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  110632. yygotominor.yy0 = yymsp[0].minor.yy0;
  110633. pParse->constraintName.n = 0;
  110634. }
  110635. break;
  110636. case 38: /* id ::= ID */
  110637. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  110638. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  110639. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  110640. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  110641. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  110642. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  110643. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  110644. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  110645. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  110646. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  110647. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  110648. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  110649. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  110650. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  110651. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  110652. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  110653. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  110654. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  110655. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  110656. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  110657. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  110658. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  110659. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  110660. break;
  110661. case 45: /* type ::= typetoken */
  110662. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  110663. break;
  110664. case 47: /* typetoken ::= typename LP signed RP */
  110665. {
  110666. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  110667. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  110668. }
  110669. break;
  110670. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  110671. {
  110672. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  110673. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  110674. }
  110675. break;
  110676. case 50: /* typename ::= typename ids */
  110677. {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);}
  110678. break;
  110679. case 55: /* ccons ::= CONSTRAINT nm */
  110680. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  110681. {pParse->constraintName = yymsp[0].minor.yy0;}
  110682. break;
  110683. case 56: /* ccons ::= DEFAULT term */
  110684. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  110685. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  110686. break;
  110687. case 57: /* ccons ::= DEFAULT LP expr RP */
  110688. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  110689. break;
  110690. case 59: /* ccons ::= DEFAULT MINUS term */
  110691. {
  110692. ExprSpan v;
  110693. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  110694. v.zStart = yymsp[-1].minor.yy0.z;
  110695. v.zEnd = yymsp[0].minor.yy342.zEnd;
  110696. sqlite3AddDefaultValue(pParse,&v);
  110697. }
  110698. break;
  110699. case 60: /* ccons ::= DEFAULT id */
  110700. {
  110701. ExprSpan v;
  110702. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  110703. sqlite3AddDefaultValue(pParse,&v);
  110704. }
  110705. break;
  110706. case 62: /* ccons ::= NOT NULL onconf */
  110707. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  110708. break;
  110709. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  110710. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  110711. break;
  110712. case 64: /* ccons ::= UNIQUE onconf */
  110713. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  110714. break;
  110715. case 65: /* ccons ::= CHECK LP expr RP */
  110716. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  110717. break;
  110718. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  110719. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  110720. break;
  110721. case 67: /* ccons ::= defer_subclause */
  110722. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  110723. break;
  110724. case 68: /* ccons ::= COLLATE ids */
  110725. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  110726. break;
  110727. case 71: /* refargs ::= */
  110728. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  110729. break;
  110730. case 72: /* refargs ::= refargs refarg */
  110731. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  110732. break;
  110733. case 73: /* refarg ::= MATCH nm */
  110734. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  110735. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  110736. break;
  110737. case 75: /* refarg ::= ON DELETE refact */
  110738. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  110739. break;
  110740. case 76: /* refarg ::= ON UPDATE refact */
  110741. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  110742. break;
  110743. case 77: /* refact ::= SET NULL */
  110744. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  110745. break;
  110746. case 78: /* refact ::= SET DEFAULT */
  110747. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  110748. break;
  110749. case 79: /* refact ::= CASCADE */
  110750. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  110751. break;
  110752. case 80: /* refact ::= RESTRICT */
  110753. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  110754. break;
  110755. case 81: /* refact ::= NO ACTION */
  110756. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  110757. break;
  110758. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  110759. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  110760. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  110761. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  110762. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  110763. break;
  110764. case 87: /* conslist_opt ::= */
  110765. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  110766. break;
  110767. case 88: /* conslist_opt ::= COMMA conslist */
  110768. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  110769. break;
  110770. case 91: /* tconscomma ::= COMMA */
  110771. {pParse->constraintName.n = 0;}
  110772. break;
  110773. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  110774. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  110775. break;
  110776. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  110777. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  110778. break;
  110779. case 96: /* tcons ::= CHECK LP expr RP onconf */
  110780. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  110781. break;
  110782. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  110783. {
  110784. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  110785. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  110786. }
  110787. break;
  110788. case 100: /* onconf ::= */
  110789. {yygotominor.yy392 = OE_Default;}
  110790. break;
  110791. case 102: /* orconf ::= */
  110792. {yygotominor.yy258 = OE_Default;}
  110793. break;
  110794. case 103: /* orconf ::= OR resolvetype */
  110795. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  110796. break;
  110797. case 105: /* resolvetype ::= IGNORE */
  110798. {yygotominor.yy392 = OE_Ignore;}
  110799. break;
  110800. case 106: /* resolvetype ::= REPLACE */
  110801. {yygotominor.yy392 = OE_Replace;}
  110802. break;
  110803. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  110804. {
  110805. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  110806. }
  110807. break;
  110808. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  110809. {
  110810. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
  110811. }
  110812. break;
  110813. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  110814. {
  110815. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  110816. }
  110817. break;
  110818. case 112: /* cmd ::= select */
  110819. {
  110820. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  110821. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  110822. sqlite3ExplainBegin(pParse->pVdbe);
  110823. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  110824. sqlite3ExplainFinish(pParse->pVdbe);
  110825. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  110826. }
  110827. break;
  110828. case 113: /* select ::= oneselect */
  110829. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  110830. break;
  110831. case 114: /* select ::= select multiselect_op oneselect */
  110832. {
  110833. if( yymsp[0].minor.yy159 ){
  110834. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  110835. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  110836. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  110837. }else{
  110838. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  110839. }
  110840. yygotominor.yy159 = yymsp[0].minor.yy159;
  110841. }
  110842. break;
  110843. case 116: /* multiselect_op ::= UNION ALL */
  110844. {yygotominor.yy392 = TK_ALL;}
  110845. break;
  110846. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  110847. {
  110848. yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  110849. }
  110850. break;
  110851. case 119: /* distinct ::= DISTINCT */
  110852. {yygotominor.yy305 = SF_Distinct;}
  110853. break;
  110854. case 120: /* distinct ::= ALL */
  110855. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  110856. {yygotominor.yy305 = 0;}
  110857. break;
  110858. case 122: /* sclp ::= selcollist COMMA */
  110859. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  110860. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  110861. break;
  110862. case 123: /* sclp ::= */
  110863. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  110864. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  110865. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  110866. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  110867. {yygotominor.yy442 = 0;}
  110868. break;
  110869. case 124: /* selcollist ::= sclp expr as */
  110870. {
  110871. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  110872. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  110873. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  110874. }
  110875. break;
  110876. case 125: /* selcollist ::= sclp STAR */
  110877. {
  110878. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  110879. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  110880. }
  110881. break;
  110882. case 126: /* selcollist ::= sclp nm DOT STAR */
  110883. {
  110884. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  110885. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  110886. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  110887. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  110888. }
  110889. break;
  110890. case 129: /* as ::= */
  110891. {yygotominor.yy0.n = 0;}
  110892. break;
  110893. case 130: /* from ::= */
  110894. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  110895. break;
  110896. case 131: /* from ::= FROM seltablist */
  110897. {
  110898. yygotominor.yy347 = yymsp[0].minor.yy347;
  110899. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  110900. }
  110901. break;
  110902. case 132: /* stl_prefix ::= seltablist joinop */
  110903. {
  110904. yygotominor.yy347 = yymsp[-1].minor.yy347;
  110905. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  110906. }
  110907. break;
  110908. case 133: /* stl_prefix ::= */
  110909. {yygotominor.yy347 = 0;}
  110910. break;
  110911. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  110912. {
  110913. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110914. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  110915. }
  110916. break;
  110917. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  110918. {
  110919. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110920. }
  110921. break;
  110922. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  110923. {
  110924. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  110925. yygotominor.yy347 = yymsp[-4].minor.yy347;
  110926. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  110927. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110928. if( yygotominor.yy347 ){
  110929. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  110930. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  110931. pNew->zName = pOld->zName;
  110932. pNew->zDatabase = pOld->zDatabase;
  110933. pNew->pSelect = pOld->pSelect;
  110934. pOld->zName = pOld->zDatabase = 0;
  110935. pOld->pSelect = 0;
  110936. }
  110937. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  110938. }else{
  110939. Select *pSubquery;
  110940. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  110941. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  110942. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110943. }
  110944. }
  110945. break;
  110946. case 137: /* dbnm ::= */
  110947. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  110948. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  110949. break;
  110950. case 139: /* fullname ::= nm dbnm */
  110951. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  110952. break;
  110953. case 140: /* joinop ::= COMMA|JOIN */
  110954. { yygotominor.yy392 = JT_INNER; }
  110955. break;
  110956. case 141: /* joinop ::= JOIN_KW JOIN */
  110957. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  110958. break;
  110959. case 142: /* joinop ::= JOIN_KW nm JOIN */
  110960. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  110961. break;
  110962. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  110963. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  110964. break;
  110965. case 144: /* on_opt ::= ON expr */
  110966. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  110967. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  110968. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  110969. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  110970. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  110971. break;
  110972. case 145: /* on_opt ::= */
  110973. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  110974. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  110975. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  110976. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  110977. {yygotominor.yy122 = 0;}
  110978. break;
  110979. case 148: /* indexed_opt ::= NOT INDEXED */
  110980. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  110981. break;
  110982. case 149: /* using_opt ::= USING LP inscollist RP */
  110983. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  110984. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  110985. break;
  110986. case 150: /* using_opt ::= */
  110987. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  110988. {yygotominor.yy180 = 0;}
  110989. break;
  110990. case 152: /* orderby_opt ::= ORDER BY sortlist */
  110991. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  110992. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  110993. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  110994. break;
  110995. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  110996. {
  110997. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  110998. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  110999. }
  111000. break;
  111001. case 154: /* sortlist ::= expr sortorder */
  111002. {
  111003. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  111004. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  111005. }
  111006. break;
  111007. case 155: /* sortorder ::= ASC */
  111008. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  111009. {yygotominor.yy392 = SQLITE_SO_ASC;}
  111010. break;
  111011. case 156: /* sortorder ::= DESC */
  111012. {yygotominor.yy392 = SQLITE_SO_DESC;}
  111013. break;
  111014. case 162: /* limit_opt ::= */
  111015. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  111016. break;
  111017. case 163: /* limit_opt ::= LIMIT expr */
  111018. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  111019. break;
  111020. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  111021. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  111022. break;
  111023. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  111024. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  111025. break;
  111026. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  111027. {
  111028. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  111029. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  111030. }
  111031. break;
  111032. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  111033. {
  111034. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  111035. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  111036. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  111037. }
  111038. break;
  111039. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  111040. {
  111041. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  111042. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111043. }
  111044. break;
  111045. case 171: /* setlist ::= nm EQ expr */
  111046. {
  111047. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  111048. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111049. }
  111050. break;
  111051. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  111052. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  111053. break;
  111054. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  111055. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  111056. break;
  111057. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  111058. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  111059. break;
  111060. case 175: /* insert_cmd ::= INSERT orconf */
  111061. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  111062. break;
  111063. case 176: /* insert_cmd ::= REPLACE */
  111064. {yygotominor.yy258 = OE_Replace;}
  111065. break;
  111066. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  111067. {
  111068. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  111069. yygotominor.yy487.pSelect = 0;
  111070. }
  111071. break;
  111072. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  111073. {
  111074. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  111075. if( yymsp[-4].minor.yy487.pList ){
  111076. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  111077. yymsp[-4].minor.yy487.pList = 0;
  111078. }
  111079. yygotominor.yy487.pList = 0;
  111080. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  111081. sqlite3SelectDelete(pParse->db, pRight);
  111082. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  111083. yygotominor.yy487.pSelect = 0;
  111084. }else{
  111085. pRight->op = TK_ALL;
  111086. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  111087. pRight->selFlags |= SF_Values;
  111088. pRight->pPrior->selFlags |= SF_Values;
  111089. yygotominor.yy487.pSelect = pRight;
  111090. }
  111091. }
  111092. break;
  111093. case 181: /* inscollist ::= inscollist COMMA nm */
  111094. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  111095. break;
  111096. case 182: /* inscollist ::= nm */
  111097. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  111098. break;
  111099. case 183: /* expr ::= term */
  111100. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  111101. break;
  111102. case 184: /* expr ::= LP expr RP */
  111103. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  111104. break;
  111105. case 185: /* term ::= NULL */
  111106. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  111107. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  111108. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  111109. break;
  111110. case 186: /* expr ::= id */
  111111. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  111112. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  111113. break;
  111114. case 188: /* expr ::= nm DOT nm */
  111115. {
  111116. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  111117. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  111118. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  111119. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  111120. }
  111121. break;
  111122. case 189: /* expr ::= nm DOT nm DOT nm */
  111123. {
  111124. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  111125. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  111126. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  111127. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  111128. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  111129. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  111130. }
  111131. break;
  111132. case 192: /* expr ::= REGISTER */
  111133. {
  111134. /* When doing a nested parse, one can include terms in an expression
  111135. ** that look like this: #1 #2 ... These terms refer to registers
  111136. ** in the virtual machine. #N is the N-th register. */
  111137. if( pParse->nested==0 ){
  111138. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  111139. yygotominor.yy342.pExpr = 0;
  111140. }else{
  111141. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  111142. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  111143. }
  111144. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111145. }
  111146. break;
  111147. case 193: /* expr ::= VARIABLE */
  111148. {
  111149. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  111150. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  111151. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111152. }
  111153. break;
  111154. case 194: /* expr ::= expr COLLATE ids */
  111155. {
  111156. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  111157. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  111158. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111159. }
  111160. break;
  111161. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  111162. {
  111163. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  111164. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  111165. }
  111166. break;
  111167. case 196: /* expr ::= ID LP distinct exprlist RP */
  111168. {
  111169. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  111170. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  111171. }
  111172. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  111173. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  111174. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  111175. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  111176. }
  111177. }
  111178. break;
  111179. case 197: /* expr ::= ID LP STAR RP */
  111180. {
  111181. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  111182. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  111183. }
  111184. break;
  111185. case 198: /* term ::= CTIME_KW */
  111186. {
  111187. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  111188. ** treated as functions that return constants */
  111189. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  111190. if( yygotominor.yy342.pExpr ){
  111191. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  111192. }
  111193. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111194. }
  111195. break;
  111196. case 199: /* expr ::= expr AND expr */
  111197. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  111198. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  111199. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  111200. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  111201. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  111202. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  111203. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  111204. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  111205. break;
  111206. case 207: /* likeop ::= LIKE_KW */
  111207. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  111208. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  111209. break;
  111210. case 208: /* likeop ::= NOT LIKE_KW */
  111211. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  111212. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  111213. break;
  111214. case 211: /* expr ::= expr likeop expr */
  111215. {
  111216. ExprList *pList;
  111217. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  111218. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  111219. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  111220. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111221. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  111222. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111223. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  111224. }
  111225. break;
  111226. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  111227. {
  111228. ExprList *pList;
  111229. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111230. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  111231. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  111232. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  111233. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111234. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111235. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111236. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  111237. }
  111238. break;
  111239. case 213: /* expr ::= expr ISNULL|NOTNULL */
  111240. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  111241. break;
  111242. case 214: /* expr ::= expr NOT NULL */
  111243. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  111244. break;
  111245. case 215: /* expr ::= expr IS expr */
  111246. {
  111247. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  111248. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  111249. }
  111250. break;
  111251. case 216: /* expr ::= expr IS NOT expr */
  111252. {
  111253. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  111254. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  111255. }
  111256. break;
  111257. case 217: /* expr ::= NOT expr */
  111258. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  111259. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111260. break;
  111261. case 219: /* expr ::= MINUS expr */
  111262. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111263. break;
  111264. case 220: /* expr ::= PLUS expr */
  111265. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111266. break;
  111267. case 223: /* expr ::= expr between_op expr AND expr */
  111268. {
  111269. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111270. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  111271. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111272. if( yygotominor.yy342.pExpr ){
  111273. yygotominor.yy342.pExpr->x.pList = pList;
  111274. }else{
  111275. sqlite3ExprListDelete(pParse->db, pList);
  111276. }
  111277. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111278. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111279. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111280. }
  111281. break;
  111282. case 226: /* expr ::= expr in_op LP exprlist RP */
  111283. {
  111284. if( yymsp[-1].minor.yy442==0 ){
  111285. /* Expressions of the form
  111286. **
  111287. ** expr1 IN ()
  111288. ** expr1 NOT IN ()
  111289. **
  111290. ** simplify to constants 0 (false) and 1 (true), respectively,
  111291. ** regardless of the value of expr1.
  111292. */
  111293. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  111294. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  111295. }else{
  111296. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111297. if( yygotominor.yy342.pExpr ){
  111298. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  111299. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111300. }else{
  111301. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  111302. }
  111303. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111304. }
  111305. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111306. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111307. }
  111308. break;
  111309. case 227: /* expr ::= LP select RP */
  111310. {
  111311. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  111312. if( yygotominor.yy342.pExpr ){
  111313. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  111314. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111315. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111316. }else{
  111317. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111318. }
  111319. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  111320. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111321. }
  111322. break;
  111323. case 228: /* expr ::= expr in_op LP select RP */
  111324. {
  111325. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111326. if( yygotominor.yy342.pExpr ){
  111327. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  111328. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111329. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111330. }else{
  111331. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111332. }
  111333. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111334. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111335. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111336. }
  111337. break;
  111338. case 229: /* expr ::= expr in_op nm dbnm */
  111339. {
  111340. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  111341. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  111342. if( yygotominor.yy342.pExpr ){
  111343. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  111344. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111345. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111346. }else{
  111347. sqlite3SrcListDelete(pParse->db, pSrc);
  111348. }
  111349. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111350. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  111351. yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  111352. }
  111353. break;
  111354. case 230: /* expr ::= EXISTS LP select RP */
  111355. {
  111356. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  111357. if( p ){
  111358. p->x.pSelect = yymsp[-1].minor.yy159;
  111359. ExprSetProperty(p, EP_xIsSelect);
  111360. sqlite3ExprSetHeight(pParse, p);
  111361. }else{
  111362. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111363. }
  111364. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  111365. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111366. }
  111367. break;
  111368. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  111369. {
  111370. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  111371. if( yygotominor.yy342.pExpr ){
  111372. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  111373. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111374. }else{
  111375. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  111376. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  111377. }
  111378. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  111379. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111380. }
  111381. break;
  111382. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  111383. {
  111384. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  111385. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  111386. }
  111387. break;
  111388. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  111389. {
  111390. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111391. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  111392. }
  111393. break;
  111394. case 240: /* nexprlist ::= nexprlist COMMA expr */
  111395. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  111396. break;
  111397. case 241: /* nexprlist ::= expr */
  111398. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  111399. break;
  111400. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  111401. {
  111402. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  111403. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  111404. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  111405. }
  111406. break;
  111407. case 243: /* uniqueflag ::= UNIQUE */
  111408. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  111409. {yygotominor.yy392 = OE_Abort;}
  111410. break;
  111411. case 244: /* uniqueflag ::= */
  111412. {yygotominor.yy392 = OE_None;}
  111413. break;
  111414. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  111415. {
  111416. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  111417. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  111418. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  111419. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  111420. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  111421. }
  111422. break;
  111423. case 248: /* idxlist ::= nm collate sortorder */
  111424. {
  111425. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  111426. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  111427. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111428. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  111429. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  111430. }
  111431. break;
  111432. case 249: /* collate ::= */
  111433. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  111434. break;
  111435. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  111436. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  111437. break;
  111438. case 252: /* cmd ::= VACUUM */
  111439. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  111440. {sqlite3Vacuum(pParse);}
  111441. break;
  111442. case 254: /* cmd ::= PRAGMA nm dbnm */
  111443. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  111444. break;
  111445. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  111446. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  111447. break;
  111448. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  111449. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  111450. break;
  111451. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  111452. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  111453. break;
  111454. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  111455. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  111456. break;
  111457. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  111458. {
  111459. Token all;
  111460. all.z = yymsp[-3].minor.yy0.z;
  111461. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  111462. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  111463. }
  111464. break;
  111465. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  111466. {
  111467. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
  111468. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  111469. }
  111470. break;
  111471. case 270: /* trigger_time ::= BEFORE */
  111472. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  111473. { yygotominor.yy392 = TK_BEFORE; }
  111474. break;
  111475. case 271: /* trigger_time ::= AFTER */
  111476. { yygotominor.yy392 = TK_AFTER; }
  111477. break;
  111478. case 272: /* trigger_time ::= INSTEAD OF */
  111479. { yygotominor.yy392 = TK_INSTEAD;}
  111480. break;
  111481. case 274: /* trigger_event ::= DELETE|INSERT */
  111482. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  111483. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  111484. break;
  111485. case 276: /* trigger_event ::= UPDATE OF inscollist */
  111486. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  111487. break;
  111488. case 279: /* when_clause ::= */
  111489. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  111490. { yygotominor.yy122 = 0; }
  111491. break;
  111492. case 280: /* when_clause ::= WHEN expr */
  111493. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  111494. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  111495. break;
  111496. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  111497. {
  111498. assert( yymsp[-2].minor.yy327!=0 );
  111499. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  111500. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  111501. yygotominor.yy327 = yymsp[-2].minor.yy327;
  111502. }
  111503. break;
  111504. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  111505. {
  111506. assert( yymsp[-1].minor.yy327!=0 );
  111507. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  111508. yygotominor.yy327 = yymsp[-1].minor.yy327;
  111509. }
  111510. break;
  111511. case 284: /* trnm ::= nm DOT nm */
  111512. {
  111513. yygotominor.yy0 = yymsp[0].minor.yy0;
  111514. sqlite3ErrorMsg(pParse,
  111515. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  111516. "statements within triggers");
  111517. }
  111518. break;
  111519. case 286: /* tridxby ::= INDEXED BY nm */
  111520. {
  111521. sqlite3ErrorMsg(pParse,
  111522. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  111523. "within triggers");
  111524. }
  111525. break;
  111526. case 287: /* tridxby ::= NOT INDEXED */
  111527. {
  111528. sqlite3ErrorMsg(pParse,
  111529. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  111530. "within triggers");
  111531. }
  111532. break;
  111533. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  111534. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  111535. break;
  111536. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  111537. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
  111538. break;
  111539. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  111540. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  111541. break;
  111542. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  111543. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  111544. break;
  111545. case 292: /* trigger_cmd ::= select */
  111546. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  111547. break;
  111548. case 293: /* expr ::= RAISE LP IGNORE RP */
  111549. {
  111550. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  111551. if( yygotominor.yy342.pExpr ){
  111552. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  111553. }
  111554. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  111555. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111556. }
  111557. break;
  111558. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  111559. {
  111560. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  111561. if( yygotominor.yy342.pExpr ) {
  111562. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  111563. }
  111564. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  111565. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111566. }
  111567. break;
  111568. case 295: /* raisetype ::= ROLLBACK */
  111569. {yygotominor.yy392 = OE_Rollback;}
  111570. break;
  111571. case 297: /* raisetype ::= FAIL */
  111572. {yygotominor.yy392 = OE_Fail;}
  111573. break;
  111574. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  111575. {
  111576. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  111577. }
  111578. break;
  111579. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  111580. {
  111581. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  111582. }
  111583. break;
  111584. case 300: /* cmd ::= DETACH database_kw_opt expr */
  111585. {
  111586. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  111587. }
  111588. break;
  111589. case 305: /* cmd ::= REINDEX */
  111590. {sqlite3Reindex(pParse, 0, 0);}
  111591. break;
  111592. case 306: /* cmd ::= REINDEX nm dbnm */
  111593. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  111594. break;
  111595. case 307: /* cmd ::= ANALYZE */
  111596. {sqlite3Analyze(pParse, 0, 0);}
  111597. break;
  111598. case 308: /* cmd ::= ANALYZE nm dbnm */
  111599. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  111600. break;
  111601. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  111602. {
  111603. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  111604. }
  111605. break;
  111606. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  111607. {
  111608. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  111609. }
  111610. break;
  111611. case 311: /* add_column_fullname ::= fullname */
  111612. {
  111613. pParse->db->lookaside.bEnabled = 0;
  111614. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  111615. }
  111616. break;
  111617. case 314: /* cmd ::= create_vtab */
  111618. {sqlite3VtabFinishParse(pParse,0);}
  111619. break;
  111620. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  111621. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  111622. break;
  111623. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  111624. {
  111625. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  111626. }
  111627. break;
  111628. case 319: /* vtabarg ::= */
  111629. {sqlite3VtabArgInit(pParse);}
  111630. break;
  111631. case 321: /* vtabargtoken ::= ANY */
  111632. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  111633. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  111634. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  111635. break;
  111636. default:
  111637. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  111638. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  111639. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  111640. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  111641. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  111642. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  111643. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  111644. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  111645. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  111646. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  111647. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  111648. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  111649. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  111650. /* (44) type ::= */ yytestcase(yyruleno==44);
  111651. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  111652. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  111653. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  111654. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  111655. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  111656. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  111657. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  111658. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  111659. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  111660. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  111661. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  111662. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  111663. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  111664. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  111665. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  111666. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  111667. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  111668. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  111669. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  111670. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  111671. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  111672. break;
  111673. };
  111674. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  111675. yygoto = yyRuleInfo[yyruleno].lhs;
  111676. yysize = yyRuleInfo[yyruleno].nrhs;
  111677. yypParser->yyidx -= yysize;
  111678. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  111679. if( yyact < YYNSTATE ){
  111680. #ifdef NDEBUG
  111681. /* If we are not debugging and the reduce action popped at least
  111682. ** one element off the stack, then we can push the new element back
  111683. ** onto the stack here, and skip the stack overflow test in yy_shift().
  111684. ** That gives a significant speed improvement. */
  111685. if( yysize ){
  111686. yypParser->yyidx++;
  111687. yymsp -= yysize-1;
  111688. yymsp->stateno = (YYACTIONTYPE)yyact;
  111689. yymsp->major = (YYCODETYPE)yygoto;
  111690. yymsp->minor = yygotominor;
  111691. }else
  111692. #endif
  111693. {
  111694. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  111695. }
  111696. }else{
  111697. assert( yyact == YYNSTATE + YYNRULE + 1 );
  111698. yy_accept(yypParser);
  111699. }
  111700. }
  111701. /*
  111702. ** The following code executes when the parse fails
  111703. */
  111704. #ifndef YYNOERRORRECOVERY
  111705. static void yy_parse_failed(
  111706. yyParser *yypParser /* The parser */
  111707. ){
  111708. sqlite3ParserARG_FETCH;
  111709. #ifndef NDEBUG
  111710. if( yyTraceFILE ){
  111711. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  111712. }
  111713. #endif
  111714. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  111715. /* Here code is inserted which will be executed whenever the
  111716. ** parser fails */
  111717. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111718. }
  111719. #endif /* YYNOERRORRECOVERY */
  111720. /*
  111721. ** The following code executes when a syntax error first occurs.
  111722. */
  111723. static void yy_syntax_error(
  111724. yyParser *yypParser, /* The parser */
  111725. int yymajor, /* The major type of the error token */
  111726. YYMINORTYPE yyminor /* The minor type of the error token */
  111727. ){
  111728. sqlite3ParserARG_FETCH;
  111729. #define TOKEN (yyminor.yy0)
  111730. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  111731. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  111732. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  111733. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111734. }
  111735. /*
  111736. ** The following is executed when the parser accepts
  111737. */
  111738. static void yy_accept(
  111739. yyParser *yypParser /* The parser */
  111740. ){
  111741. sqlite3ParserARG_FETCH;
  111742. #ifndef NDEBUG
  111743. if( yyTraceFILE ){
  111744. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  111745. }
  111746. #endif
  111747. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  111748. /* Here code is inserted which will be executed whenever the
  111749. ** parser accepts */
  111750. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111751. }
  111752. /* The main parser program.
  111753. ** The first argument is a pointer to a structure obtained from
  111754. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  111755. ** The second argument is the major token number. The third is
  111756. ** the minor token. The fourth optional argument is whatever the
  111757. ** user wants (and specified in the grammar) and is available for
  111758. ** use by the action routines.
  111759. **
  111760. ** Inputs:
  111761. ** <ul>
  111762. ** <li> A pointer to the parser (an opaque structure.)
  111763. ** <li> The major token number.
  111764. ** <li> The minor token number.
  111765. ** <li> An option argument of a grammar-specified type.
  111766. ** </ul>
  111767. **
  111768. ** Outputs:
  111769. ** None.
  111770. */
  111771. SQLITE_PRIVATE void sqlite3Parser(
  111772. void *yyp, /* The parser */
  111773. int yymajor, /* The major token code number */
  111774. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  111775. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  111776. ){
  111777. YYMINORTYPE yyminorunion;
  111778. int yyact; /* The parser action. */
  111779. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  111780. int yyendofinput; /* True if we are at the end of input */
  111781. #endif
  111782. #ifdef YYERRORSYMBOL
  111783. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  111784. #endif
  111785. yyParser *yypParser; /* The parser */
  111786. /* (re)initialize the parser, if necessary */
  111787. yypParser = (yyParser*)yyp;
  111788. if( yypParser->yyidx<0 ){
  111789. #if YYSTACKDEPTH<=0
  111790. if( yypParser->yystksz <=0 ){
  111791. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  111792. yyminorunion = yyzerominor;
  111793. yyStackOverflow(yypParser, &yyminorunion);
  111794. return;
  111795. }
  111796. #endif
  111797. yypParser->yyidx = 0;
  111798. yypParser->yyerrcnt = -1;
  111799. yypParser->yystack[0].stateno = 0;
  111800. yypParser->yystack[0].major = 0;
  111801. }
  111802. yyminorunion.yy0 = yyminor;
  111803. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  111804. yyendofinput = (yymajor==0);
  111805. #endif
  111806. sqlite3ParserARG_STORE;
  111807. #ifndef NDEBUG
  111808. if( yyTraceFILE ){
  111809. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  111810. }
  111811. #endif
  111812. do{
  111813. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  111814. if( yyact<YYNSTATE ){
  111815. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  111816. yypParser->yyerrcnt--;
  111817. yymajor = YYNOCODE;
  111818. }else if( yyact < YYNSTATE + YYNRULE ){
  111819. yy_reduce(yypParser,yyact-YYNSTATE);
  111820. }else{
  111821. assert( yyact == YY_ERROR_ACTION );
  111822. #ifdef YYERRORSYMBOL
  111823. int yymx;
  111824. #endif
  111825. #ifndef NDEBUG
  111826. if( yyTraceFILE ){
  111827. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  111828. }
  111829. #endif
  111830. #ifdef YYERRORSYMBOL
  111831. /* A syntax error has occurred.
  111832. ** The response to an error depends upon whether or not the
  111833. ** grammar defines an error token "ERROR".
  111834. **
  111835. ** This is what we do if the grammar does define ERROR:
  111836. **
  111837. ** * Call the %syntax_error function.
  111838. **
  111839. ** * Begin popping the stack until we enter a state where
  111840. ** it is legal to shift the error symbol, then shift
  111841. ** the error symbol.
  111842. **
  111843. ** * Set the error count to three.
  111844. **
  111845. ** * Begin accepting and shifting new tokens. No new error
  111846. ** processing will occur until three tokens have been
  111847. ** shifted successfully.
  111848. **
  111849. */
  111850. if( yypParser->yyerrcnt<0 ){
  111851. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111852. }
  111853. yymx = yypParser->yystack[yypParser->yyidx].major;
  111854. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  111855. #ifndef NDEBUG
  111856. if( yyTraceFILE ){
  111857. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  111858. yyTracePrompt,yyTokenName[yymajor]);
  111859. }
  111860. #endif
  111861. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  111862. yymajor = YYNOCODE;
  111863. }else{
  111864. while(
  111865. yypParser->yyidx >= 0 &&
  111866. yymx != YYERRORSYMBOL &&
  111867. (yyact = yy_find_reduce_action(
  111868. yypParser->yystack[yypParser->yyidx].stateno,
  111869. YYERRORSYMBOL)) >= YYNSTATE
  111870. ){
  111871. yy_pop_parser_stack(yypParser);
  111872. }
  111873. if( yypParser->yyidx < 0 || yymajor==0 ){
  111874. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111875. yy_parse_failed(yypParser);
  111876. yymajor = YYNOCODE;
  111877. }else if( yymx!=YYERRORSYMBOL ){
  111878. YYMINORTYPE u2;
  111879. u2.YYERRSYMDT = 0;
  111880. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  111881. }
  111882. }
  111883. yypParser->yyerrcnt = 3;
  111884. yyerrorhit = 1;
  111885. #elif defined(YYNOERRORRECOVERY)
  111886. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  111887. ** do any kind of error recovery. Instead, simply invoke the syntax
  111888. ** error routine and continue going as if nothing had happened.
  111889. **
  111890. ** Applications can set this macro (for example inside %include) if
  111891. ** they intend to abandon the parse upon the first syntax error seen.
  111892. */
  111893. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111894. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111895. yymajor = YYNOCODE;
  111896. #else /* YYERRORSYMBOL is not defined */
  111897. /* This is what we do if the grammar does not define ERROR:
  111898. **
  111899. ** * Report an error message, and throw away the input token.
  111900. **
  111901. ** * If the input token is $, then fail the parse.
  111902. **
  111903. ** As before, subsequent error messages are suppressed until
  111904. ** three input tokens have been successfully shifted.
  111905. */
  111906. if( yypParser->yyerrcnt<=0 ){
  111907. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111908. }
  111909. yypParser->yyerrcnt = 3;
  111910. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111911. if( yyendofinput ){
  111912. yy_parse_failed(yypParser);
  111913. }
  111914. yymajor = YYNOCODE;
  111915. #endif
  111916. }
  111917. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  111918. return;
  111919. }
  111920. /************** End of parse.c ***********************************************/
  111921. /************** Begin file tokenize.c ****************************************/
  111922. /*
  111923. ** 2001 September 15
  111924. **
  111925. ** The author disclaims copyright to this source code. In place of
  111926. ** a legal notice, here is a blessing:
  111927. **
  111928. ** May you do good and not evil.
  111929. ** May you find forgiveness for yourself and forgive others.
  111930. ** May you share freely, never taking more than you give.
  111931. **
  111932. *************************************************************************
  111933. ** An tokenizer for SQL
  111934. **
  111935. ** This file contains C code that splits an SQL input string up into
  111936. ** individual tokens and sends those tokens one-by-one over to the
  111937. ** parser for analysis.
  111938. */
  111939. /* #include <stdlib.h> */
  111940. /*
  111941. ** The charMap() macro maps alphabetic characters into their
  111942. ** lower-case ASCII equivalent. On ASCII machines, this is just
  111943. ** an upper-to-lower case map. On EBCDIC machines we also need
  111944. ** to adjust the encoding. Only alphabetic characters and underscores
  111945. ** need to be translated.
  111946. */
  111947. #ifdef SQLITE_ASCII
  111948. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  111949. #endif
  111950. #ifdef SQLITE_EBCDIC
  111951. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  111952. const unsigned char ebcdicToAscii[] = {
  111953. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  111954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  111955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  111956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  111957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  111958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  111959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  111960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  111961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  111962. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  111963. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  111964. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  111965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  111966. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  111967. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  111968. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  111969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  111970. };
  111971. #endif
  111972. /*
  111973. ** The sqlite3KeywordCode function looks up an identifier to determine if
  111974. ** it is a keyword. If it is a keyword, the token code of that keyword is
  111975. ** returned. If the input is not a keyword, TK_ID is returned.
  111976. **
  111977. ** The implementation of this routine was generated by a program,
  111978. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  111979. ** The output of the mkkeywordhash.c program is written into a file
  111980. ** named keywordhash.h and then included into this source file by
  111981. ** the #include below.
  111982. */
  111983. /************** Include keywordhash.h in the middle of tokenize.c ************/
  111984. /************** Begin file keywordhash.h *************************************/
  111985. /***** This file contains automatically generated code ******
  111986. **
  111987. ** The code in this file has been automatically generated by
  111988. **
  111989. ** sqlite/tool/mkkeywordhash.c
  111990. **
  111991. ** The code in this file implements a function that determines whether
  111992. ** or not a given identifier is really an SQL keyword. The same thing
  111993. ** might be implemented more directly using a hand-written hash table.
  111994. ** But by using this automatically generated code, the size of the code
  111995. ** is substantially reduced. This is important for embedded applications
  111996. ** on platforms with limited memory.
  111997. */
  111998. /* Hash score: 175 */
  111999. static int keywordCode(const char *z, int n){
  112000. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  112001. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  112002. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  112003. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  112004. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  112005. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  112006. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  112007. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  112008. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  112009. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  112010. /* INITIALLY */
  112011. static const char zText[540] = {
  112012. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  112013. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  112014. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  112015. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  112016. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  112017. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  112018. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  112019. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  112020. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  112021. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  112022. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  112023. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  112024. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  112025. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  112026. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  112027. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  112028. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  112029. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  112030. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  112031. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  112032. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  112033. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  112034. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  112035. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  112036. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  112037. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  112038. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  112039. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  112040. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  112041. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  112042. };
  112043. static const unsigned char aHash[127] = {
  112044. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  112045. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  112046. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  112047. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  112048. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  112049. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  112050. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  112051. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  112052. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  112053. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  112054. };
  112055. static const unsigned char aNext[121] = {
  112056. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  112057. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  112058. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  112059. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  112060. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  112061. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  112062. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  112063. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  112064. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  112065. 35, 64, 0, 0,
  112066. };
  112067. static const unsigned char aLen[121] = {
  112068. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  112069. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  112070. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  112071. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  112072. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  112073. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  112074. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  112075. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  112076. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  112077. 6, 4, 9, 3,
  112078. };
  112079. static const unsigned short int aOffset[121] = {
  112080. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  112081. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  112082. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  112083. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  112084. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  112085. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  112086. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  112087. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  112088. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  112089. 521, 527, 531, 536,
  112090. };
  112091. static const unsigned char aCode[121] = {
  112092. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  112093. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  112094. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  112095. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  112096. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  112097. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  112098. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  112099. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  112100. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  112101. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  112102. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  112103. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  112104. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  112105. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  112106. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  112107. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  112108. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  112109. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  112110. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  112111. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  112112. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  112113. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  112114. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  112115. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  112116. TK_ALL,
  112117. };
  112118. int h, i;
  112119. if( n<2 ) return TK_ID;
  112120. h = ((charMap(z[0])*4) ^
  112121. (charMap(z[n-1])*3) ^
  112122. n) % 127;
  112123. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  112124. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  112125. testcase( i==0 ); /* REINDEX */
  112126. testcase( i==1 ); /* INDEXED */
  112127. testcase( i==2 ); /* INDEX */
  112128. testcase( i==3 ); /* DESC */
  112129. testcase( i==4 ); /* ESCAPE */
  112130. testcase( i==5 ); /* EACH */
  112131. testcase( i==6 ); /* CHECK */
  112132. testcase( i==7 ); /* KEY */
  112133. testcase( i==8 ); /* BEFORE */
  112134. testcase( i==9 ); /* FOREIGN */
  112135. testcase( i==10 ); /* FOR */
  112136. testcase( i==11 ); /* IGNORE */
  112137. testcase( i==12 ); /* REGEXP */
  112138. testcase( i==13 ); /* EXPLAIN */
  112139. testcase( i==14 ); /* INSTEAD */
  112140. testcase( i==15 ); /* ADD */
  112141. testcase( i==16 ); /* DATABASE */
  112142. testcase( i==17 ); /* AS */
  112143. testcase( i==18 ); /* SELECT */
  112144. testcase( i==19 ); /* TABLE */
  112145. testcase( i==20 ); /* LEFT */
  112146. testcase( i==21 ); /* THEN */
  112147. testcase( i==22 ); /* END */
  112148. testcase( i==23 ); /* DEFERRABLE */
  112149. testcase( i==24 ); /* ELSE */
  112150. testcase( i==25 ); /* EXCEPT */
  112151. testcase( i==26 ); /* TRANSACTION */
  112152. testcase( i==27 ); /* ACTION */
  112153. testcase( i==28 ); /* ON */
  112154. testcase( i==29 ); /* NATURAL */
  112155. testcase( i==30 ); /* ALTER */
  112156. testcase( i==31 ); /* RAISE */
  112157. testcase( i==32 ); /* EXCLUSIVE */
  112158. testcase( i==33 ); /* EXISTS */
  112159. testcase( i==34 ); /* SAVEPOINT */
  112160. testcase( i==35 ); /* INTERSECT */
  112161. testcase( i==36 ); /* TRIGGER */
  112162. testcase( i==37 ); /* REFERENCES */
  112163. testcase( i==38 ); /* CONSTRAINT */
  112164. testcase( i==39 ); /* INTO */
  112165. testcase( i==40 ); /* OFFSET */
  112166. testcase( i==41 ); /* OF */
  112167. testcase( i==42 ); /* SET */
  112168. testcase( i==43 ); /* TEMPORARY */
  112169. testcase( i==44 ); /* TEMP */
  112170. testcase( i==45 ); /* OR */
  112171. testcase( i==46 ); /* UNIQUE */
  112172. testcase( i==47 ); /* QUERY */
  112173. testcase( i==48 ); /* ATTACH */
  112174. testcase( i==49 ); /* HAVING */
  112175. testcase( i==50 ); /* GROUP */
  112176. testcase( i==51 ); /* UPDATE */
  112177. testcase( i==52 ); /* BEGIN */
  112178. testcase( i==53 ); /* INNER */
  112179. testcase( i==54 ); /* RELEASE */
  112180. testcase( i==55 ); /* BETWEEN */
  112181. testcase( i==56 ); /* NOTNULL */
  112182. testcase( i==57 ); /* NOT */
  112183. testcase( i==58 ); /* NO */
  112184. testcase( i==59 ); /* NULL */
  112185. testcase( i==60 ); /* LIKE */
  112186. testcase( i==61 ); /* CASCADE */
  112187. testcase( i==62 ); /* ASC */
  112188. testcase( i==63 ); /* DELETE */
  112189. testcase( i==64 ); /* CASE */
  112190. testcase( i==65 ); /* COLLATE */
  112191. testcase( i==66 ); /* CREATE */
  112192. testcase( i==67 ); /* CURRENT_DATE */
  112193. testcase( i==68 ); /* DETACH */
  112194. testcase( i==69 ); /* IMMEDIATE */
  112195. testcase( i==70 ); /* JOIN */
  112196. testcase( i==71 ); /* INSERT */
  112197. testcase( i==72 ); /* MATCH */
  112198. testcase( i==73 ); /* PLAN */
  112199. testcase( i==74 ); /* ANALYZE */
  112200. testcase( i==75 ); /* PRAGMA */
  112201. testcase( i==76 ); /* ABORT */
  112202. testcase( i==77 ); /* VALUES */
  112203. testcase( i==78 ); /* VIRTUAL */
  112204. testcase( i==79 ); /* LIMIT */
  112205. testcase( i==80 ); /* WHEN */
  112206. testcase( i==81 ); /* WHERE */
  112207. testcase( i==82 ); /* RENAME */
  112208. testcase( i==83 ); /* AFTER */
  112209. testcase( i==84 ); /* REPLACE */
  112210. testcase( i==85 ); /* AND */
  112211. testcase( i==86 ); /* DEFAULT */
  112212. testcase( i==87 ); /* AUTOINCREMENT */
  112213. testcase( i==88 ); /* TO */
  112214. testcase( i==89 ); /* IN */
  112215. testcase( i==90 ); /* CAST */
  112216. testcase( i==91 ); /* COLUMN */
  112217. testcase( i==92 ); /* COMMIT */
  112218. testcase( i==93 ); /* CONFLICT */
  112219. testcase( i==94 ); /* CROSS */
  112220. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  112221. testcase( i==96 ); /* CURRENT_TIME */
  112222. testcase( i==97 ); /* PRIMARY */
  112223. testcase( i==98 ); /* DEFERRED */
  112224. testcase( i==99 ); /* DISTINCT */
  112225. testcase( i==100 ); /* IS */
  112226. testcase( i==101 ); /* DROP */
  112227. testcase( i==102 ); /* FAIL */
  112228. testcase( i==103 ); /* FROM */
  112229. testcase( i==104 ); /* FULL */
  112230. testcase( i==105 ); /* GLOB */
  112231. testcase( i==106 ); /* BY */
  112232. testcase( i==107 ); /* IF */
  112233. testcase( i==108 ); /* ISNULL */
  112234. testcase( i==109 ); /* ORDER */
  112235. testcase( i==110 ); /* RESTRICT */
  112236. testcase( i==111 ); /* OUTER */
  112237. testcase( i==112 ); /* RIGHT */
  112238. testcase( i==113 ); /* ROLLBACK */
  112239. testcase( i==114 ); /* ROW */
  112240. testcase( i==115 ); /* UNION */
  112241. testcase( i==116 ); /* USING */
  112242. testcase( i==117 ); /* VACUUM */
  112243. testcase( i==118 ); /* VIEW */
  112244. testcase( i==119 ); /* INITIALLY */
  112245. testcase( i==120 ); /* ALL */
  112246. return aCode[i];
  112247. }
  112248. }
  112249. return TK_ID;
  112250. }
  112251. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  112252. return keywordCode((char*)z, n);
  112253. }
  112254. #define SQLITE_N_KEYWORD 121
  112255. /************** End of keywordhash.h *****************************************/
  112256. /************** Continuing where we left off in tokenize.c *******************/
  112257. /*
  112258. ** If X is a character that can be used in an identifier then
  112259. ** IdChar(X) will be true. Otherwise it is false.
  112260. **
  112261. ** For ASCII, any character with the high-order bit set is
  112262. ** allowed in an identifier. For 7-bit characters,
  112263. ** sqlite3IsIdChar[X] must be 1.
  112264. **
  112265. ** For EBCDIC, the rules are more complex but have the same
  112266. ** end result.
  112267. **
  112268. ** Ticket #1066. the SQL standard does not allow '$' in the
  112269. ** middle of identfiers. But many SQL implementations do.
  112270. ** SQLite will allow '$' in identifiers for compatibility.
  112271. ** But the feature is undocumented.
  112272. */
  112273. #ifdef SQLITE_ASCII
  112274. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  112275. #endif
  112276. #ifdef SQLITE_EBCDIC
  112277. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  112278. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  112279. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  112280. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  112281. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  112282. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  112283. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  112284. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  112285. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  112286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  112287. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  112288. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  112289. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  112290. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  112291. };
  112292. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  112293. #endif
  112294. /*
  112295. ** Return the length of the token that begins at z[0].
  112296. ** Store the token type in *tokenType before returning.
  112297. */
  112298. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  112299. int i, c;
  112300. switch( *z ){
  112301. case ' ': case '\t': case '\n': case '\f': case '\r': {
  112302. testcase( z[0]==' ' );
  112303. testcase( z[0]=='\t' );
  112304. testcase( z[0]=='\n' );
  112305. testcase( z[0]=='\f' );
  112306. testcase( z[0]=='\r' );
  112307. for(i=1; sqlite3Isspace(z[i]); i++){}
  112308. *tokenType = TK_SPACE;
  112309. return i;
  112310. }
  112311. case '-': {
  112312. if( z[1]=='-' ){
  112313. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  112314. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  112315. return i;
  112316. }
  112317. *tokenType = TK_MINUS;
  112318. return 1;
  112319. }
  112320. case '(': {
  112321. *tokenType = TK_LP;
  112322. return 1;
  112323. }
  112324. case ')': {
  112325. *tokenType = TK_RP;
  112326. return 1;
  112327. }
  112328. case ';': {
  112329. *tokenType = TK_SEMI;
  112330. return 1;
  112331. }
  112332. case '+': {
  112333. *tokenType = TK_PLUS;
  112334. return 1;
  112335. }
  112336. case '*': {
  112337. *tokenType = TK_STAR;
  112338. return 1;
  112339. }
  112340. case '/': {
  112341. if( z[1]!='*' || z[2]==0 ){
  112342. *tokenType = TK_SLASH;
  112343. return 1;
  112344. }
  112345. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  112346. if( c ) i++;
  112347. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  112348. return i;
  112349. }
  112350. case '%': {
  112351. *tokenType = TK_REM;
  112352. return 1;
  112353. }
  112354. case '=': {
  112355. *tokenType = TK_EQ;
  112356. return 1 + (z[1]=='=');
  112357. }
  112358. case '<': {
  112359. if( (c=z[1])=='=' ){
  112360. *tokenType = TK_LE;
  112361. return 2;
  112362. }else if( c=='>' ){
  112363. *tokenType = TK_NE;
  112364. return 2;
  112365. }else if( c=='<' ){
  112366. *tokenType = TK_LSHIFT;
  112367. return 2;
  112368. }else{
  112369. *tokenType = TK_LT;
  112370. return 1;
  112371. }
  112372. }
  112373. case '>': {
  112374. if( (c=z[1])=='=' ){
  112375. *tokenType = TK_GE;
  112376. return 2;
  112377. }else if( c=='>' ){
  112378. *tokenType = TK_RSHIFT;
  112379. return 2;
  112380. }else{
  112381. *tokenType = TK_GT;
  112382. return 1;
  112383. }
  112384. }
  112385. case '!': {
  112386. if( z[1]!='=' ){
  112387. *tokenType = TK_ILLEGAL;
  112388. return 2;
  112389. }else{
  112390. *tokenType = TK_NE;
  112391. return 2;
  112392. }
  112393. }
  112394. case '|': {
  112395. if( z[1]!='|' ){
  112396. *tokenType = TK_BITOR;
  112397. return 1;
  112398. }else{
  112399. *tokenType = TK_CONCAT;
  112400. return 2;
  112401. }
  112402. }
  112403. case ',': {
  112404. *tokenType = TK_COMMA;
  112405. return 1;
  112406. }
  112407. case '&': {
  112408. *tokenType = TK_BITAND;
  112409. return 1;
  112410. }
  112411. case '~': {
  112412. *tokenType = TK_BITNOT;
  112413. return 1;
  112414. }
  112415. case '`':
  112416. case '\'':
  112417. case '"': {
  112418. int delim = z[0];
  112419. testcase( delim=='`' );
  112420. testcase( delim=='\'' );
  112421. testcase( delim=='"' );
  112422. for(i=1; (c=z[i])!=0; i++){
  112423. if( c==delim ){
  112424. if( z[i+1]==delim ){
  112425. i++;
  112426. }else{
  112427. break;
  112428. }
  112429. }
  112430. }
  112431. if( c=='\'' ){
  112432. *tokenType = TK_STRING;
  112433. return i+1;
  112434. }else if( c!=0 ){
  112435. *tokenType = TK_ID;
  112436. return i+1;
  112437. }else{
  112438. *tokenType = TK_ILLEGAL;
  112439. return i;
  112440. }
  112441. }
  112442. case '.': {
  112443. #ifndef SQLITE_OMIT_FLOATING_POINT
  112444. if( !sqlite3Isdigit(z[1]) )
  112445. #endif
  112446. {
  112447. *tokenType = TK_DOT;
  112448. return 1;
  112449. }
  112450. /* If the next character is a digit, this is a floating point
  112451. ** number that begins with ".". Fall thru into the next case */
  112452. }
  112453. case '0': case '1': case '2': case '3': case '4':
  112454. case '5': case '6': case '7': case '8': case '9': {
  112455. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  112456. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  112457. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  112458. testcase( z[0]=='9' );
  112459. *tokenType = TK_INTEGER;
  112460. for(i=0; sqlite3Isdigit(z[i]); i++){}
  112461. #ifndef SQLITE_OMIT_FLOATING_POINT
  112462. if( z[i]=='.' ){
  112463. i++;
  112464. while( sqlite3Isdigit(z[i]) ){ i++; }
  112465. *tokenType = TK_FLOAT;
  112466. }
  112467. if( (z[i]=='e' || z[i]=='E') &&
  112468. ( sqlite3Isdigit(z[i+1])
  112469. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  112470. )
  112471. ){
  112472. i += 2;
  112473. while( sqlite3Isdigit(z[i]) ){ i++; }
  112474. *tokenType = TK_FLOAT;
  112475. }
  112476. #endif
  112477. while( IdChar(z[i]) ){
  112478. *tokenType = TK_ILLEGAL;
  112479. i++;
  112480. }
  112481. return i;
  112482. }
  112483. case '[': {
  112484. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  112485. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  112486. return i;
  112487. }
  112488. case '?': {
  112489. *tokenType = TK_VARIABLE;
  112490. for(i=1; sqlite3Isdigit(z[i]); i++){}
  112491. return i;
  112492. }
  112493. case '#': {
  112494. for(i=1; sqlite3Isdigit(z[i]); i++){}
  112495. if( i>1 ){
  112496. /* Parameters of the form #NNN (where NNN is a number) are used
  112497. ** internally by sqlite3NestedParse. */
  112498. *tokenType = TK_REGISTER;
  112499. return i;
  112500. }
  112501. /* Fall through into the next case if the '#' is not followed by
  112502. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  112503. }
  112504. #ifndef SQLITE_OMIT_TCL_VARIABLE
  112505. case '$':
  112506. #endif
  112507. case '@': /* For compatibility with MS SQL Server */
  112508. case ':': {
  112509. int n = 0;
  112510. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  112511. *tokenType = TK_VARIABLE;
  112512. for(i=1; (c=z[i])!=0; i++){
  112513. if( IdChar(c) ){
  112514. n++;
  112515. #ifndef SQLITE_OMIT_TCL_VARIABLE
  112516. }else if( c=='(' && n>0 ){
  112517. do{
  112518. i++;
  112519. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  112520. if( c==')' ){
  112521. i++;
  112522. }else{
  112523. *tokenType = TK_ILLEGAL;
  112524. }
  112525. break;
  112526. }else if( c==':' && z[i+1]==':' ){
  112527. i++;
  112528. #endif
  112529. }else{
  112530. break;
  112531. }
  112532. }
  112533. if( n==0 ) *tokenType = TK_ILLEGAL;
  112534. return i;
  112535. }
  112536. #ifndef SQLITE_OMIT_BLOB_LITERAL
  112537. case 'x': case 'X': {
  112538. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  112539. if( z[1]=='\'' ){
  112540. *tokenType = TK_BLOB;
  112541. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  112542. if( z[i]!='\'' || i%2 ){
  112543. *tokenType = TK_ILLEGAL;
  112544. while( z[i] && z[i]!='\'' ){ i++; }
  112545. }
  112546. if( z[i] ) i++;
  112547. return i;
  112548. }
  112549. /* Otherwise fall through to the next case */
  112550. }
  112551. #endif
  112552. default: {
  112553. if( !IdChar(*z) ){
  112554. break;
  112555. }
  112556. for(i=1; IdChar(z[i]); i++){}
  112557. *tokenType = keywordCode((char*)z, i);
  112558. return i;
  112559. }
  112560. }
  112561. *tokenType = TK_ILLEGAL;
  112562. return 1;
  112563. }
  112564. /*
  112565. ** Run the parser on the given SQL string. The parser structure is
  112566. ** passed in. An SQLITE_ status code is returned. If an error occurs
  112567. ** then an and attempt is made to write an error message into
  112568. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  112569. ** error message.
  112570. */
  112571. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  112572. int nErr = 0; /* Number of errors encountered */
  112573. int i; /* Loop counter */
  112574. void *pEngine; /* The LEMON-generated LALR(1) parser */
  112575. int tokenType; /* type of the next token */
  112576. int lastTokenParsed = -1; /* type of the previous token */
  112577. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  112578. sqlite3 *db = pParse->db; /* The database connection */
  112579. int mxSqlLen; /* Max length of an SQL string */
  112580. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  112581. if( db->nVdbeActive==0 ){
  112582. db->u1.isInterrupted = 0;
  112583. }
  112584. pParse->rc = SQLITE_OK;
  112585. pParse->zTail = zSql;
  112586. i = 0;
  112587. assert( pzErrMsg!=0 );
  112588. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  112589. if( pEngine==0 ){
  112590. db->mallocFailed = 1;
  112591. return SQLITE_NOMEM;
  112592. }
  112593. assert( pParse->pNewTable==0 );
  112594. assert( pParse->pNewTrigger==0 );
  112595. assert( pParse->nVar==0 );
  112596. assert( pParse->nzVar==0 );
  112597. assert( pParse->azVar==0 );
  112598. enableLookaside = db->lookaside.bEnabled;
  112599. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  112600. while( !db->mallocFailed && zSql[i]!=0 ){
  112601. assert( i>=0 );
  112602. pParse->sLastToken.z = &zSql[i];
  112603. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  112604. i += pParse->sLastToken.n;
  112605. if( i>mxSqlLen ){
  112606. pParse->rc = SQLITE_TOOBIG;
  112607. break;
  112608. }
  112609. switch( tokenType ){
  112610. case TK_SPACE: {
  112611. if( db->u1.isInterrupted ){
  112612. sqlite3ErrorMsg(pParse, "interrupt");
  112613. pParse->rc = SQLITE_INTERRUPT;
  112614. goto abort_parse;
  112615. }
  112616. break;
  112617. }
  112618. case TK_ILLEGAL: {
  112619. sqlite3DbFree(db, *pzErrMsg);
  112620. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  112621. &pParse->sLastToken);
  112622. nErr++;
  112623. goto abort_parse;
  112624. }
  112625. case TK_SEMI: {
  112626. pParse->zTail = &zSql[i];
  112627. /* Fall thru into the default case */
  112628. }
  112629. default: {
  112630. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  112631. lastTokenParsed = tokenType;
  112632. if( pParse->rc!=SQLITE_OK ){
  112633. goto abort_parse;
  112634. }
  112635. break;
  112636. }
  112637. }
  112638. }
  112639. abort_parse:
  112640. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  112641. if( lastTokenParsed!=TK_SEMI ){
  112642. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  112643. pParse->zTail = &zSql[i];
  112644. }
  112645. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  112646. }
  112647. #ifdef YYTRACKMAXSTACKDEPTH
  112648. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  112649. sqlite3ParserStackPeak(pEngine)
  112650. );
  112651. #endif /* YYDEBUG */
  112652. sqlite3ParserFree(pEngine, sqlite3_free);
  112653. db->lookaside.bEnabled = enableLookaside;
  112654. if( db->mallocFailed ){
  112655. pParse->rc = SQLITE_NOMEM;
  112656. }
  112657. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  112658. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  112659. }
  112660. assert( pzErrMsg!=0 );
  112661. if( pParse->zErrMsg ){
  112662. *pzErrMsg = pParse->zErrMsg;
  112663. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  112664. pParse->zErrMsg = 0;
  112665. nErr++;
  112666. }
  112667. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  112668. sqlite3VdbeDelete(pParse->pVdbe);
  112669. pParse->pVdbe = 0;
  112670. }
  112671. #ifndef SQLITE_OMIT_SHARED_CACHE
  112672. if( pParse->nested==0 ){
  112673. sqlite3DbFree(db, pParse->aTableLock);
  112674. pParse->aTableLock = 0;
  112675. pParse->nTableLock = 0;
  112676. }
  112677. #endif
  112678. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112679. sqlite3_free(pParse->apVtabLock);
  112680. #endif
  112681. if( !IN_DECLARE_VTAB ){
  112682. /* If the pParse->declareVtab flag is set, do not delete any table
  112683. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  112684. ** will take responsibility for freeing the Table structure.
  112685. */
  112686. sqlite3DeleteTable(db, pParse->pNewTable);
  112687. }
  112688. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  112689. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  112690. sqlite3DbFree(db, pParse->azVar);
  112691. sqlite3DbFree(db, pParse->aAlias);
  112692. while( pParse->pAinc ){
  112693. AutoincInfo *p = pParse->pAinc;
  112694. pParse->pAinc = p->pNext;
  112695. sqlite3DbFree(db, p);
  112696. }
  112697. while( pParse->pZombieTab ){
  112698. Table *p = pParse->pZombieTab;
  112699. pParse->pZombieTab = p->pNextZombie;
  112700. sqlite3DeleteTable(db, p);
  112701. }
  112702. if( nErr>0 && pParse->rc==SQLITE_OK ){
  112703. pParse->rc = SQLITE_ERROR;
  112704. }
  112705. return nErr;
  112706. }
  112707. /************** End of tokenize.c ********************************************/
  112708. /************** Begin file complete.c ****************************************/
  112709. /*
  112710. ** 2001 September 15
  112711. **
  112712. ** The author disclaims copyright to this source code. In place of
  112713. ** a legal notice, here is a blessing:
  112714. **
  112715. ** May you do good and not evil.
  112716. ** May you find forgiveness for yourself and forgive others.
  112717. ** May you share freely, never taking more than you give.
  112718. **
  112719. *************************************************************************
  112720. ** An tokenizer for SQL
  112721. **
  112722. ** This file contains C code that implements the sqlite3_complete() API.
  112723. ** This code used to be part of the tokenizer.c source file. But by
  112724. ** separating it out, the code will be automatically omitted from
  112725. ** static links that do not use it.
  112726. */
  112727. #ifndef SQLITE_OMIT_COMPLETE
  112728. /*
  112729. ** This is defined in tokenize.c. We just have to import the definition.
  112730. */
  112731. #ifndef SQLITE_AMALGAMATION
  112732. #ifdef SQLITE_ASCII
  112733. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  112734. #endif
  112735. #ifdef SQLITE_EBCDIC
  112736. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  112737. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  112738. #endif
  112739. #endif /* SQLITE_AMALGAMATION */
  112740. /*
  112741. ** Token types used by the sqlite3_complete() routine. See the header
  112742. ** comments on that procedure for additional information.
  112743. */
  112744. #define tkSEMI 0
  112745. #define tkWS 1
  112746. #define tkOTHER 2
  112747. #ifndef SQLITE_OMIT_TRIGGER
  112748. #define tkEXPLAIN 3
  112749. #define tkCREATE 4
  112750. #define tkTEMP 5
  112751. #define tkTRIGGER 6
  112752. #define tkEND 7
  112753. #endif
  112754. /*
  112755. ** Return TRUE if the given SQL string ends in a semicolon.
  112756. **
  112757. ** Special handling is require for CREATE TRIGGER statements.
  112758. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  112759. ** must end with ";END;".
  112760. **
  112761. ** This implementation uses a state machine with 8 states:
  112762. **
  112763. ** (0) INVALID We have not yet seen a non-whitespace character.
  112764. **
  112765. ** (1) START At the beginning or end of an SQL statement. This routine
  112766. ** returns 1 if it ends in the START state and 0 if it ends
  112767. ** in any other state.
  112768. **
  112769. ** (2) NORMAL We are in the middle of statement which ends with a single
  112770. ** semicolon.
  112771. **
  112772. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  112773. ** a statement.
  112774. **
  112775. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  112776. ** statement, possibly preceeded by EXPLAIN and/or followed by
  112777. ** TEMP or TEMPORARY
  112778. **
  112779. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  112780. ** ended by a semicolon, the keyword END, and another semicolon.
  112781. **
  112782. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  112783. ** the end of a trigger definition.
  112784. **
  112785. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  112786. ** of a trigger difinition.
  112787. **
  112788. ** Transitions between states above are determined by tokens extracted
  112789. ** from the input. The following tokens are significant:
  112790. **
  112791. ** (0) tkSEMI A semicolon.
  112792. ** (1) tkWS Whitespace.
  112793. ** (2) tkOTHER Any other SQL token.
  112794. ** (3) tkEXPLAIN The "explain" keyword.
  112795. ** (4) tkCREATE The "create" keyword.
  112796. ** (5) tkTEMP The "temp" or "temporary" keyword.
  112797. ** (6) tkTRIGGER The "trigger" keyword.
  112798. ** (7) tkEND The "end" keyword.
  112799. **
  112800. ** Whitespace never causes a state transition and is always ignored.
  112801. ** This means that a SQL string of all whitespace is invalid.
  112802. **
  112803. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  112804. ** to recognize the end of a trigger can be omitted. All we have to do
  112805. ** is look for a semicolon that is not part of an string or comment.
  112806. */
  112807. SQLITE_API int sqlite3_complete(const char *zSql){
  112808. u8 state = 0; /* Current state, using numbers defined in header comment */
  112809. u8 token; /* Value of the next token */
  112810. #ifndef SQLITE_OMIT_TRIGGER
  112811. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  112812. ** statement. This is the normal case.
  112813. */
  112814. static const u8 trans[8][8] = {
  112815. /* Token: */
  112816. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  112817. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  112818. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  112819. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  112820. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  112821. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  112822. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  112823. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  112824. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  112825. };
  112826. #else
  112827. /* If triggers are not supported by this compile then the statement machine
  112828. ** used to detect the end of a statement is much simplier
  112829. */
  112830. static const u8 trans[3][3] = {
  112831. /* Token: */
  112832. /* State: ** SEMI WS OTHER */
  112833. /* 0 INVALID: */ { 1, 0, 2, },
  112834. /* 1 START: */ { 1, 1, 2, },
  112835. /* 2 NORMAL: */ { 1, 2, 2, },
  112836. };
  112837. #endif /* SQLITE_OMIT_TRIGGER */
  112838. while( *zSql ){
  112839. switch( *zSql ){
  112840. case ';': { /* A semicolon */
  112841. token = tkSEMI;
  112842. break;
  112843. }
  112844. case ' ':
  112845. case '\r':
  112846. case '\t':
  112847. case '\n':
  112848. case '\f': { /* White space is ignored */
  112849. token = tkWS;
  112850. break;
  112851. }
  112852. case '/': { /* C-style comments */
  112853. if( zSql[1]!='*' ){
  112854. token = tkOTHER;
  112855. break;
  112856. }
  112857. zSql += 2;
  112858. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  112859. if( zSql[0]==0 ) return 0;
  112860. zSql++;
  112861. token = tkWS;
  112862. break;
  112863. }
  112864. case '-': { /* SQL-style comments from "--" to end of line */
  112865. if( zSql[1]!='-' ){
  112866. token = tkOTHER;
  112867. break;
  112868. }
  112869. while( *zSql && *zSql!='\n' ){ zSql++; }
  112870. if( *zSql==0 ) return state==1;
  112871. token = tkWS;
  112872. break;
  112873. }
  112874. case '[': { /* Microsoft-style identifiers in [...] */
  112875. zSql++;
  112876. while( *zSql && *zSql!=']' ){ zSql++; }
  112877. if( *zSql==0 ) return 0;
  112878. token = tkOTHER;
  112879. break;
  112880. }
  112881. case '`': /* Grave-accent quoted symbols used by MySQL */
  112882. case '"': /* single- and double-quoted strings */
  112883. case '\'': {
  112884. int c = *zSql;
  112885. zSql++;
  112886. while( *zSql && *zSql!=c ){ zSql++; }
  112887. if( *zSql==0 ) return 0;
  112888. token = tkOTHER;
  112889. break;
  112890. }
  112891. default: {
  112892. #ifdef SQLITE_EBCDIC
  112893. unsigned char c;
  112894. #endif
  112895. if( IdChar((u8)*zSql) ){
  112896. /* Keywords and unquoted identifiers */
  112897. int nId;
  112898. for(nId=1; IdChar(zSql[nId]); nId++){}
  112899. #ifdef SQLITE_OMIT_TRIGGER
  112900. token = tkOTHER;
  112901. #else
  112902. switch( *zSql ){
  112903. case 'c': case 'C': {
  112904. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  112905. token = tkCREATE;
  112906. }else{
  112907. token = tkOTHER;
  112908. }
  112909. break;
  112910. }
  112911. case 't': case 'T': {
  112912. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  112913. token = tkTRIGGER;
  112914. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  112915. token = tkTEMP;
  112916. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  112917. token = tkTEMP;
  112918. }else{
  112919. token = tkOTHER;
  112920. }
  112921. break;
  112922. }
  112923. case 'e': case 'E': {
  112924. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  112925. token = tkEND;
  112926. }else
  112927. #ifndef SQLITE_OMIT_EXPLAIN
  112928. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  112929. token = tkEXPLAIN;
  112930. }else
  112931. #endif
  112932. {
  112933. token = tkOTHER;
  112934. }
  112935. break;
  112936. }
  112937. default: {
  112938. token = tkOTHER;
  112939. break;
  112940. }
  112941. }
  112942. #endif /* SQLITE_OMIT_TRIGGER */
  112943. zSql += nId-1;
  112944. }else{
  112945. /* Operators and special symbols */
  112946. token = tkOTHER;
  112947. }
  112948. break;
  112949. }
  112950. }
  112951. state = trans[state][token];
  112952. zSql++;
  112953. }
  112954. return state==1;
  112955. }
  112956. #ifndef SQLITE_OMIT_UTF16
  112957. /*
  112958. ** This routine is the same as the sqlite3_complete() routine described
  112959. ** above, except that the parameter is required to be UTF-16 encoded, not
  112960. ** UTF-8.
  112961. */
  112962. SQLITE_API int sqlite3_complete16(const void *zSql){
  112963. sqlite3_value *pVal;
  112964. char const *zSql8;
  112965. int rc = SQLITE_NOMEM;
  112966. #ifndef SQLITE_OMIT_AUTOINIT
  112967. rc = sqlite3_initialize();
  112968. if( rc ) return rc;
  112969. #endif
  112970. pVal = sqlite3ValueNew(0);
  112971. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  112972. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  112973. if( zSql8 ){
  112974. rc = sqlite3_complete(zSql8);
  112975. }else{
  112976. rc = SQLITE_NOMEM;
  112977. }
  112978. sqlite3ValueFree(pVal);
  112979. return sqlite3ApiExit(0, rc);
  112980. }
  112981. #endif /* SQLITE_OMIT_UTF16 */
  112982. #endif /* SQLITE_OMIT_COMPLETE */
  112983. /************** End of complete.c ********************************************/
  112984. /************** Begin file main.c ********************************************/
  112985. /*
  112986. ** 2001 September 15
  112987. **
  112988. ** The author disclaims copyright to this source code. In place of
  112989. ** a legal notice, here is a blessing:
  112990. **
  112991. ** May you do good and not evil.
  112992. ** May you find forgiveness for yourself and forgive others.
  112993. ** May you share freely, never taking more than you give.
  112994. **
  112995. *************************************************************************
  112996. ** Main file for the SQLite library. The routines in this file
  112997. ** implement the programmer interface to the library. Routines in
  112998. ** other files are for internal use by SQLite and should not be
  112999. ** accessed by users of the library.
  113000. */
  113001. #ifdef SQLITE_ENABLE_FTS3
  113002. /************** Include fts3.h in the middle of main.c ***********************/
  113003. /************** Begin file fts3.h ********************************************/
  113004. /*
  113005. ** 2006 Oct 10
  113006. **
  113007. ** The author disclaims copyright to this source code. In place of
  113008. ** a legal notice, here is a blessing:
  113009. **
  113010. ** May you do good and not evil.
  113011. ** May you find forgiveness for yourself and forgive others.
  113012. ** May you share freely, never taking more than you give.
  113013. **
  113014. ******************************************************************************
  113015. **
  113016. ** This header file is used by programs that want to link against the
  113017. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  113018. */
  113019. #if 0
  113020. extern "C" {
  113021. #endif /* __cplusplus */
  113022. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  113023. #if 0
  113024. } /* extern "C" */
  113025. #endif /* __cplusplus */
  113026. /************** End of fts3.h ************************************************/
  113027. /************** Continuing where we left off in main.c ***********************/
  113028. #endif
  113029. #ifdef SQLITE_ENABLE_RTREE
  113030. /************** Include rtree.h in the middle of main.c **********************/
  113031. /************** Begin file rtree.h *******************************************/
  113032. /*
  113033. ** 2008 May 26
  113034. **
  113035. ** The author disclaims copyright to this source code. In place of
  113036. ** a legal notice, here is a blessing:
  113037. **
  113038. ** May you do good and not evil.
  113039. ** May you find forgiveness for yourself and forgive others.
  113040. ** May you share freely, never taking more than you give.
  113041. **
  113042. ******************************************************************************
  113043. **
  113044. ** This header file is used by programs that want to link against the
  113045. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  113046. */
  113047. #if 0
  113048. extern "C" {
  113049. #endif /* __cplusplus */
  113050. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  113051. #if 0
  113052. } /* extern "C" */
  113053. #endif /* __cplusplus */
  113054. /************** End of rtree.h ***********************************************/
  113055. /************** Continuing where we left off in main.c ***********************/
  113056. #endif
  113057. #ifdef SQLITE_ENABLE_ICU
  113058. /************** Include sqliteicu.h in the middle of main.c ******************/
  113059. /************** Begin file sqliteicu.h ***************************************/
  113060. /*
  113061. ** 2008 May 26
  113062. **
  113063. ** The author disclaims copyright to this source code. In place of
  113064. ** a legal notice, here is a blessing:
  113065. **
  113066. ** May you do good and not evil.
  113067. ** May you find forgiveness for yourself and forgive others.
  113068. ** May you share freely, never taking more than you give.
  113069. **
  113070. ******************************************************************************
  113071. **
  113072. ** This header file is used by programs that want to link against the
  113073. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  113074. */
  113075. #if 0
  113076. extern "C" {
  113077. #endif /* __cplusplus */
  113078. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  113079. #if 0
  113080. } /* extern "C" */
  113081. #endif /* __cplusplus */
  113082. /************** End of sqliteicu.h *******************************************/
  113083. /************** Continuing where we left off in main.c ***********************/
  113084. #endif
  113085. #ifndef SQLITE_AMALGAMATION
  113086. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  113087. ** contains the text of SQLITE_VERSION macro.
  113088. */
  113089. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  113090. #endif
  113091. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  113092. ** a pointer to the to the sqlite3_version[] string constant.
  113093. */
  113094. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  113095. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  113096. ** pointer to a string constant whose value is the same as the
  113097. ** SQLITE_SOURCE_ID C preprocessor macro.
  113098. */
  113099. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  113100. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  113101. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  113102. */
  113103. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  113104. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  113105. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  113106. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  113107. */
  113108. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  113109. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  113110. /*
  113111. ** If the following function pointer is not NULL and if
  113112. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  113113. ** I/O active are written using this function. These messages
  113114. ** are intended for debugging activity only.
  113115. */
  113116. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  113117. #endif
  113118. /*
  113119. ** If the following global variable points to a string which is the
  113120. ** name of a directory, then that directory will be used to store
  113121. ** temporary files.
  113122. **
  113123. ** See also the "PRAGMA temp_store_directory" SQL command.
  113124. */
  113125. SQLITE_API char *sqlite3_temp_directory = 0;
  113126. /*
  113127. ** If the following global variable points to a string which is the
  113128. ** name of a directory, then that directory will be used to store
  113129. ** all database files specified with a relative pathname.
  113130. **
  113131. ** See also the "PRAGMA data_store_directory" SQL command.
  113132. */
  113133. SQLITE_API char *sqlite3_data_directory = 0;
  113134. /*
  113135. ** Initialize SQLite.
  113136. **
  113137. ** This routine must be called to initialize the memory allocation,
  113138. ** VFS, and mutex subsystems prior to doing any serious work with
  113139. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  113140. ** this routine will be called automatically by key routines such as
  113141. ** sqlite3_open().
  113142. **
  113143. ** This routine is a no-op except on its very first call for the process,
  113144. ** or for the first call after a call to sqlite3_shutdown.
  113145. **
  113146. ** The first thread to call this routine runs the initialization to
  113147. ** completion. If subsequent threads call this routine before the first
  113148. ** thread has finished the initialization process, then the subsequent
  113149. ** threads must block until the first thread finishes with the initialization.
  113150. **
  113151. ** The first thread might call this routine recursively. Recursive
  113152. ** calls to this routine should not block, of course. Otherwise the
  113153. ** initialization process would never complete.
  113154. **
  113155. ** Let X be the first thread to enter this routine. Let Y be some other
  113156. ** thread. Then while the initial invocation of this routine by X is
  113157. ** incomplete, it is required that:
  113158. **
  113159. ** * Calls to this routine from Y must block until the outer-most
  113160. ** call by X completes.
  113161. **
  113162. ** * Recursive calls to this routine from thread X return immediately
  113163. ** without blocking.
  113164. */
  113165. SQLITE_API int sqlite3_initialize(void){
  113166. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  113167. int rc; /* Result code */
  113168. #ifdef SQLITE_EXTRA_INIT
  113169. int bRunExtraInit = 0; /* Extra initialization needed */
  113170. #endif
  113171. #ifdef SQLITE_OMIT_WSD
  113172. rc = sqlite3_wsd_init(4096, 24);
  113173. if( rc!=SQLITE_OK ){
  113174. return rc;
  113175. }
  113176. #endif
  113177. /* If SQLite is already completely initialized, then this call
  113178. ** to sqlite3_initialize() should be a no-op. But the initialization
  113179. ** must be complete. So isInit must not be set until the very end
  113180. ** of this routine.
  113181. */
  113182. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  113183. #ifdef SQLITE_ENABLE_SQLLOG
  113184. {
  113185. extern void sqlite3_init_sqllog(void);
  113186. sqlite3_init_sqllog();
  113187. }
  113188. #endif
  113189. /* Make sure the mutex subsystem is initialized. If unable to
  113190. ** initialize the mutex subsystem, return early with the error.
  113191. ** If the system is so sick that we are unable to allocate a mutex,
  113192. ** there is not much SQLite is going to be able to do.
  113193. **
  113194. ** The mutex subsystem must take care of serializing its own
  113195. ** initialization.
  113196. */
  113197. rc = sqlite3MutexInit();
  113198. if( rc ) return rc;
  113199. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  113200. ** This operation is protected by the STATIC_MASTER mutex. Note that
  113201. ** MutexAlloc() is called for a static mutex prior to initializing the
  113202. ** malloc subsystem - this implies that the allocation of a static
  113203. ** mutex must not require support from the malloc subsystem.
  113204. */
  113205. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  113206. sqlite3_mutex_enter(pMaster);
  113207. sqlite3GlobalConfig.isMutexInit = 1;
  113208. if( !sqlite3GlobalConfig.isMallocInit ){
  113209. rc = sqlite3MallocInit();
  113210. }
  113211. if( rc==SQLITE_OK ){
  113212. sqlite3GlobalConfig.isMallocInit = 1;
  113213. if( !sqlite3GlobalConfig.pInitMutex ){
  113214. sqlite3GlobalConfig.pInitMutex =
  113215. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  113216. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  113217. rc = SQLITE_NOMEM;
  113218. }
  113219. }
  113220. }
  113221. if( rc==SQLITE_OK ){
  113222. sqlite3GlobalConfig.nRefInitMutex++;
  113223. }
  113224. sqlite3_mutex_leave(pMaster);
  113225. /* If rc is not SQLITE_OK at this point, then either the malloc
  113226. ** subsystem could not be initialized or the system failed to allocate
  113227. ** the pInitMutex mutex. Return an error in either case. */
  113228. if( rc!=SQLITE_OK ){
  113229. return rc;
  113230. }
  113231. /* Do the rest of the initialization under the recursive mutex so
  113232. ** that we will be able to handle recursive calls into
  113233. ** sqlite3_initialize(). The recursive calls normally come through
  113234. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  113235. ** recursive calls might also be possible.
  113236. **
  113237. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  113238. ** to the xInit method, so the xInit method need not be threadsafe.
  113239. **
  113240. ** The following mutex is what serializes access to the appdef pcache xInit
  113241. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  113242. ** call to sqlite3PcacheInitialize().
  113243. */
  113244. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  113245. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  113246. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  113247. sqlite3GlobalConfig.inProgress = 1;
  113248. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  113249. sqlite3RegisterGlobalFunctions();
  113250. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  113251. rc = sqlite3PcacheInitialize();
  113252. }
  113253. if( rc==SQLITE_OK ){
  113254. sqlite3GlobalConfig.isPCacheInit = 1;
  113255. rc = sqlite3OsInit();
  113256. }
  113257. if( rc==SQLITE_OK ){
  113258. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  113259. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  113260. sqlite3GlobalConfig.isInit = 1;
  113261. #ifdef SQLITE_EXTRA_INIT
  113262. bRunExtraInit = 1;
  113263. #endif
  113264. }
  113265. sqlite3GlobalConfig.inProgress = 0;
  113266. }
  113267. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  113268. /* Go back under the static mutex and clean up the recursive
  113269. ** mutex to prevent a resource leak.
  113270. */
  113271. sqlite3_mutex_enter(pMaster);
  113272. sqlite3GlobalConfig.nRefInitMutex--;
  113273. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  113274. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  113275. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  113276. sqlite3GlobalConfig.pInitMutex = 0;
  113277. }
  113278. sqlite3_mutex_leave(pMaster);
  113279. /* The following is just a sanity check to make sure SQLite has
  113280. ** been compiled correctly. It is important to run this code, but
  113281. ** we don't want to run it too often and soak up CPU cycles for no
  113282. ** reason. So we run it once during initialization.
  113283. */
  113284. #ifndef NDEBUG
  113285. #ifndef SQLITE_OMIT_FLOATING_POINT
  113286. /* This section of code's only "output" is via assert() statements. */
  113287. if ( rc==SQLITE_OK ){
  113288. u64 x = (((u64)1)<<63)-1;
  113289. double y;
  113290. assert(sizeof(x)==8);
  113291. assert(sizeof(x)==sizeof(y));
  113292. memcpy(&y, &x, 8);
  113293. assert( sqlite3IsNaN(y) );
  113294. }
  113295. #endif
  113296. #endif
  113297. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  113298. ** compile-time option.
  113299. */
  113300. #ifdef SQLITE_EXTRA_INIT
  113301. if( bRunExtraInit ){
  113302. int SQLITE_EXTRA_INIT(const char*);
  113303. rc = SQLITE_EXTRA_INIT(0);
  113304. }
  113305. #endif
  113306. return rc;
  113307. }
  113308. /*
  113309. ** Undo the effects of sqlite3_initialize(). Must not be called while
  113310. ** there are outstanding database connections or memory allocations or
  113311. ** while any part of SQLite is otherwise in use in any thread. This
  113312. ** routine is not threadsafe. But it is safe to invoke this routine
  113313. ** on when SQLite is already shut down. If SQLite is already shut down
  113314. ** when this routine is invoked, then this routine is a harmless no-op.
  113315. */
  113316. SQLITE_API int sqlite3_shutdown(void){
  113317. if( sqlite3GlobalConfig.isInit ){
  113318. #ifdef SQLITE_EXTRA_SHUTDOWN
  113319. void SQLITE_EXTRA_SHUTDOWN(void);
  113320. SQLITE_EXTRA_SHUTDOWN();
  113321. #endif
  113322. sqlite3_os_end();
  113323. sqlite3_reset_auto_extension();
  113324. sqlite3GlobalConfig.isInit = 0;
  113325. }
  113326. if( sqlite3GlobalConfig.isPCacheInit ){
  113327. sqlite3PcacheShutdown();
  113328. sqlite3GlobalConfig.isPCacheInit = 0;
  113329. }
  113330. if( sqlite3GlobalConfig.isMallocInit ){
  113331. sqlite3MallocEnd();
  113332. sqlite3GlobalConfig.isMallocInit = 0;
  113333. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  113334. /* The heap subsystem has now been shutdown and these values are supposed
  113335. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  113336. ** which would rely on that heap subsystem; therefore, make sure these
  113337. ** values cannot refer to heap memory that was just invalidated when the
  113338. ** heap subsystem was shutdown. This is only done if the current call to
  113339. ** this function resulted in the heap subsystem actually being shutdown.
  113340. */
  113341. sqlite3_data_directory = 0;
  113342. sqlite3_temp_directory = 0;
  113343. #endif
  113344. }
  113345. if( sqlite3GlobalConfig.isMutexInit ){
  113346. sqlite3MutexEnd();
  113347. sqlite3GlobalConfig.isMutexInit = 0;
  113348. }
  113349. return SQLITE_OK;
  113350. }
  113351. /*
  113352. ** This API allows applications to modify the global configuration of
  113353. ** the SQLite library at run-time.
  113354. **
  113355. ** This routine should only be called when there are no outstanding
  113356. ** database connections or memory allocations. This routine is not
  113357. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  113358. ** behavior.
  113359. */
  113360. SQLITE_API int sqlite3_config(int op, ...){
  113361. va_list ap;
  113362. int rc = SQLITE_OK;
  113363. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  113364. ** the SQLite library is in use. */
  113365. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  113366. va_start(ap, op);
  113367. switch( op ){
  113368. /* Mutex configuration options are only available in a threadsafe
  113369. ** compile.
  113370. */
  113371. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  113372. case SQLITE_CONFIG_SINGLETHREAD: {
  113373. /* Disable all mutexing */
  113374. sqlite3GlobalConfig.bCoreMutex = 0;
  113375. sqlite3GlobalConfig.bFullMutex = 0;
  113376. break;
  113377. }
  113378. case SQLITE_CONFIG_MULTITHREAD: {
  113379. /* Disable mutexing of database connections */
  113380. /* Enable mutexing of core data structures */
  113381. sqlite3GlobalConfig.bCoreMutex = 1;
  113382. sqlite3GlobalConfig.bFullMutex = 0;
  113383. break;
  113384. }
  113385. case SQLITE_CONFIG_SERIALIZED: {
  113386. /* Enable all mutexing */
  113387. sqlite3GlobalConfig.bCoreMutex = 1;
  113388. sqlite3GlobalConfig.bFullMutex = 1;
  113389. break;
  113390. }
  113391. case SQLITE_CONFIG_MUTEX: {
  113392. /* Specify an alternative mutex implementation */
  113393. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  113394. break;
  113395. }
  113396. case SQLITE_CONFIG_GETMUTEX: {
  113397. /* Retrieve the current mutex implementation */
  113398. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  113399. break;
  113400. }
  113401. #endif
  113402. case SQLITE_CONFIG_MALLOC: {
  113403. /* Specify an alternative malloc implementation */
  113404. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  113405. break;
  113406. }
  113407. case SQLITE_CONFIG_GETMALLOC: {
  113408. /* Retrieve the current malloc() implementation */
  113409. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  113410. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  113411. break;
  113412. }
  113413. case SQLITE_CONFIG_MEMSTATUS: {
  113414. /* Enable or disable the malloc status collection */
  113415. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  113416. break;
  113417. }
  113418. case SQLITE_CONFIG_SCRATCH: {
  113419. /* Designate a buffer for scratch memory space */
  113420. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  113421. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  113422. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  113423. break;
  113424. }
  113425. case SQLITE_CONFIG_PAGECACHE: {
  113426. /* Designate a buffer for page cache memory space */
  113427. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  113428. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  113429. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  113430. break;
  113431. }
  113432. case SQLITE_CONFIG_PCACHE: {
  113433. /* no-op */
  113434. break;
  113435. }
  113436. case SQLITE_CONFIG_GETPCACHE: {
  113437. /* now an error */
  113438. rc = SQLITE_ERROR;
  113439. break;
  113440. }
  113441. case SQLITE_CONFIG_PCACHE2: {
  113442. /* Specify an alternative page cache implementation */
  113443. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  113444. break;
  113445. }
  113446. case SQLITE_CONFIG_GETPCACHE2: {
  113447. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  113448. sqlite3PCacheSetDefault();
  113449. }
  113450. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  113451. break;
  113452. }
  113453. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  113454. case SQLITE_CONFIG_HEAP: {
  113455. /* Designate a buffer for heap memory space */
  113456. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  113457. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  113458. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  113459. if( sqlite3GlobalConfig.mnReq<1 ){
  113460. sqlite3GlobalConfig.mnReq = 1;
  113461. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  113462. /* cap min request size at 2^12 */
  113463. sqlite3GlobalConfig.mnReq = (1<<12);
  113464. }
  113465. if( sqlite3GlobalConfig.pHeap==0 ){
  113466. /* If the heap pointer is NULL, then restore the malloc implementation
  113467. ** back to NULL pointers too. This will cause the malloc to go
  113468. ** back to its default implementation when sqlite3_initialize() is
  113469. ** run.
  113470. */
  113471. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  113472. }else{
  113473. /* The heap pointer is not NULL, then install one of the
  113474. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  113475. ** least one of these methods is currently enabled.
  113476. */
  113477. #ifdef SQLITE_ENABLE_MEMSYS3
  113478. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  113479. #endif
  113480. #ifdef SQLITE_ENABLE_MEMSYS5
  113481. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  113482. #endif
  113483. }
  113484. break;
  113485. }
  113486. #endif
  113487. case SQLITE_CONFIG_LOOKASIDE: {
  113488. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  113489. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  113490. break;
  113491. }
  113492. /* Record a pointer to the logger function and its first argument.
  113493. ** The default is NULL. Logging is disabled if the function pointer is
  113494. ** NULL.
  113495. */
  113496. case SQLITE_CONFIG_LOG: {
  113497. /* MSVC is picky about pulling func ptrs from va lists.
  113498. ** http://support.microsoft.com/kb/47961
  113499. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  113500. */
  113501. typedef void(*LOGFUNC_t)(void*,int,const char*);
  113502. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  113503. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  113504. break;
  113505. }
  113506. case SQLITE_CONFIG_URI: {
  113507. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  113508. break;
  113509. }
  113510. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  113511. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  113512. break;
  113513. }
  113514. #ifdef SQLITE_ENABLE_SQLLOG
  113515. case SQLITE_CONFIG_SQLLOG: {
  113516. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  113517. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  113518. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  113519. break;
  113520. }
  113521. #endif
  113522. case SQLITE_CONFIG_MMAP_SIZE: {
  113523. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  113524. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  113525. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  113526. mxMmap = SQLITE_MAX_MMAP_SIZE;
  113527. }
  113528. sqlite3GlobalConfig.mxMmap = mxMmap;
  113529. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  113530. if( szMmap>mxMmap) szMmap = mxMmap;
  113531. sqlite3GlobalConfig.szMmap = szMmap;
  113532. break;
  113533. }
  113534. default: {
  113535. rc = SQLITE_ERROR;
  113536. break;
  113537. }
  113538. }
  113539. va_end(ap);
  113540. return rc;
  113541. }
  113542. /*
  113543. ** Set up the lookaside buffers for a database connection.
  113544. ** Return SQLITE_OK on success.
  113545. ** If lookaside is already active, return SQLITE_BUSY.
  113546. **
  113547. ** The sz parameter is the number of bytes in each lookaside slot.
  113548. ** The cnt parameter is the number of slots. If pStart is NULL the
  113549. ** space for the lookaside memory is obtained from sqlite3_malloc().
  113550. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  113551. ** the lookaside memory.
  113552. */
  113553. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  113554. void *pStart;
  113555. if( db->lookaside.nOut ){
  113556. return SQLITE_BUSY;
  113557. }
  113558. /* Free any existing lookaside buffer for this handle before
  113559. ** allocating a new one so we don't have to have space for
  113560. ** both at the same time.
  113561. */
  113562. if( db->lookaside.bMalloced ){
  113563. sqlite3_free(db->lookaside.pStart);
  113564. }
  113565. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  113566. ** than a pointer to be useful.
  113567. */
  113568. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  113569. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  113570. if( cnt<0 ) cnt = 0;
  113571. if( sz==0 || cnt==0 ){
  113572. sz = 0;
  113573. pStart = 0;
  113574. }else if( pBuf==0 ){
  113575. sqlite3BeginBenignMalloc();
  113576. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  113577. sqlite3EndBenignMalloc();
  113578. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  113579. }else{
  113580. pStart = pBuf;
  113581. }
  113582. db->lookaside.pStart = pStart;
  113583. db->lookaside.pFree = 0;
  113584. db->lookaside.sz = (u16)sz;
  113585. if( pStart ){
  113586. int i;
  113587. LookasideSlot *p;
  113588. assert( sz > (int)sizeof(LookasideSlot*) );
  113589. p = (LookasideSlot*)pStart;
  113590. for(i=cnt-1; i>=0; i--){
  113591. p->pNext = db->lookaside.pFree;
  113592. db->lookaside.pFree = p;
  113593. p = (LookasideSlot*)&((u8*)p)[sz];
  113594. }
  113595. db->lookaside.pEnd = p;
  113596. db->lookaside.bEnabled = 1;
  113597. db->lookaside.bMalloced = pBuf==0 ?1:0;
  113598. }else{
  113599. db->lookaside.pEnd = 0;
  113600. db->lookaside.bEnabled = 0;
  113601. db->lookaside.bMalloced = 0;
  113602. }
  113603. return SQLITE_OK;
  113604. }
  113605. /*
  113606. ** Return the mutex associated with a database connection.
  113607. */
  113608. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  113609. return db->mutex;
  113610. }
  113611. /*
  113612. ** Free up as much memory as we can from the given database
  113613. ** connection.
  113614. */
  113615. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  113616. int i;
  113617. sqlite3_mutex_enter(db->mutex);
  113618. sqlite3BtreeEnterAll(db);
  113619. for(i=0; i<db->nDb; i++){
  113620. Btree *pBt = db->aDb[i].pBt;
  113621. if( pBt ){
  113622. Pager *pPager = sqlite3BtreePager(pBt);
  113623. sqlite3PagerShrink(pPager);
  113624. }
  113625. }
  113626. sqlite3BtreeLeaveAll(db);
  113627. sqlite3_mutex_leave(db->mutex);
  113628. return SQLITE_OK;
  113629. }
  113630. /*
  113631. ** Configuration settings for an individual database connection
  113632. */
  113633. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  113634. va_list ap;
  113635. int rc;
  113636. va_start(ap, op);
  113637. switch( op ){
  113638. case SQLITE_DBCONFIG_LOOKASIDE: {
  113639. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  113640. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  113641. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  113642. rc = setupLookaside(db, pBuf, sz, cnt);
  113643. break;
  113644. }
  113645. default: {
  113646. static const struct {
  113647. int op; /* The opcode */
  113648. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  113649. } aFlagOp[] = {
  113650. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  113651. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  113652. };
  113653. unsigned int i;
  113654. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  113655. for(i=0; i<ArraySize(aFlagOp); i++){
  113656. if( aFlagOp[i].op==op ){
  113657. int onoff = va_arg(ap, int);
  113658. int *pRes = va_arg(ap, int*);
  113659. int oldFlags = db->flags;
  113660. if( onoff>0 ){
  113661. db->flags |= aFlagOp[i].mask;
  113662. }else if( onoff==0 ){
  113663. db->flags &= ~aFlagOp[i].mask;
  113664. }
  113665. if( oldFlags!=db->flags ){
  113666. sqlite3ExpirePreparedStatements(db);
  113667. }
  113668. if( pRes ){
  113669. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  113670. }
  113671. rc = SQLITE_OK;
  113672. break;
  113673. }
  113674. }
  113675. break;
  113676. }
  113677. }
  113678. va_end(ap);
  113679. return rc;
  113680. }
  113681. /*
  113682. ** Return true if the buffer z[0..n-1] contains all spaces.
  113683. */
  113684. static int allSpaces(const char *z, int n){
  113685. while( n>0 && z[n-1]==' ' ){ n--; }
  113686. return n==0;
  113687. }
  113688. /*
  113689. ** This is the default collating function named "BINARY" which is always
  113690. ** available.
  113691. **
  113692. ** If the padFlag argument is not NULL then space padding at the end
  113693. ** of strings is ignored. This implements the RTRIM collation.
  113694. */
  113695. static int binCollFunc(
  113696. void *padFlag,
  113697. int nKey1, const void *pKey1,
  113698. int nKey2, const void *pKey2
  113699. ){
  113700. int rc, n;
  113701. n = nKey1<nKey2 ? nKey1 : nKey2;
  113702. rc = memcmp(pKey1, pKey2, n);
  113703. if( rc==0 ){
  113704. if( padFlag
  113705. && allSpaces(((char*)pKey1)+n, nKey1-n)
  113706. && allSpaces(((char*)pKey2)+n, nKey2-n)
  113707. ){
  113708. /* Leave rc unchanged at 0 */
  113709. }else{
  113710. rc = nKey1 - nKey2;
  113711. }
  113712. }
  113713. return rc;
  113714. }
  113715. /*
  113716. ** Another built-in collating sequence: NOCASE.
  113717. **
  113718. ** This collating sequence is intended to be used for "case independent
  113719. ** comparison". SQLite's knowledge of upper and lower case equivalents
  113720. ** extends only to the 26 characters used in the English language.
  113721. **
  113722. ** At the moment there is only a UTF-8 implementation.
  113723. */
  113724. static int nocaseCollatingFunc(
  113725. void *NotUsed,
  113726. int nKey1, const void *pKey1,
  113727. int nKey2, const void *pKey2
  113728. ){
  113729. int r = sqlite3StrNICmp(
  113730. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  113731. UNUSED_PARAMETER(NotUsed);
  113732. if( 0==r ){
  113733. r = nKey1-nKey2;
  113734. }
  113735. return r;
  113736. }
  113737. /*
  113738. ** Return the ROWID of the most recent insert
  113739. */
  113740. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  113741. return db->lastRowid;
  113742. }
  113743. /*
  113744. ** Return the number of changes in the most recent call to sqlite3_exec().
  113745. */
  113746. SQLITE_API int sqlite3_changes(sqlite3 *db){
  113747. return db->nChange;
  113748. }
  113749. /*
  113750. ** Return the number of changes since the database handle was opened.
  113751. */
  113752. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  113753. return db->nTotalChange;
  113754. }
  113755. /*
  113756. ** Close all open savepoints. This function only manipulates fields of the
  113757. ** database handle object, it does not close any savepoints that may be open
  113758. ** at the b-tree/pager level.
  113759. */
  113760. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  113761. while( db->pSavepoint ){
  113762. Savepoint *pTmp = db->pSavepoint;
  113763. db->pSavepoint = pTmp->pNext;
  113764. sqlite3DbFree(db, pTmp);
  113765. }
  113766. db->nSavepoint = 0;
  113767. db->nStatement = 0;
  113768. db->isTransactionSavepoint = 0;
  113769. }
  113770. /*
  113771. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  113772. ** if this is not the last copy of the function, do not invoke it. Multiple
  113773. ** copies of a single function are created when create_function() is called
  113774. ** with SQLITE_ANY as the encoding.
  113775. */
  113776. static void functionDestroy(sqlite3 *db, FuncDef *p){
  113777. FuncDestructor *pDestructor = p->pDestructor;
  113778. if( pDestructor ){
  113779. pDestructor->nRef--;
  113780. if( pDestructor->nRef==0 ){
  113781. pDestructor->xDestroy(pDestructor->pUserData);
  113782. sqlite3DbFree(db, pDestructor);
  113783. }
  113784. }
  113785. }
  113786. /*
  113787. ** Disconnect all sqlite3_vtab objects that belong to database connection
  113788. ** db. This is called when db is being closed.
  113789. */
  113790. static void disconnectAllVtab(sqlite3 *db){
  113791. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113792. int i;
  113793. sqlite3BtreeEnterAll(db);
  113794. for(i=0; i<db->nDb; i++){
  113795. Schema *pSchema = db->aDb[i].pSchema;
  113796. if( db->aDb[i].pSchema ){
  113797. HashElem *p;
  113798. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  113799. Table *pTab = (Table *)sqliteHashData(p);
  113800. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  113801. }
  113802. }
  113803. }
  113804. sqlite3BtreeLeaveAll(db);
  113805. #else
  113806. UNUSED_PARAMETER(db);
  113807. #endif
  113808. }
  113809. /*
  113810. ** Return TRUE if database connection db has unfinalized prepared
  113811. ** statements or unfinished sqlite3_backup objects.
  113812. */
  113813. static int connectionIsBusy(sqlite3 *db){
  113814. int j;
  113815. assert( sqlite3_mutex_held(db->mutex) );
  113816. if( db->pVdbe ) return 1;
  113817. for(j=0; j<db->nDb; j++){
  113818. Btree *pBt = db->aDb[j].pBt;
  113819. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  113820. }
  113821. return 0;
  113822. }
  113823. /*
  113824. ** Close an existing SQLite database
  113825. */
  113826. static int sqlite3Close(sqlite3 *db, int forceZombie){
  113827. if( !db ){
  113828. return SQLITE_OK;
  113829. }
  113830. if( !sqlite3SafetyCheckSickOrOk(db) ){
  113831. return SQLITE_MISUSE_BKPT;
  113832. }
  113833. sqlite3_mutex_enter(db->mutex);
  113834. /* Force xDisconnect calls on all virtual tables */
  113835. disconnectAllVtab(db);
  113836. /* If a transaction is open, the disconnectAllVtab() call above
  113837. ** will not have called the xDisconnect() method on any virtual
  113838. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  113839. ** call will do so. We need to do this before the check for active
  113840. ** SQL statements below, as the v-table implementation may be storing
  113841. ** some prepared statements internally.
  113842. */
  113843. sqlite3VtabRollback(db);
  113844. /* Legacy behavior (sqlite3_close() behavior) is to return
  113845. ** SQLITE_BUSY if the connection can not be closed immediately.
  113846. */
  113847. if( !forceZombie && connectionIsBusy(db) ){
  113848. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  113849. "statements or unfinished backups");
  113850. sqlite3_mutex_leave(db->mutex);
  113851. return SQLITE_BUSY;
  113852. }
  113853. #ifdef SQLITE_ENABLE_SQLLOG
  113854. if( sqlite3GlobalConfig.xSqllog ){
  113855. /* Closing the handle. Fourth parameter is passed the value 2. */
  113856. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  113857. }
  113858. #endif
  113859. /* Convert the connection into a zombie and then close it.
  113860. */
  113861. db->magic = SQLITE_MAGIC_ZOMBIE;
  113862. sqlite3LeaveMutexAndCloseZombie(db);
  113863. return SQLITE_OK;
  113864. }
  113865. /*
  113866. ** Two variations on the public interface for closing a database
  113867. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  113868. ** leaves the connection option if there are unfinalized prepared
  113869. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  113870. ** version forces the connection to become a zombie if there are
  113871. ** unclosed resources, and arranges for deallocation when the last
  113872. ** prepare statement or sqlite3_backup closes.
  113873. */
  113874. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  113875. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  113876. /*
  113877. ** Close the mutex on database connection db.
  113878. **
  113879. ** Furthermore, if database connection db is a zombie (meaning that there
  113880. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  113881. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  113882. ** finished, then free all resources.
  113883. */
  113884. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  113885. HashElem *i; /* Hash table iterator */
  113886. int j;
  113887. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  113888. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  113889. ** then just leave the mutex and return.
  113890. */
  113891. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  113892. sqlite3_mutex_leave(db->mutex);
  113893. return;
  113894. }
  113895. /* If we reach this point, it means that the database connection has
  113896. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  113897. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  113898. ** go ahead and free all resources.
  113899. */
  113900. /* If a transaction is open, roll it back. This also ensures that if
  113901. ** any database schemas have been modified by an uncommitted transaction
  113902. ** they are reset. And that the required b-tree mutex is held to make
  113903. ** the pager rollback and schema reset an atomic operation. */
  113904. sqlite3RollbackAll(db, SQLITE_OK);
  113905. /* Free any outstanding Savepoint structures. */
  113906. sqlite3CloseSavepoints(db);
  113907. /* Close all database connections */
  113908. for(j=0; j<db->nDb; j++){
  113909. struct Db *pDb = &db->aDb[j];
  113910. if( pDb->pBt ){
  113911. sqlite3BtreeClose(pDb->pBt);
  113912. pDb->pBt = 0;
  113913. if( j!=1 ){
  113914. pDb->pSchema = 0;
  113915. }
  113916. }
  113917. }
  113918. /* Clear the TEMP schema separately and last */
  113919. if( db->aDb[1].pSchema ){
  113920. sqlite3SchemaClear(db->aDb[1].pSchema);
  113921. }
  113922. sqlite3VtabUnlockList(db);
  113923. /* Free up the array of auxiliary databases */
  113924. sqlite3CollapseDatabaseArray(db);
  113925. assert( db->nDb<=2 );
  113926. assert( db->aDb==db->aDbStatic );
  113927. /* Tell the code in notify.c that the connection no longer holds any
  113928. ** locks and does not require any further unlock-notify callbacks.
  113929. */
  113930. sqlite3ConnectionClosed(db);
  113931. for(j=0; j<ArraySize(db->aFunc.a); j++){
  113932. FuncDef *pNext, *pHash, *p;
  113933. for(p=db->aFunc.a[j]; p; p=pHash){
  113934. pHash = p->pHash;
  113935. while( p ){
  113936. functionDestroy(db, p);
  113937. pNext = p->pNext;
  113938. sqlite3DbFree(db, p);
  113939. p = pNext;
  113940. }
  113941. }
  113942. }
  113943. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  113944. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  113945. /* Invoke any destructors registered for collation sequence user data. */
  113946. for(j=0; j<3; j++){
  113947. if( pColl[j].xDel ){
  113948. pColl[j].xDel(pColl[j].pUser);
  113949. }
  113950. }
  113951. sqlite3DbFree(db, pColl);
  113952. }
  113953. sqlite3HashClear(&db->aCollSeq);
  113954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113955. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  113956. Module *pMod = (Module *)sqliteHashData(i);
  113957. if( pMod->xDestroy ){
  113958. pMod->xDestroy(pMod->pAux);
  113959. }
  113960. sqlite3DbFree(db, pMod);
  113961. }
  113962. sqlite3HashClear(&db->aModule);
  113963. #endif
  113964. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  113965. if( db->pErr ){
  113966. sqlite3ValueFree(db->pErr);
  113967. }
  113968. sqlite3CloseExtensions(db);
  113969. db->magic = SQLITE_MAGIC_ERROR;
  113970. /* The temp-database schema is allocated differently from the other schema
  113971. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  113972. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  113973. ** the same sqliteMalloc() as the one that allocates the database
  113974. ** structure?
  113975. */
  113976. sqlite3DbFree(db, db->aDb[1].pSchema);
  113977. sqlite3_mutex_leave(db->mutex);
  113978. db->magic = SQLITE_MAGIC_CLOSED;
  113979. sqlite3_mutex_free(db->mutex);
  113980. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  113981. if( db->lookaside.bMalloced ){
  113982. sqlite3_free(db->lookaside.pStart);
  113983. }
  113984. sqlite3_free(db);
  113985. }
  113986. /*
  113987. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  113988. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  113989. ** breaker") and made to return tripCode if there are any further
  113990. ** attempts to use that cursor.
  113991. */
  113992. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  113993. int i;
  113994. int inTrans = 0;
  113995. assert( sqlite3_mutex_held(db->mutex) );
  113996. sqlite3BeginBenignMalloc();
  113997. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  113998. ** This is important in case the transaction being rolled back has
  113999. ** modified the database schema. If the b-tree mutexes are not taken
  114000. ** here, then another shared-cache connection might sneak in between
  114001. ** the database rollback and schema reset, which can cause false
  114002. ** corruption reports in some cases. */
  114003. sqlite3BtreeEnterAll(db);
  114004. for(i=0; i<db->nDb; i++){
  114005. Btree *p = db->aDb[i].pBt;
  114006. if( p ){
  114007. if( sqlite3BtreeIsInTrans(p) ){
  114008. inTrans = 1;
  114009. }
  114010. sqlite3BtreeRollback(p, tripCode);
  114011. }
  114012. }
  114013. sqlite3VtabRollback(db);
  114014. sqlite3EndBenignMalloc();
  114015. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  114016. sqlite3ExpirePreparedStatements(db);
  114017. sqlite3ResetAllSchemasOfConnection(db);
  114018. }
  114019. sqlite3BtreeLeaveAll(db);
  114020. /* Any deferred constraint violations have now been resolved. */
  114021. db->nDeferredCons = 0;
  114022. db->nDeferredImmCons = 0;
  114023. db->flags &= ~SQLITE_DeferFKs;
  114024. /* If one has been configured, invoke the rollback-hook callback */
  114025. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  114026. db->xRollbackCallback(db->pRollbackArg);
  114027. }
  114028. }
  114029. /*
  114030. ** Return a static string containing the name corresponding to the error code
  114031. ** specified in the argument.
  114032. */
  114033. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  114034. defined(SQLITE_DEBUG_OS_TRACE)
  114035. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  114036. const char *zName = 0;
  114037. int i, origRc = rc;
  114038. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  114039. switch( rc ){
  114040. case SQLITE_OK: zName = "SQLITE_OK"; break;
  114041. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  114042. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  114043. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  114044. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  114045. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  114046. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  114047. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  114048. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  114049. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  114050. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  114051. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  114052. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  114053. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  114054. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  114055. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  114056. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  114057. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  114058. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  114059. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  114060. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  114061. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  114062. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  114063. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  114064. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  114065. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  114066. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  114067. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  114068. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  114069. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  114070. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  114071. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  114072. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  114073. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  114074. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  114075. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  114076. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  114077. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  114078. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  114079. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  114080. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  114081. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  114082. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  114083. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  114084. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  114085. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  114086. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  114087. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  114088. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  114089. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  114090. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  114091. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  114092. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  114093. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  114094. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  114095. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  114096. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  114097. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  114098. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  114099. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  114100. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  114101. case SQLITE_CONSTRAINT_FOREIGNKEY:
  114102. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  114103. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  114104. case SQLITE_CONSTRAINT_PRIMARYKEY:
  114105. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  114106. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  114107. case SQLITE_CONSTRAINT_COMMITHOOK:
  114108. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  114109. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  114110. case SQLITE_CONSTRAINT_FUNCTION:
  114111. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  114112. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  114113. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  114114. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  114115. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  114116. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  114117. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  114118. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  114119. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  114120. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  114121. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  114122. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  114123. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  114124. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  114125. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  114126. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  114127. }
  114128. }
  114129. if( zName==0 ){
  114130. static char zBuf[50];
  114131. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  114132. zName = zBuf;
  114133. }
  114134. return zName;
  114135. }
  114136. #endif
  114137. /*
  114138. ** Return a static string that describes the kind of error specified in the
  114139. ** argument.
  114140. */
  114141. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  114142. static const char* const aMsg[] = {
  114143. /* SQLITE_OK */ "not an error",
  114144. /* SQLITE_ERROR */ "SQL logic error or missing database",
  114145. /* SQLITE_INTERNAL */ 0,
  114146. /* SQLITE_PERM */ "access permission denied",
  114147. /* SQLITE_ABORT */ "callback requested query abort",
  114148. /* SQLITE_BUSY */ "database is locked",
  114149. /* SQLITE_LOCKED */ "database table is locked",
  114150. /* SQLITE_NOMEM */ "out of memory",
  114151. /* SQLITE_READONLY */ "attempt to write a readonly database",
  114152. /* SQLITE_INTERRUPT */ "interrupted",
  114153. /* SQLITE_IOERR */ "disk I/O error",
  114154. /* SQLITE_CORRUPT */ "database disk image is malformed",
  114155. /* SQLITE_NOTFOUND */ "unknown operation",
  114156. /* SQLITE_FULL */ "database or disk is full",
  114157. /* SQLITE_CANTOPEN */ "unable to open database file",
  114158. /* SQLITE_PROTOCOL */ "locking protocol",
  114159. /* SQLITE_EMPTY */ "table contains no data",
  114160. /* SQLITE_SCHEMA */ "database schema has changed",
  114161. /* SQLITE_TOOBIG */ "string or blob too big",
  114162. /* SQLITE_CONSTRAINT */ "constraint failed",
  114163. /* SQLITE_MISMATCH */ "datatype mismatch",
  114164. /* SQLITE_MISUSE */ "library routine called out of sequence",
  114165. /* SQLITE_NOLFS */ "large file support is disabled",
  114166. /* SQLITE_AUTH */ "authorization denied",
  114167. /* SQLITE_FORMAT */ "auxiliary database format error",
  114168. /* SQLITE_RANGE */ "bind or column index out of range",
  114169. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  114170. };
  114171. const char *zErr = "unknown error";
  114172. switch( rc ){
  114173. case SQLITE_ABORT_ROLLBACK: {
  114174. zErr = "abort due to ROLLBACK";
  114175. break;
  114176. }
  114177. default: {
  114178. rc &= 0xff;
  114179. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  114180. zErr = aMsg[rc];
  114181. }
  114182. break;
  114183. }
  114184. }
  114185. return zErr;
  114186. }
  114187. /*
  114188. ** This routine implements a busy callback that sleeps and tries
  114189. ** again until a timeout value is reached. The timeout value is
  114190. ** an integer number of milliseconds passed in as the first
  114191. ** argument.
  114192. */
  114193. static int sqliteDefaultBusyCallback(
  114194. void *ptr, /* Database connection */
  114195. int count /* Number of times table has been busy */
  114196. ){
  114197. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  114198. static const u8 delays[] =
  114199. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  114200. static const u8 totals[] =
  114201. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  114202. # define NDELAY ArraySize(delays)
  114203. sqlite3 *db = (sqlite3 *)ptr;
  114204. int timeout = db->busyTimeout;
  114205. int delay, prior;
  114206. assert( count>=0 );
  114207. if( count < NDELAY ){
  114208. delay = delays[count];
  114209. prior = totals[count];
  114210. }else{
  114211. delay = delays[NDELAY-1];
  114212. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  114213. }
  114214. if( prior + delay > timeout ){
  114215. delay = timeout - prior;
  114216. if( delay<=0 ) return 0;
  114217. }
  114218. sqlite3OsSleep(db->pVfs, delay*1000);
  114219. return 1;
  114220. #else
  114221. sqlite3 *db = (sqlite3 *)ptr;
  114222. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  114223. if( (count+1)*1000 > timeout ){
  114224. return 0;
  114225. }
  114226. sqlite3OsSleep(db->pVfs, 1000000);
  114227. return 1;
  114228. #endif
  114229. }
  114230. /*
  114231. ** Invoke the given busy handler.
  114232. **
  114233. ** This routine is called when an operation failed with a lock.
  114234. ** If this routine returns non-zero, the lock is retried. If it
  114235. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  114236. */
  114237. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  114238. int rc;
  114239. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  114240. rc = p->xFunc(p->pArg, p->nBusy);
  114241. if( rc==0 ){
  114242. p->nBusy = -1;
  114243. }else{
  114244. p->nBusy++;
  114245. }
  114246. return rc;
  114247. }
  114248. /*
  114249. ** This routine sets the busy callback for an Sqlite database to the
  114250. ** given callback function with the given argument.
  114251. */
  114252. SQLITE_API int sqlite3_busy_handler(
  114253. sqlite3 *db,
  114254. int (*xBusy)(void*,int),
  114255. void *pArg
  114256. ){
  114257. sqlite3_mutex_enter(db->mutex);
  114258. db->busyHandler.xFunc = xBusy;
  114259. db->busyHandler.pArg = pArg;
  114260. db->busyHandler.nBusy = 0;
  114261. db->busyTimeout = 0;
  114262. sqlite3_mutex_leave(db->mutex);
  114263. return SQLITE_OK;
  114264. }
  114265. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  114266. /*
  114267. ** This routine sets the progress callback for an Sqlite database to the
  114268. ** given callback function with the given argument. The progress callback will
  114269. ** be invoked every nOps opcodes.
  114270. */
  114271. SQLITE_API void sqlite3_progress_handler(
  114272. sqlite3 *db,
  114273. int nOps,
  114274. int (*xProgress)(void*),
  114275. void *pArg
  114276. ){
  114277. sqlite3_mutex_enter(db->mutex);
  114278. if( nOps>0 ){
  114279. db->xProgress = xProgress;
  114280. db->nProgressOps = (unsigned)nOps;
  114281. db->pProgressArg = pArg;
  114282. }else{
  114283. db->xProgress = 0;
  114284. db->nProgressOps = 0;
  114285. db->pProgressArg = 0;
  114286. }
  114287. sqlite3_mutex_leave(db->mutex);
  114288. }
  114289. #endif
  114290. /*
  114291. ** This routine installs a default busy handler that waits for the
  114292. ** specified number of milliseconds before returning 0.
  114293. */
  114294. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  114295. if( ms>0 ){
  114296. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  114297. db->busyTimeout = ms;
  114298. }else{
  114299. sqlite3_busy_handler(db, 0, 0);
  114300. }
  114301. return SQLITE_OK;
  114302. }
  114303. /*
  114304. ** Cause any pending operation to stop at its earliest opportunity.
  114305. */
  114306. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  114307. db->u1.isInterrupted = 1;
  114308. }
  114309. /*
  114310. ** This function is exactly the same as sqlite3_create_function(), except
  114311. ** that it is designed to be called by internal code. The difference is
  114312. ** that if a malloc() fails in sqlite3_create_function(), an error code
  114313. ** is returned and the mallocFailed flag cleared.
  114314. */
  114315. SQLITE_PRIVATE int sqlite3CreateFunc(
  114316. sqlite3 *db,
  114317. const char *zFunctionName,
  114318. int nArg,
  114319. int enc,
  114320. void *pUserData,
  114321. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114322. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114323. void (*xFinal)(sqlite3_context*),
  114324. FuncDestructor *pDestructor
  114325. ){
  114326. FuncDef *p;
  114327. int nName;
  114328. assert( sqlite3_mutex_held(db->mutex) );
  114329. if( zFunctionName==0 ||
  114330. (xFunc && (xFinal || xStep)) ||
  114331. (!xFunc && (xFinal && !xStep)) ||
  114332. (!xFunc && (!xFinal && xStep)) ||
  114333. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  114334. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  114335. return SQLITE_MISUSE_BKPT;
  114336. }
  114337. #ifndef SQLITE_OMIT_UTF16
  114338. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  114339. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  114340. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  114341. **
  114342. ** If SQLITE_ANY is specified, add three versions of the function
  114343. ** to the hash table.
  114344. */
  114345. if( enc==SQLITE_UTF16 ){
  114346. enc = SQLITE_UTF16NATIVE;
  114347. }else if( enc==SQLITE_ANY ){
  114348. int rc;
  114349. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  114350. pUserData, xFunc, xStep, xFinal, pDestructor);
  114351. if( rc==SQLITE_OK ){
  114352. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  114353. pUserData, xFunc, xStep, xFinal, pDestructor);
  114354. }
  114355. if( rc!=SQLITE_OK ){
  114356. return rc;
  114357. }
  114358. enc = SQLITE_UTF16BE;
  114359. }
  114360. #else
  114361. enc = SQLITE_UTF8;
  114362. #endif
  114363. /* Check if an existing function is being overridden or deleted. If so,
  114364. ** and there are active VMs, then return SQLITE_BUSY. If a function
  114365. ** is being overridden/deleted but there are no active VMs, allow the
  114366. ** operation to continue but invalidate all precompiled statements.
  114367. */
  114368. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  114369. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  114370. if( db->nVdbeActive ){
  114371. sqlite3Error(db, SQLITE_BUSY,
  114372. "unable to delete/modify user-function due to active statements");
  114373. assert( !db->mallocFailed );
  114374. return SQLITE_BUSY;
  114375. }else{
  114376. sqlite3ExpirePreparedStatements(db);
  114377. }
  114378. }
  114379. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  114380. assert(p || db->mallocFailed);
  114381. if( !p ){
  114382. return SQLITE_NOMEM;
  114383. }
  114384. /* If an older version of the function with a configured destructor is
  114385. ** being replaced invoke the destructor function here. */
  114386. functionDestroy(db, p);
  114387. if( pDestructor ){
  114388. pDestructor->nRef++;
  114389. }
  114390. p->pDestructor = pDestructor;
  114391. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  114392. p->xFunc = xFunc;
  114393. p->xStep = xStep;
  114394. p->xFinalize = xFinal;
  114395. p->pUserData = pUserData;
  114396. p->nArg = (u16)nArg;
  114397. return SQLITE_OK;
  114398. }
  114399. /*
  114400. ** Create new user functions.
  114401. */
  114402. SQLITE_API int sqlite3_create_function(
  114403. sqlite3 *db,
  114404. const char *zFunc,
  114405. int nArg,
  114406. int enc,
  114407. void *p,
  114408. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114409. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114410. void (*xFinal)(sqlite3_context*)
  114411. ){
  114412. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  114413. xFinal, 0);
  114414. }
  114415. SQLITE_API int sqlite3_create_function_v2(
  114416. sqlite3 *db,
  114417. const char *zFunc,
  114418. int nArg,
  114419. int enc,
  114420. void *p,
  114421. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114422. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114423. void (*xFinal)(sqlite3_context*),
  114424. void (*xDestroy)(void *)
  114425. ){
  114426. int rc = SQLITE_ERROR;
  114427. FuncDestructor *pArg = 0;
  114428. sqlite3_mutex_enter(db->mutex);
  114429. if( xDestroy ){
  114430. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  114431. if( !pArg ){
  114432. xDestroy(p);
  114433. goto out;
  114434. }
  114435. pArg->xDestroy = xDestroy;
  114436. pArg->pUserData = p;
  114437. }
  114438. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  114439. if( pArg && pArg->nRef==0 ){
  114440. assert( rc!=SQLITE_OK );
  114441. xDestroy(p);
  114442. sqlite3DbFree(db, pArg);
  114443. }
  114444. out:
  114445. rc = sqlite3ApiExit(db, rc);
  114446. sqlite3_mutex_leave(db->mutex);
  114447. return rc;
  114448. }
  114449. #ifndef SQLITE_OMIT_UTF16
  114450. SQLITE_API int sqlite3_create_function16(
  114451. sqlite3 *db,
  114452. const void *zFunctionName,
  114453. int nArg,
  114454. int eTextRep,
  114455. void *p,
  114456. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  114457. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  114458. void (*xFinal)(sqlite3_context*)
  114459. ){
  114460. int rc;
  114461. char *zFunc8;
  114462. sqlite3_mutex_enter(db->mutex);
  114463. assert( !db->mallocFailed );
  114464. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  114465. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  114466. sqlite3DbFree(db, zFunc8);
  114467. rc = sqlite3ApiExit(db, rc);
  114468. sqlite3_mutex_leave(db->mutex);
  114469. return rc;
  114470. }
  114471. #endif
  114472. /*
  114473. ** Declare that a function has been overloaded by a virtual table.
  114474. **
  114475. ** If the function already exists as a regular global function, then
  114476. ** this routine is a no-op. If the function does not exist, then create
  114477. ** a new one that always throws a run-time error.
  114478. **
  114479. ** When virtual tables intend to provide an overloaded function, they
  114480. ** should call this routine to make sure the global function exists.
  114481. ** A global function must exist in order for name resolution to work
  114482. ** properly.
  114483. */
  114484. SQLITE_API int sqlite3_overload_function(
  114485. sqlite3 *db,
  114486. const char *zName,
  114487. int nArg
  114488. ){
  114489. int nName = sqlite3Strlen30(zName);
  114490. int rc = SQLITE_OK;
  114491. sqlite3_mutex_enter(db->mutex);
  114492. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  114493. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  114494. 0, sqlite3InvalidFunction, 0, 0, 0);
  114495. }
  114496. rc = sqlite3ApiExit(db, rc);
  114497. sqlite3_mutex_leave(db->mutex);
  114498. return rc;
  114499. }
  114500. #ifndef SQLITE_OMIT_TRACE
  114501. /*
  114502. ** Register a trace function. The pArg from the previously registered trace
  114503. ** is returned.
  114504. **
  114505. ** A NULL trace function means that no tracing is executes. A non-NULL
  114506. ** trace is a pointer to a function that is invoked at the start of each
  114507. ** SQL statement.
  114508. */
  114509. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  114510. void *pOld;
  114511. sqlite3_mutex_enter(db->mutex);
  114512. pOld = db->pTraceArg;
  114513. db->xTrace = xTrace;
  114514. db->pTraceArg = pArg;
  114515. sqlite3_mutex_leave(db->mutex);
  114516. return pOld;
  114517. }
  114518. /*
  114519. ** Register a profile function. The pArg from the previously registered
  114520. ** profile function is returned.
  114521. **
  114522. ** A NULL profile function means that no profiling is executes. A non-NULL
  114523. ** profile is a pointer to a function that is invoked at the conclusion of
  114524. ** each SQL statement that is run.
  114525. */
  114526. SQLITE_API void *sqlite3_profile(
  114527. sqlite3 *db,
  114528. void (*xProfile)(void*,const char*,sqlite_uint64),
  114529. void *pArg
  114530. ){
  114531. void *pOld;
  114532. sqlite3_mutex_enter(db->mutex);
  114533. pOld = db->pProfileArg;
  114534. db->xProfile = xProfile;
  114535. db->pProfileArg = pArg;
  114536. sqlite3_mutex_leave(db->mutex);
  114537. return pOld;
  114538. }
  114539. #endif /* SQLITE_OMIT_TRACE */
  114540. /*
  114541. ** Register a function to be invoked when a transaction commits.
  114542. ** If the invoked function returns non-zero, then the commit becomes a
  114543. ** rollback.
  114544. */
  114545. SQLITE_API void *sqlite3_commit_hook(
  114546. sqlite3 *db, /* Attach the hook to this database */
  114547. int (*xCallback)(void*), /* Function to invoke on each commit */
  114548. void *pArg /* Argument to the function */
  114549. ){
  114550. void *pOld;
  114551. sqlite3_mutex_enter(db->mutex);
  114552. pOld = db->pCommitArg;
  114553. db->xCommitCallback = xCallback;
  114554. db->pCommitArg = pArg;
  114555. sqlite3_mutex_leave(db->mutex);
  114556. return pOld;
  114557. }
  114558. /*
  114559. ** Register a callback to be invoked each time a row is updated,
  114560. ** inserted or deleted using this database connection.
  114561. */
  114562. SQLITE_API void *sqlite3_update_hook(
  114563. sqlite3 *db, /* Attach the hook to this database */
  114564. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  114565. void *pArg /* Argument to the function */
  114566. ){
  114567. void *pRet;
  114568. sqlite3_mutex_enter(db->mutex);
  114569. pRet = db->pUpdateArg;
  114570. db->xUpdateCallback = xCallback;
  114571. db->pUpdateArg = pArg;
  114572. sqlite3_mutex_leave(db->mutex);
  114573. return pRet;
  114574. }
  114575. /*
  114576. ** Register a callback to be invoked each time a transaction is rolled
  114577. ** back by this database connection.
  114578. */
  114579. SQLITE_API void *sqlite3_rollback_hook(
  114580. sqlite3 *db, /* Attach the hook to this database */
  114581. void (*xCallback)(void*), /* Callback function */
  114582. void *pArg /* Argument to the function */
  114583. ){
  114584. void *pRet;
  114585. sqlite3_mutex_enter(db->mutex);
  114586. pRet = db->pRollbackArg;
  114587. db->xRollbackCallback = xCallback;
  114588. db->pRollbackArg = pArg;
  114589. sqlite3_mutex_leave(db->mutex);
  114590. return pRet;
  114591. }
  114592. #ifndef SQLITE_OMIT_WAL
  114593. /*
  114594. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  114595. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  114596. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  114597. ** wal_autocheckpoint()).
  114598. */
  114599. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  114600. void *pClientData, /* Argument */
  114601. sqlite3 *db, /* Connection */
  114602. const char *zDb, /* Database */
  114603. int nFrame /* Size of WAL */
  114604. ){
  114605. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  114606. sqlite3BeginBenignMalloc();
  114607. sqlite3_wal_checkpoint(db, zDb);
  114608. sqlite3EndBenignMalloc();
  114609. }
  114610. return SQLITE_OK;
  114611. }
  114612. #endif /* SQLITE_OMIT_WAL */
  114613. /*
  114614. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  114615. ** a database after committing a transaction if there are nFrame or
  114616. ** more frames in the log file. Passing zero or a negative value as the
  114617. ** nFrame parameter disables automatic checkpoints entirely.
  114618. **
  114619. ** The callback registered by this function replaces any existing callback
  114620. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  114621. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  114622. ** configured by this function.
  114623. */
  114624. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  114625. #ifdef SQLITE_OMIT_WAL
  114626. UNUSED_PARAMETER(db);
  114627. UNUSED_PARAMETER(nFrame);
  114628. #else
  114629. if( nFrame>0 ){
  114630. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  114631. }else{
  114632. sqlite3_wal_hook(db, 0, 0);
  114633. }
  114634. #endif
  114635. return SQLITE_OK;
  114636. }
  114637. /*
  114638. ** Register a callback to be invoked each time a transaction is written
  114639. ** into the write-ahead-log by this database connection.
  114640. */
  114641. SQLITE_API void *sqlite3_wal_hook(
  114642. sqlite3 *db, /* Attach the hook to this db handle */
  114643. int(*xCallback)(void *, sqlite3*, const char*, int),
  114644. void *pArg /* First argument passed to xCallback() */
  114645. ){
  114646. #ifndef SQLITE_OMIT_WAL
  114647. void *pRet;
  114648. sqlite3_mutex_enter(db->mutex);
  114649. pRet = db->pWalArg;
  114650. db->xWalCallback = xCallback;
  114651. db->pWalArg = pArg;
  114652. sqlite3_mutex_leave(db->mutex);
  114653. return pRet;
  114654. #else
  114655. return 0;
  114656. #endif
  114657. }
  114658. /*
  114659. ** Checkpoint database zDb.
  114660. */
  114661. SQLITE_API int sqlite3_wal_checkpoint_v2(
  114662. sqlite3 *db, /* Database handle */
  114663. const char *zDb, /* Name of attached database (or NULL) */
  114664. int eMode, /* SQLITE_CHECKPOINT_* value */
  114665. int *pnLog, /* OUT: Size of WAL log in frames */
  114666. int *pnCkpt /* OUT: Total number of frames checkpointed */
  114667. ){
  114668. #ifdef SQLITE_OMIT_WAL
  114669. return SQLITE_OK;
  114670. #else
  114671. int rc; /* Return code */
  114672. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  114673. /* Initialize the output variables to -1 in case an error occurs. */
  114674. if( pnLog ) *pnLog = -1;
  114675. if( pnCkpt ) *pnCkpt = -1;
  114676. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  114677. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  114678. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  114679. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  114680. return SQLITE_MISUSE;
  114681. }
  114682. sqlite3_mutex_enter(db->mutex);
  114683. if( zDb && zDb[0] ){
  114684. iDb = sqlite3FindDbName(db, zDb);
  114685. }
  114686. if( iDb<0 ){
  114687. rc = SQLITE_ERROR;
  114688. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  114689. }else{
  114690. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  114691. sqlite3Error(db, rc, 0);
  114692. }
  114693. rc = sqlite3ApiExit(db, rc);
  114694. sqlite3_mutex_leave(db->mutex);
  114695. return rc;
  114696. #endif
  114697. }
  114698. /*
  114699. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  114700. ** to contains a zero-length string, all attached databases are
  114701. ** checkpointed.
  114702. */
  114703. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  114704. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  114705. }
  114706. #ifndef SQLITE_OMIT_WAL
  114707. /*
  114708. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  114709. ** not currently open in WAL mode.
  114710. **
  114711. ** If a transaction is open on the database being checkpointed, this
  114712. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  114713. ** an error occurs while running the checkpoint, an SQLite error code is
  114714. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  114715. **
  114716. ** The mutex on database handle db should be held by the caller. The mutex
  114717. ** associated with the specific b-tree being checkpointed is taken by
  114718. ** this function while the checkpoint is running.
  114719. **
  114720. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  114721. ** checkpointed. If an error is encountered it is returned immediately -
  114722. ** no attempt is made to checkpoint any remaining databases.
  114723. **
  114724. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  114725. */
  114726. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  114727. int rc = SQLITE_OK; /* Return code */
  114728. int i; /* Used to iterate through attached dbs */
  114729. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  114730. assert( sqlite3_mutex_held(db->mutex) );
  114731. assert( !pnLog || *pnLog==-1 );
  114732. assert( !pnCkpt || *pnCkpt==-1 );
  114733. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  114734. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  114735. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  114736. pnLog = 0;
  114737. pnCkpt = 0;
  114738. if( rc==SQLITE_BUSY ){
  114739. bBusy = 1;
  114740. rc = SQLITE_OK;
  114741. }
  114742. }
  114743. }
  114744. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  114745. }
  114746. #endif /* SQLITE_OMIT_WAL */
  114747. /*
  114748. ** This function returns true if main-memory should be used instead of
  114749. ** a temporary file for transient pager files and statement journals.
  114750. ** The value returned depends on the value of db->temp_store (runtime
  114751. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  114752. ** following table describes the relationship between these two values
  114753. ** and this functions return value.
  114754. **
  114755. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  114756. ** ----------------- -------------- ------------------------------
  114757. ** 0 any file (return 0)
  114758. ** 1 1 file (return 0)
  114759. ** 1 2 memory (return 1)
  114760. ** 1 0 file (return 0)
  114761. ** 2 1 file (return 0)
  114762. ** 2 2 memory (return 1)
  114763. ** 2 0 memory (return 1)
  114764. ** 3 any memory (return 1)
  114765. */
  114766. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  114767. #if SQLITE_TEMP_STORE==1
  114768. return ( db->temp_store==2 );
  114769. #endif
  114770. #if SQLITE_TEMP_STORE==2
  114771. return ( db->temp_store!=1 );
  114772. #endif
  114773. #if SQLITE_TEMP_STORE==3
  114774. return 1;
  114775. #endif
  114776. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  114777. return 0;
  114778. #endif
  114779. }
  114780. /*
  114781. ** Return UTF-8 encoded English language explanation of the most recent
  114782. ** error.
  114783. */
  114784. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  114785. const char *z;
  114786. if( !db ){
  114787. return sqlite3ErrStr(SQLITE_NOMEM);
  114788. }
  114789. if( !sqlite3SafetyCheckSickOrOk(db) ){
  114790. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  114791. }
  114792. sqlite3_mutex_enter(db->mutex);
  114793. if( db->mallocFailed ){
  114794. z = sqlite3ErrStr(SQLITE_NOMEM);
  114795. }else{
  114796. z = (char*)sqlite3_value_text(db->pErr);
  114797. assert( !db->mallocFailed );
  114798. if( z==0 ){
  114799. z = sqlite3ErrStr(db->errCode);
  114800. }
  114801. }
  114802. sqlite3_mutex_leave(db->mutex);
  114803. return z;
  114804. }
  114805. #ifndef SQLITE_OMIT_UTF16
  114806. /*
  114807. ** Return UTF-16 encoded English language explanation of the most recent
  114808. ** error.
  114809. */
  114810. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  114811. static const u16 outOfMem[] = {
  114812. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  114813. };
  114814. static const u16 misuse[] = {
  114815. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  114816. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  114817. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  114818. 'o', 'u', 't', ' ',
  114819. 'o', 'f', ' ',
  114820. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  114821. };
  114822. const void *z;
  114823. if( !db ){
  114824. return (void *)outOfMem;
  114825. }
  114826. if( !sqlite3SafetyCheckSickOrOk(db) ){
  114827. return (void *)misuse;
  114828. }
  114829. sqlite3_mutex_enter(db->mutex);
  114830. if( db->mallocFailed ){
  114831. z = (void *)outOfMem;
  114832. }else{
  114833. z = sqlite3_value_text16(db->pErr);
  114834. if( z==0 ){
  114835. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  114836. SQLITE_UTF8, SQLITE_STATIC);
  114837. z = sqlite3_value_text16(db->pErr);
  114838. }
  114839. /* A malloc() may have failed within the call to sqlite3_value_text16()
  114840. ** above. If this is the case, then the db->mallocFailed flag needs to
  114841. ** be cleared before returning. Do this directly, instead of via
  114842. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  114843. */
  114844. db->mallocFailed = 0;
  114845. }
  114846. sqlite3_mutex_leave(db->mutex);
  114847. return z;
  114848. }
  114849. #endif /* SQLITE_OMIT_UTF16 */
  114850. /*
  114851. ** Return the most recent error code generated by an SQLite routine. If NULL is
  114852. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  114853. */
  114854. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  114855. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  114856. return SQLITE_MISUSE_BKPT;
  114857. }
  114858. if( !db || db->mallocFailed ){
  114859. return SQLITE_NOMEM;
  114860. }
  114861. return db->errCode & db->errMask;
  114862. }
  114863. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  114864. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  114865. return SQLITE_MISUSE_BKPT;
  114866. }
  114867. if( !db || db->mallocFailed ){
  114868. return SQLITE_NOMEM;
  114869. }
  114870. return db->errCode;
  114871. }
  114872. /*
  114873. ** Return a string that describes the kind of error specified in the
  114874. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  114875. ** function.
  114876. */
  114877. SQLITE_API const char *sqlite3_errstr(int rc){
  114878. return sqlite3ErrStr(rc);
  114879. }
  114880. /*
  114881. ** Create a new collating function for database "db". The name is zName
  114882. ** and the encoding is enc.
  114883. */
  114884. static int createCollation(
  114885. sqlite3* db,
  114886. const char *zName,
  114887. u8 enc,
  114888. void* pCtx,
  114889. int(*xCompare)(void*,int,const void*,int,const void*),
  114890. void(*xDel)(void*)
  114891. ){
  114892. CollSeq *pColl;
  114893. int enc2;
  114894. int nName = sqlite3Strlen30(zName);
  114895. assert( sqlite3_mutex_held(db->mutex) );
  114896. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  114897. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  114898. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  114899. */
  114900. enc2 = enc;
  114901. testcase( enc2==SQLITE_UTF16 );
  114902. testcase( enc2==SQLITE_UTF16_ALIGNED );
  114903. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  114904. enc2 = SQLITE_UTF16NATIVE;
  114905. }
  114906. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  114907. return SQLITE_MISUSE_BKPT;
  114908. }
  114909. /* Check if this call is removing or replacing an existing collation
  114910. ** sequence. If so, and there are active VMs, return busy. If there
  114911. ** are no active VMs, invalidate any pre-compiled statements.
  114912. */
  114913. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  114914. if( pColl && pColl->xCmp ){
  114915. if( db->nVdbeActive ){
  114916. sqlite3Error(db, SQLITE_BUSY,
  114917. "unable to delete/modify collation sequence due to active statements");
  114918. return SQLITE_BUSY;
  114919. }
  114920. sqlite3ExpirePreparedStatements(db);
  114921. /* If collation sequence pColl was created directly by a call to
  114922. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  114923. ** then any copies made by synthCollSeq() need to be invalidated.
  114924. ** Also, collation destructor - CollSeq.xDel() - function may need
  114925. ** to be called.
  114926. */
  114927. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  114928. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  114929. int j;
  114930. for(j=0; j<3; j++){
  114931. CollSeq *p = &aColl[j];
  114932. if( p->enc==pColl->enc ){
  114933. if( p->xDel ){
  114934. p->xDel(p->pUser);
  114935. }
  114936. p->xCmp = 0;
  114937. }
  114938. }
  114939. }
  114940. }
  114941. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  114942. if( pColl==0 ) return SQLITE_NOMEM;
  114943. pColl->xCmp = xCompare;
  114944. pColl->pUser = pCtx;
  114945. pColl->xDel = xDel;
  114946. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  114947. sqlite3Error(db, SQLITE_OK, 0);
  114948. return SQLITE_OK;
  114949. }
  114950. /*
  114951. ** This array defines hard upper bounds on limit values. The
  114952. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  114953. ** #defines in sqlite3.h.
  114954. */
  114955. static const int aHardLimit[] = {
  114956. SQLITE_MAX_LENGTH,
  114957. SQLITE_MAX_SQL_LENGTH,
  114958. SQLITE_MAX_COLUMN,
  114959. SQLITE_MAX_EXPR_DEPTH,
  114960. SQLITE_MAX_COMPOUND_SELECT,
  114961. SQLITE_MAX_VDBE_OP,
  114962. SQLITE_MAX_FUNCTION_ARG,
  114963. SQLITE_MAX_ATTACHED,
  114964. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  114965. SQLITE_MAX_VARIABLE_NUMBER,
  114966. SQLITE_MAX_TRIGGER_DEPTH,
  114967. };
  114968. /*
  114969. ** Make sure the hard limits are set to reasonable values
  114970. */
  114971. #if SQLITE_MAX_LENGTH<100
  114972. # error SQLITE_MAX_LENGTH must be at least 100
  114973. #endif
  114974. #if SQLITE_MAX_SQL_LENGTH<100
  114975. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  114976. #endif
  114977. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  114978. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  114979. #endif
  114980. #if SQLITE_MAX_COMPOUND_SELECT<2
  114981. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  114982. #endif
  114983. #if SQLITE_MAX_VDBE_OP<40
  114984. # error SQLITE_MAX_VDBE_OP must be at least 40
  114985. #endif
  114986. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  114987. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  114988. #endif
  114989. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  114990. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  114991. #endif
  114992. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  114993. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  114994. #endif
  114995. #if SQLITE_MAX_COLUMN>32767
  114996. # error SQLITE_MAX_COLUMN must not exceed 32767
  114997. #endif
  114998. #if SQLITE_MAX_TRIGGER_DEPTH<1
  114999. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  115000. #endif
  115001. /*
  115002. ** Change the value of a limit. Report the old value.
  115003. ** If an invalid limit index is supplied, report -1.
  115004. ** Make no changes but still report the old value if the
  115005. ** new limit is negative.
  115006. **
  115007. ** A new lower limit does not shrink existing constructs.
  115008. ** It merely prevents new constructs that exceed the limit
  115009. ** from forming.
  115010. */
  115011. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  115012. int oldLimit;
  115013. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  115014. ** there is a hard upper bound set at compile-time by a C preprocessor
  115015. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  115016. ** "_MAX_".)
  115017. */
  115018. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  115019. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  115020. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  115021. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  115022. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  115023. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  115024. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  115025. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  115026. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  115027. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  115028. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  115029. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  115030. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  115031. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  115032. return -1;
  115033. }
  115034. oldLimit = db->aLimit[limitId];
  115035. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  115036. if( newLimit>aHardLimit[limitId] ){
  115037. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  115038. }
  115039. db->aLimit[limitId] = newLimit;
  115040. }
  115041. return oldLimit; /* IMP: R-53341-35419 */
  115042. }
  115043. /*
  115044. ** This function is used to parse both URIs and non-URI filenames passed by the
  115045. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  115046. ** URIs specified as part of ATTACH statements.
  115047. **
  115048. ** The first argument to this function is the name of the VFS to use (or
  115049. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  115050. ** query parameter. The second argument contains the URI (or non-URI filename)
  115051. ** itself. When this function is called the *pFlags variable should contain
  115052. ** the default flags to open the database handle with. The value stored in
  115053. ** *pFlags may be updated before returning if the URI filename contains
  115054. ** "cache=xxx" or "mode=xxx" query parameters.
  115055. **
  115056. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  115057. ** the VFS that should be used to open the database file. *pzFile is set to
  115058. ** point to a buffer containing the name of the file to open. It is the
  115059. ** responsibility of the caller to eventually call sqlite3_free() to release
  115060. ** this buffer.
  115061. **
  115062. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  115063. ** may be set to point to a buffer containing an English language error
  115064. ** message. It is the responsibility of the caller to eventually release
  115065. ** this buffer by calling sqlite3_free().
  115066. */
  115067. SQLITE_PRIVATE int sqlite3ParseUri(
  115068. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  115069. const char *zUri, /* Nul-terminated URI to parse */
  115070. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  115071. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  115072. char **pzFile, /* OUT: Filename component of URI */
  115073. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  115074. ){
  115075. int rc = SQLITE_OK;
  115076. unsigned int flags = *pFlags;
  115077. const char *zVfs = zDefaultVfs;
  115078. char *zFile;
  115079. char c;
  115080. int nUri = sqlite3Strlen30(zUri);
  115081. assert( *pzErrMsg==0 );
  115082. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  115083. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  115084. ){
  115085. char *zOpt;
  115086. int eState; /* Parser state when parsing URI */
  115087. int iIn; /* Input character index */
  115088. int iOut = 0; /* Output character index */
  115089. int nByte = nUri+2; /* Bytes of space to allocate */
  115090. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  115091. ** method that there may be extra parameters following the file-name. */
  115092. flags |= SQLITE_OPEN_URI;
  115093. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  115094. zFile = sqlite3_malloc(nByte);
  115095. if( !zFile ) return SQLITE_NOMEM;
  115096. iIn = 5;
  115097. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  115098. /* Discard the scheme and authority segments of the URI. */
  115099. if( zUri[5]=='/' && zUri[6]=='/' ){
  115100. iIn = 7;
  115101. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  115102. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  115103. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  115104. iIn-7, &zUri[7]);
  115105. rc = SQLITE_ERROR;
  115106. goto parse_uri_out;
  115107. }
  115108. }
  115109. #endif
  115110. /* Copy the filename and any query parameters into the zFile buffer.
  115111. ** Decode %HH escape codes along the way.
  115112. **
  115113. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  115114. ** on the parsing context. As follows:
  115115. **
  115116. ** 0: Parsing file-name.
  115117. ** 1: Parsing name section of a name=value query parameter.
  115118. ** 2: Parsing value section of a name=value query parameter.
  115119. */
  115120. eState = 0;
  115121. while( (c = zUri[iIn])!=0 && c!='#' ){
  115122. iIn++;
  115123. if( c=='%'
  115124. && sqlite3Isxdigit(zUri[iIn])
  115125. && sqlite3Isxdigit(zUri[iIn+1])
  115126. ){
  115127. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  115128. octet += sqlite3HexToInt(zUri[iIn++]);
  115129. assert( octet>=0 && octet<256 );
  115130. if( octet==0 ){
  115131. /* This branch is taken when "%00" appears within the URI. In this
  115132. ** case we ignore all text in the remainder of the path, name or
  115133. ** value currently being parsed. So ignore the current character
  115134. ** and skip to the next "?", "=" or "&", as appropriate. */
  115135. while( (c = zUri[iIn])!=0 && c!='#'
  115136. && (eState!=0 || c!='?')
  115137. && (eState!=1 || (c!='=' && c!='&'))
  115138. && (eState!=2 || c!='&')
  115139. ){
  115140. iIn++;
  115141. }
  115142. continue;
  115143. }
  115144. c = octet;
  115145. }else if( eState==1 && (c=='&' || c=='=') ){
  115146. if( zFile[iOut-1]==0 ){
  115147. /* An empty option name. Ignore this option altogether. */
  115148. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  115149. continue;
  115150. }
  115151. if( c=='&' ){
  115152. zFile[iOut++] = '\0';
  115153. }else{
  115154. eState = 2;
  115155. }
  115156. c = 0;
  115157. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  115158. c = 0;
  115159. eState = 1;
  115160. }
  115161. zFile[iOut++] = c;
  115162. }
  115163. if( eState==1 ) zFile[iOut++] = '\0';
  115164. zFile[iOut++] = '\0';
  115165. zFile[iOut++] = '\0';
  115166. /* Check if there were any options specified that should be interpreted
  115167. ** here. Options that are interpreted here include "vfs" and those that
  115168. ** correspond to flags that may be passed to the sqlite3_open_v2()
  115169. ** method. */
  115170. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  115171. while( zOpt[0] ){
  115172. int nOpt = sqlite3Strlen30(zOpt);
  115173. char *zVal = &zOpt[nOpt+1];
  115174. int nVal = sqlite3Strlen30(zVal);
  115175. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  115176. zVfs = zVal;
  115177. }else{
  115178. struct OpenMode {
  115179. const char *z;
  115180. int mode;
  115181. } *aMode = 0;
  115182. char *zModeType = 0;
  115183. int mask = 0;
  115184. int limit = 0;
  115185. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  115186. static struct OpenMode aCacheMode[] = {
  115187. { "shared", SQLITE_OPEN_SHAREDCACHE },
  115188. { "private", SQLITE_OPEN_PRIVATECACHE },
  115189. { 0, 0 }
  115190. };
  115191. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  115192. aMode = aCacheMode;
  115193. limit = mask;
  115194. zModeType = "cache";
  115195. }
  115196. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  115197. static struct OpenMode aOpenMode[] = {
  115198. { "ro", SQLITE_OPEN_READONLY },
  115199. { "rw", SQLITE_OPEN_READWRITE },
  115200. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  115201. { "memory", SQLITE_OPEN_MEMORY },
  115202. { 0, 0 }
  115203. };
  115204. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  115205. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  115206. aMode = aOpenMode;
  115207. limit = mask & flags;
  115208. zModeType = "access";
  115209. }
  115210. if( aMode ){
  115211. int i;
  115212. int mode = 0;
  115213. for(i=0; aMode[i].z; i++){
  115214. const char *z = aMode[i].z;
  115215. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  115216. mode = aMode[i].mode;
  115217. break;
  115218. }
  115219. }
  115220. if( mode==0 ){
  115221. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  115222. rc = SQLITE_ERROR;
  115223. goto parse_uri_out;
  115224. }
  115225. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  115226. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  115227. zModeType, zVal);
  115228. rc = SQLITE_PERM;
  115229. goto parse_uri_out;
  115230. }
  115231. flags = (flags & ~mask) | mode;
  115232. }
  115233. }
  115234. zOpt = &zVal[nVal+1];
  115235. }
  115236. }else{
  115237. zFile = sqlite3_malloc(nUri+2);
  115238. if( !zFile ) return SQLITE_NOMEM;
  115239. memcpy(zFile, zUri, nUri);
  115240. zFile[nUri] = '\0';
  115241. zFile[nUri+1] = '\0';
  115242. flags &= ~SQLITE_OPEN_URI;
  115243. }
  115244. *ppVfs = sqlite3_vfs_find(zVfs);
  115245. if( *ppVfs==0 ){
  115246. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  115247. rc = SQLITE_ERROR;
  115248. }
  115249. parse_uri_out:
  115250. if( rc!=SQLITE_OK ){
  115251. sqlite3_free(zFile);
  115252. zFile = 0;
  115253. }
  115254. *pFlags = flags;
  115255. *pzFile = zFile;
  115256. return rc;
  115257. }
  115258. /*
  115259. ** This routine does the work of opening a database on behalf of
  115260. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  115261. ** is UTF-8 encoded.
  115262. */
  115263. static int openDatabase(
  115264. const char *zFilename, /* Database filename UTF-8 encoded */
  115265. sqlite3 **ppDb, /* OUT: Returned database handle */
  115266. unsigned int flags, /* Operational flags */
  115267. const char *zVfs /* Name of the VFS to use */
  115268. ){
  115269. sqlite3 *db; /* Store allocated handle here */
  115270. int rc; /* Return code */
  115271. int isThreadsafe; /* True for threadsafe connections */
  115272. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  115273. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  115274. *ppDb = 0;
  115275. #ifndef SQLITE_OMIT_AUTOINIT
  115276. rc = sqlite3_initialize();
  115277. if( rc ) return rc;
  115278. #endif
  115279. /* Only allow sensible combinations of bits in the flags argument.
  115280. ** Throw an error if any non-sense combination is used. If we
  115281. ** do not block illegal combinations here, it could trigger
  115282. ** assert() statements in deeper layers. Sensible combinations
  115283. ** are:
  115284. **
  115285. ** 1: SQLITE_OPEN_READONLY
  115286. ** 2: SQLITE_OPEN_READWRITE
  115287. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  115288. */
  115289. assert( SQLITE_OPEN_READONLY == 0x01 );
  115290. assert( SQLITE_OPEN_READWRITE == 0x02 );
  115291. assert( SQLITE_OPEN_CREATE == 0x04 );
  115292. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  115293. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  115294. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  115295. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  115296. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  115297. isThreadsafe = 0;
  115298. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  115299. isThreadsafe = 0;
  115300. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  115301. isThreadsafe = 1;
  115302. }else{
  115303. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  115304. }
  115305. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  115306. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  115307. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  115308. flags |= SQLITE_OPEN_SHAREDCACHE;
  115309. }
  115310. /* Remove harmful bits from the flags parameter
  115311. **
  115312. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  115313. ** dealt with in the previous code block. Besides these, the only
  115314. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  115315. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  115316. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  115317. ** off all other flags.
  115318. */
  115319. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  115320. SQLITE_OPEN_EXCLUSIVE |
  115321. SQLITE_OPEN_MAIN_DB |
  115322. SQLITE_OPEN_TEMP_DB |
  115323. SQLITE_OPEN_TRANSIENT_DB |
  115324. SQLITE_OPEN_MAIN_JOURNAL |
  115325. SQLITE_OPEN_TEMP_JOURNAL |
  115326. SQLITE_OPEN_SUBJOURNAL |
  115327. SQLITE_OPEN_MASTER_JOURNAL |
  115328. SQLITE_OPEN_NOMUTEX |
  115329. SQLITE_OPEN_FULLMUTEX |
  115330. SQLITE_OPEN_WAL
  115331. );
  115332. /* Allocate the sqlite data structure */
  115333. db = sqlite3MallocZero( sizeof(sqlite3) );
  115334. if( db==0 ) goto opendb_out;
  115335. if( isThreadsafe ){
  115336. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  115337. if( db->mutex==0 ){
  115338. sqlite3_free(db);
  115339. db = 0;
  115340. goto opendb_out;
  115341. }
  115342. }
  115343. sqlite3_mutex_enter(db->mutex);
  115344. db->errMask = 0xff;
  115345. db->nDb = 2;
  115346. db->magic = SQLITE_MAGIC_BUSY;
  115347. db->aDb = db->aDbStatic;
  115348. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  115349. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  115350. db->autoCommit = 1;
  115351. db->nextAutovac = -1;
  115352. db->szMmap = sqlite3GlobalConfig.szMmap;
  115353. db->nextPagesize = 0;
  115354. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  115355. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  115356. | SQLITE_AutoIndex
  115357. #endif
  115358. #if SQLITE_DEFAULT_FILE_FORMAT<4
  115359. | SQLITE_LegacyFileFmt
  115360. #endif
  115361. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  115362. | SQLITE_LoadExtension
  115363. #endif
  115364. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  115365. | SQLITE_RecTriggers
  115366. #endif
  115367. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  115368. | SQLITE_ForeignKeys
  115369. #endif
  115370. ;
  115371. sqlite3HashInit(&db->aCollSeq);
  115372. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115373. sqlite3HashInit(&db->aModule);
  115374. #endif
  115375. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  115376. ** and UTF-16, so add a version for each to avoid any unnecessary
  115377. ** conversions. The only error that can occur here is a malloc() failure.
  115378. */
  115379. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  115380. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  115381. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  115382. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  115383. if( db->mallocFailed ){
  115384. goto opendb_out;
  115385. }
  115386. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  115387. assert( db->pDfltColl!=0 );
  115388. /* Also add a UTF-8 case-insensitive collation sequence. */
  115389. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  115390. /* Parse the filename/URI argument. */
  115391. db->openFlags = flags;
  115392. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  115393. if( rc!=SQLITE_OK ){
  115394. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  115395. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  115396. sqlite3_free(zErrMsg);
  115397. goto opendb_out;
  115398. }
  115399. /* Open the backend database driver */
  115400. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  115401. flags | SQLITE_OPEN_MAIN_DB);
  115402. if( rc!=SQLITE_OK ){
  115403. if( rc==SQLITE_IOERR_NOMEM ){
  115404. rc = SQLITE_NOMEM;
  115405. }
  115406. sqlite3Error(db, rc, 0);
  115407. goto opendb_out;
  115408. }
  115409. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  115410. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  115411. /* The default safety_level for the main database is 'full'; for the temp
  115412. ** database it is 'NONE'. This matches the pager layer defaults.
  115413. */
  115414. db->aDb[0].zName = "main";
  115415. db->aDb[0].safety_level = 3;
  115416. db->aDb[1].zName = "temp";
  115417. db->aDb[1].safety_level = 1;
  115418. db->magic = SQLITE_MAGIC_OPEN;
  115419. if( db->mallocFailed ){
  115420. goto opendb_out;
  115421. }
  115422. /* Register all built-in functions, but do not attempt to read the
  115423. ** database schema yet. This is delayed until the first time the database
  115424. ** is accessed.
  115425. */
  115426. sqlite3Error(db, SQLITE_OK, 0);
  115427. sqlite3RegisterBuiltinFunctions(db);
  115428. /* Load automatic extensions - extensions that have been registered
  115429. ** using the sqlite3_automatic_extension() API.
  115430. */
  115431. rc = sqlite3_errcode(db);
  115432. if( rc==SQLITE_OK ){
  115433. sqlite3AutoLoadExtensions(db);
  115434. rc = sqlite3_errcode(db);
  115435. if( rc!=SQLITE_OK ){
  115436. goto opendb_out;
  115437. }
  115438. }
  115439. #ifdef SQLITE_ENABLE_FTS1
  115440. if( !db->mallocFailed ){
  115441. extern int sqlite3Fts1Init(sqlite3*);
  115442. rc = sqlite3Fts1Init(db);
  115443. }
  115444. #endif
  115445. #ifdef SQLITE_ENABLE_FTS2
  115446. if( !db->mallocFailed && rc==SQLITE_OK ){
  115447. extern int sqlite3Fts2Init(sqlite3*);
  115448. rc = sqlite3Fts2Init(db);
  115449. }
  115450. #endif
  115451. #ifdef SQLITE_ENABLE_FTS3
  115452. if( !db->mallocFailed && rc==SQLITE_OK ){
  115453. rc = sqlite3Fts3Init(db);
  115454. }
  115455. #endif
  115456. #ifdef SQLITE_ENABLE_ICU
  115457. if( !db->mallocFailed && rc==SQLITE_OK ){
  115458. rc = sqlite3IcuInit(db);
  115459. }
  115460. #endif
  115461. #ifdef SQLITE_ENABLE_RTREE
  115462. if( !db->mallocFailed && rc==SQLITE_OK){
  115463. rc = sqlite3RtreeInit(db);
  115464. }
  115465. #endif
  115466. sqlite3Error(db, rc, 0);
  115467. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  115468. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  115469. ** mode. Doing nothing at all also makes NORMAL the default.
  115470. */
  115471. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  115472. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  115473. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  115474. SQLITE_DEFAULT_LOCKING_MODE);
  115475. #endif
  115476. /* Enable the lookaside-malloc subsystem */
  115477. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  115478. sqlite3GlobalConfig.nLookaside);
  115479. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  115480. opendb_out:
  115481. sqlite3_free(zOpen);
  115482. if( db ){
  115483. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  115484. sqlite3_mutex_leave(db->mutex);
  115485. }
  115486. rc = sqlite3_errcode(db);
  115487. assert( db!=0 || rc==SQLITE_NOMEM );
  115488. if( rc==SQLITE_NOMEM ){
  115489. sqlite3_close(db);
  115490. db = 0;
  115491. }else if( rc!=SQLITE_OK ){
  115492. db->magic = SQLITE_MAGIC_SICK;
  115493. }
  115494. *ppDb = db;
  115495. #ifdef SQLITE_ENABLE_SQLLOG
  115496. if( sqlite3GlobalConfig.xSqllog ){
  115497. /* Opening a db handle. Fourth parameter is passed 0. */
  115498. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  115499. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  115500. }
  115501. #endif
  115502. return sqlite3ApiExit(0, rc);
  115503. }
  115504. /*
  115505. ** Open a new database handle.
  115506. */
  115507. SQLITE_API int sqlite3_open(
  115508. const char *zFilename,
  115509. sqlite3 **ppDb
  115510. ){
  115511. return openDatabase(zFilename, ppDb,
  115512. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  115513. }
  115514. SQLITE_API int sqlite3_open_v2(
  115515. const char *filename, /* Database filename (UTF-8) */
  115516. sqlite3 **ppDb, /* OUT: SQLite db handle */
  115517. int flags, /* Flags */
  115518. const char *zVfs /* Name of VFS module to use */
  115519. ){
  115520. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  115521. }
  115522. #ifndef SQLITE_OMIT_UTF16
  115523. /*
  115524. ** Open a new database handle.
  115525. */
  115526. SQLITE_API int sqlite3_open16(
  115527. const void *zFilename,
  115528. sqlite3 **ppDb
  115529. ){
  115530. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  115531. sqlite3_value *pVal;
  115532. int rc;
  115533. assert( zFilename );
  115534. assert( ppDb );
  115535. *ppDb = 0;
  115536. #ifndef SQLITE_OMIT_AUTOINIT
  115537. rc = sqlite3_initialize();
  115538. if( rc ) return rc;
  115539. #endif
  115540. pVal = sqlite3ValueNew(0);
  115541. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  115542. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  115543. if( zFilename8 ){
  115544. rc = openDatabase(zFilename8, ppDb,
  115545. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  115546. assert( *ppDb || rc==SQLITE_NOMEM );
  115547. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  115548. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  115549. }
  115550. }else{
  115551. rc = SQLITE_NOMEM;
  115552. }
  115553. sqlite3ValueFree(pVal);
  115554. return sqlite3ApiExit(0, rc);
  115555. }
  115556. #endif /* SQLITE_OMIT_UTF16 */
  115557. /*
  115558. ** Register a new collation sequence with the database handle db.
  115559. */
  115560. SQLITE_API int sqlite3_create_collation(
  115561. sqlite3* db,
  115562. const char *zName,
  115563. int enc,
  115564. void* pCtx,
  115565. int(*xCompare)(void*,int,const void*,int,const void*)
  115566. ){
  115567. int rc;
  115568. sqlite3_mutex_enter(db->mutex);
  115569. assert( !db->mallocFailed );
  115570. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  115571. rc = sqlite3ApiExit(db, rc);
  115572. sqlite3_mutex_leave(db->mutex);
  115573. return rc;
  115574. }
  115575. /*
  115576. ** Register a new collation sequence with the database handle db.
  115577. */
  115578. SQLITE_API int sqlite3_create_collation_v2(
  115579. sqlite3* db,
  115580. const char *zName,
  115581. int enc,
  115582. void* pCtx,
  115583. int(*xCompare)(void*,int,const void*,int,const void*),
  115584. void(*xDel)(void*)
  115585. ){
  115586. int rc;
  115587. sqlite3_mutex_enter(db->mutex);
  115588. assert( !db->mallocFailed );
  115589. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  115590. rc = sqlite3ApiExit(db, rc);
  115591. sqlite3_mutex_leave(db->mutex);
  115592. return rc;
  115593. }
  115594. #ifndef SQLITE_OMIT_UTF16
  115595. /*
  115596. ** Register a new collation sequence with the database handle db.
  115597. */
  115598. SQLITE_API int sqlite3_create_collation16(
  115599. sqlite3* db,
  115600. const void *zName,
  115601. int enc,
  115602. void* pCtx,
  115603. int(*xCompare)(void*,int,const void*,int,const void*)
  115604. ){
  115605. int rc = SQLITE_OK;
  115606. char *zName8;
  115607. sqlite3_mutex_enter(db->mutex);
  115608. assert( !db->mallocFailed );
  115609. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  115610. if( zName8 ){
  115611. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  115612. sqlite3DbFree(db, zName8);
  115613. }
  115614. rc = sqlite3ApiExit(db, rc);
  115615. sqlite3_mutex_leave(db->mutex);
  115616. return rc;
  115617. }
  115618. #endif /* SQLITE_OMIT_UTF16 */
  115619. /*
  115620. ** Register a collation sequence factory callback with the database handle
  115621. ** db. Replace any previously installed collation sequence factory.
  115622. */
  115623. SQLITE_API int sqlite3_collation_needed(
  115624. sqlite3 *db,
  115625. void *pCollNeededArg,
  115626. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  115627. ){
  115628. sqlite3_mutex_enter(db->mutex);
  115629. db->xCollNeeded = xCollNeeded;
  115630. db->xCollNeeded16 = 0;
  115631. db->pCollNeededArg = pCollNeededArg;
  115632. sqlite3_mutex_leave(db->mutex);
  115633. return SQLITE_OK;
  115634. }
  115635. #ifndef SQLITE_OMIT_UTF16
  115636. /*
  115637. ** Register a collation sequence factory callback with the database handle
  115638. ** db. Replace any previously installed collation sequence factory.
  115639. */
  115640. SQLITE_API int sqlite3_collation_needed16(
  115641. sqlite3 *db,
  115642. void *pCollNeededArg,
  115643. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  115644. ){
  115645. sqlite3_mutex_enter(db->mutex);
  115646. db->xCollNeeded = 0;
  115647. db->xCollNeeded16 = xCollNeeded16;
  115648. db->pCollNeededArg = pCollNeededArg;
  115649. sqlite3_mutex_leave(db->mutex);
  115650. return SQLITE_OK;
  115651. }
  115652. #endif /* SQLITE_OMIT_UTF16 */
  115653. #ifndef SQLITE_OMIT_DEPRECATED
  115654. /*
  115655. ** This function is now an anachronism. It used to be used to recover from a
  115656. ** malloc() failure, but SQLite now does this automatically.
  115657. */
  115658. SQLITE_API int sqlite3_global_recover(void){
  115659. return SQLITE_OK;
  115660. }
  115661. #endif
  115662. /*
  115663. ** Test to see whether or not the database connection is in autocommit
  115664. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  115665. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  115666. ** by the next COMMIT or ROLLBACK.
  115667. */
  115668. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  115669. return db->autoCommit;
  115670. }
  115671. /*
  115672. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  115673. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  115674. ** constants. They server two purposes:
  115675. **
  115676. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  115677. ** to detect when version error conditions occurs.
  115678. **
  115679. ** 2. Invoke sqlite3_log() to provide the source code location where
  115680. ** a low-level error is first detected.
  115681. */
  115682. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  115683. testcase( sqlite3GlobalConfig.xLog!=0 );
  115684. sqlite3_log(SQLITE_CORRUPT,
  115685. "database corruption at line %d of [%.10s]",
  115686. lineno, 20+sqlite3_sourceid());
  115687. return SQLITE_CORRUPT;
  115688. }
  115689. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  115690. testcase( sqlite3GlobalConfig.xLog!=0 );
  115691. sqlite3_log(SQLITE_MISUSE,
  115692. "misuse at line %d of [%.10s]",
  115693. lineno, 20+sqlite3_sourceid());
  115694. return SQLITE_MISUSE;
  115695. }
  115696. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  115697. testcase( sqlite3GlobalConfig.xLog!=0 );
  115698. sqlite3_log(SQLITE_CANTOPEN,
  115699. "cannot open file at line %d of [%.10s]",
  115700. lineno, 20+sqlite3_sourceid());
  115701. return SQLITE_CANTOPEN;
  115702. }
  115703. #ifndef SQLITE_OMIT_DEPRECATED
  115704. /*
  115705. ** This is a convenience routine that makes sure that all thread-specific
  115706. ** data for this thread has been deallocated.
  115707. **
  115708. ** SQLite no longer uses thread-specific data so this routine is now a
  115709. ** no-op. It is retained for historical compatibility.
  115710. */
  115711. SQLITE_API void sqlite3_thread_cleanup(void){
  115712. }
  115713. #endif
  115714. /*
  115715. ** Return meta information about a specific column of a database table.
  115716. ** See comment in sqlite3.h (sqlite.h.in) for details.
  115717. */
  115718. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115719. SQLITE_API int sqlite3_table_column_metadata(
  115720. sqlite3 *db, /* Connection handle */
  115721. const char *zDbName, /* Database name or NULL */
  115722. const char *zTableName, /* Table name */
  115723. const char *zColumnName, /* Column name */
  115724. char const **pzDataType, /* OUTPUT: Declared data type */
  115725. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  115726. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  115727. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  115728. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  115729. ){
  115730. int rc;
  115731. char *zErrMsg = 0;
  115732. Table *pTab = 0;
  115733. Column *pCol = 0;
  115734. int iCol;
  115735. char const *zDataType = 0;
  115736. char const *zCollSeq = 0;
  115737. int notnull = 0;
  115738. int primarykey = 0;
  115739. int autoinc = 0;
  115740. /* Ensure the database schema has been loaded */
  115741. sqlite3_mutex_enter(db->mutex);
  115742. sqlite3BtreeEnterAll(db);
  115743. rc = sqlite3Init(db, &zErrMsg);
  115744. if( SQLITE_OK!=rc ){
  115745. goto error_out;
  115746. }
  115747. /* Locate the table in question */
  115748. pTab = sqlite3FindTable(db, zTableName, zDbName);
  115749. if( !pTab || pTab->pSelect ){
  115750. pTab = 0;
  115751. goto error_out;
  115752. }
  115753. /* Find the column for which info is requested */
  115754. if( sqlite3IsRowid(zColumnName) ){
  115755. iCol = pTab->iPKey;
  115756. if( iCol>=0 ){
  115757. pCol = &pTab->aCol[iCol];
  115758. }
  115759. }else{
  115760. for(iCol=0; iCol<pTab->nCol; iCol++){
  115761. pCol = &pTab->aCol[iCol];
  115762. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  115763. break;
  115764. }
  115765. }
  115766. if( iCol==pTab->nCol ){
  115767. pTab = 0;
  115768. goto error_out;
  115769. }
  115770. }
  115771. /* The following block stores the meta information that will be returned
  115772. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  115773. ** and autoinc. At this point there are two possibilities:
  115774. **
  115775. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  115776. ** and there is no explicitly declared IPK column.
  115777. **
  115778. ** 2. The table is not a view and the column name identified an
  115779. ** explicitly declared column. Copy meta information from *pCol.
  115780. */
  115781. if( pCol ){
  115782. zDataType = pCol->zType;
  115783. zCollSeq = pCol->zColl;
  115784. notnull = pCol->notNull!=0;
  115785. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  115786. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  115787. }else{
  115788. zDataType = "INTEGER";
  115789. primarykey = 1;
  115790. }
  115791. if( !zCollSeq ){
  115792. zCollSeq = "BINARY";
  115793. }
  115794. error_out:
  115795. sqlite3BtreeLeaveAll(db);
  115796. /* Whether the function call succeeded or failed, set the output parameters
  115797. ** to whatever their local counterparts contain. If an error did occur,
  115798. ** this has the effect of zeroing all output parameters.
  115799. */
  115800. if( pzDataType ) *pzDataType = zDataType;
  115801. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  115802. if( pNotNull ) *pNotNull = notnull;
  115803. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  115804. if( pAutoinc ) *pAutoinc = autoinc;
  115805. if( SQLITE_OK==rc && !pTab ){
  115806. sqlite3DbFree(db, zErrMsg);
  115807. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  115808. zColumnName);
  115809. rc = SQLITE_ERROR;
  115810. }
  115811. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  115812. sqlite3DbFree(db, zErrMsg);
  115813. rc = sqlite3ApiExit(db, rc);
  115814. sqlite3_mutex_leave(db->mutex);
  115815. return rc;
  115816. }
  115817. #endif
  115818. /*
  115819. ** Sleep for a little while. Return the amount of time slept.
  115820. */
  115821. SQLITE_API int sqlite3_sleep(int ms){
  115822. sqlite3_vfs *pVfs;
  115823. int rc;
  115824. pVfs = sqlite3_vfs_find(0);
  115825. if( pVfs==0 ) return 0;
  115826. /* This function works in milliseconds, but the underlying OsSleep()
  115827. ** API uses microseconds. Hence the 1000's.
  115828. */
  115829. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  115830. return rc;
  115831. }
  115832. /*
  115833. ** Enable or disable the extended result codes.
  115834. */
  115835. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  115836. sqlite3_mutex_enter(db->mutex);
  115837. db->errMask = onoff ? 0xffffffff : 0xff;
  115838. sqlite3_mutex_leave(db->mutex);
  115839. return SQLITE_OK;
  115840. }
  115841. /*
  115842. ** Invoke the xFileControl method on a particular database.
  115843. */
  115844. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  115845. int rc = SQLITE_ERROR;
  115846. Btree *pBtree;
  115847. sqlite3_mutex_enter(db->mutex);
  115848. pBtree = sqlite3DbNameToBtree(db, zDbName);
  115849. if( pBtree ){
  115850. Pager *pPager;
  115851. sqlite3_file *fd;
  115852. sqlite3BtreeEnter(pBtree);
  115853. pPager = sqlite3BtreePager(pBtree);
  115854. assert( pPager!=0 );
  115855. fd = sqlite3PagerFile(pPager);
  115856. assert( fd!=0 );
  115857. if( op==SQLITE_FCNTL_FILE_POINTER ){
  115858. *(sqlite3_file**)pArg = fd;
  115859. rc = SQLITE_OK;
  115860. }else if( fd->pMethods ){
  115861. rc = sqlite3OsFileControl(fd, op, pArg);
  115862. }else{
  115863. rc = SQLITE_NOTFOUND;
  115864. }
  115865. sqlite3BtreeLeave(pBtree);
  115866. }
  115867. sqlite3_mutex_leave(db->mutex);
  115868. return rc;
  115869. }
  115870. /*
  115871. ** Interface to the testing logic.
  115872. */
  115873. SQLITE_API int sqlite3_test_control(int op, ...){
  115874. int rc = 0;
  115875. #ifndef SQLITE_OMIT_BUILTIN_TEST
  115876. va_list ap;
  115877. va_start(ap, op);
  115878. switch( op ){
  115879. /*
  115880. ** Save the current state of the PRNG.
  115881. */
  115882. case SQLITE_TESTCTRL_PRNG_SAVE: {
  115883. sqlite3PrngSaveState();
  115884. break;
  115885. }
  115886. /*
  115887. ** Restore the state of the PRNG to the last state saved using
  115888. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  115889. ** this verb acts like PRNG_RESET.
  115890. */
  115891. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  115892. sqlite3PrngRestoreState();
  115893. break;
  115894. }
  115895. /*
  115896. ** Reset the PRNG back to its uninitialized state. The next call
  115897. ** to sqlite3_randomness() will reseed the PRNG using a single call
  115898. ** to the xRandomness method of the default VFS.
  115899. */
  115900. case SQLITE_TESTCTRL_PRNG_RESET: {
  115901. sqlite3PrngResetState();
  115902. break;
  115903. }
  115904. /*
  115905. ** sqlite3_test_control(BITVEC_TEST, size, program)
  115906. **
  115907. ** Run a test against a Bitvec object of size. The program argument
  115908. ** is an array of integers that defines the test. Return -1 on a
  115909. ** memory allocation error, 0 on success, or non-zero for an error.
  115910. ** See the sqlite3BitvecBuiltinTest() for additional information.
  115911. */
  115912. case SQLITE_TESTCTRL_BITVEC_TEST: {
  115913. int sz = va_arg(ap, int);
  115914. int *aProg = va_arg(ap, int*);
  115915. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  115916. break;
  115917. }
  115918. /*
  115919. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  115920. **
  115921. ** Register hooks to call to indicate which malloc() failures
  115922. ** are benign.
  115923. */
  115924. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  115925. typedef void (*void_function)(void);
  115926. void_function xBenignBegin;
  115927. void_function xBenignEnd;
  115928. xBenignBegin = va_arg(ap, void_function);
  115929. xBenignEnd = va_arg(ap, void_function);
  115930. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  115931. break;
  115932. }
  115933. /*
  115934. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  115935. **
  115936. ** Set the PENDING byte to the value in the argument, if X>0.
  115937. ** Make no changes if X==0. Return the value of the pending byte
  115938. ** as it existing before this routine was called.
  115939. **
  115940. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  115941. ** an incompatible database file format. Changing the PENDING byte
  115942. ** while any database connection is open results in undefined and
  115943. ** dileterious behavior.
  115944. */
  115945. case SQLITE_TESTCTRL_PENDING_BYTE: {
  115946. rc = PENDING_BYTE;
  115947. #ifndef SQLITE_OMIT_WSD
  115948. {
  115949. unsigned int newVal = va_arg(ap, unsigned int);
  115950. if( newVal ) sqlite3PendingByte = newVal;
  115951. }
  115952. #endif
  115953. break;
  115954. }
  115955. /*
  115956. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  115957. **
  115958. ** This action provides a run-time test to see whether or not
  115959. ** assert() was enabled at compile-time. If X is true and assert()
  115960. ** is enabled, then the return value is true. If X is true and
  115961. ** assert() is disabled, then the return value is zero. If X is
  115962. ** false and assert() is enabled, then the assertion fires and the
  115963. ** process aborts. If X is false and assert() is disabled, then the
  115964. ** return value is zero.
  115965. */
  115966. case SQLITE_TESTCTRL_ASSERT: {
  115967. volatile int x = 0;
  115968. assert( (x = va_arg(ap,int))!=0 );
  115969. rc = x;
  115970. break;
  115971. }
  115972. /*
  115973. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  115974. **
  115975. ** This action provides a run-time test to see how the ALWAYS and
  115976. ** NEVER macros were defined at compile-time.
  115977. **
  115978. ** The return value is ALWAYS(X).
  115979. **
  115980. ** The recommended test is X==2. If the return value is 2, that means
  115981. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  115982. ** default setting. If the return value is 1, then ALWAYS() is either
  115983. ** hard-coded to true or else it asserts if its argument is false.
  115984. ** The first behavior (hard-coded to true) is the case if
  115985. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  115986. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  115987. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  115988. **
  115989. ** The run-time test procedure might look something like this:
  115990. **
  115991. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  115992. ** // ALWAYS() and NEVER() are no-op pass-through macros
  115993. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  115994. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  115995. ** }else{
  115996. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  115997. ** }
  115998. */
  115999. case SQLITE_TESTCTRL_ALWAYS: {
  116000. int x = va_arg(ap,int);
  116001. rc = ALWAYS(x);
  116002. break;
  116003. }
  116004. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  116005. **
  116006. ** Set the nReserve size to N for the main database on the database
  116007. ** connection db.
  116008. */
  116009. case SQLITE_TESTCTRL_RESERVE: {
  116010. sqlite3 *db = va_arg(ap, sqlite3*);
  116011. int x = va_arg(ap,int);
  116012. sqlite3_mutex_enter(db->mutex);
  116013. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  116014. sqlite3_mutex_leave(db->mutex);
  116015. break;
  116016. }
  116017. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  116018. **
  116019. ** Enable or disable various optimizations for testing purposes. The
  116020. ** argument N is a bitmask of optimizations to be disabled. For normal
  116021. ** operation N should be 0. The idea is that a test program (like the
  116022. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  116023. ** with various optimizations disabled to verify that the same answer
  116024. ** is obtained in every case.
  116025. */
  116026. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  116027. sqlite3 *db = va_arg(ap, sqlite3*);
  116028. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  116029. break;
  116030. }
  116031. #ifdef SQLITE_N_KEYWORD
  116032. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  116033. **
  116034. ** If zWord is a keyword recognized by the parser, then return the
  116035. ** number of keywords. Or if zWord is not a keyword, return 0.
  116036. **
  116037. ** This test feature is only available in the amalgamation since
  116038. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  116039. ** is built using separate source files.
  116040. */
  116041. case SQLITE_TESTCTRL_ISKEYWORD: {
  116042. const char *zWord = va_arg(ap, const char*);
  116043. int n = sqlite3Strlen30(zWord);
  116044. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  116045. break;
  116046. }
  116047. #endif
  116048. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  116049. **
  116050. ** Pass pFree into sqlite3ScratchFree().
  116051. ** If sz>0 then allocate a scratch buffer into pNew.
  116052. */
  116053. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  116054. void *pFree, **ppNew;
  116055. int sz;
  116056. sz = va_arg(ap, int);
  116057. ppNew = va_arg(ap, void**);
  116058. pFree = va_arg(ap, void*);
  116059. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  116060. sqlite3ScratchFree(pFree);
  116061. break;
  116062. }
  116063. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  116064. **
  116065. ** If parameter onoff is non-zero, configure the wrappers so that all
  116066. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  116067. ** undo this setting.
  116068. */
  116069. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  116070. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  116071. break;
  116072. }
  116073. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  116074. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  116075. ** sqlite3_stmt*,const char**);
  116076. **
  116077. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  116078. ** a string that describes the optimized parse tree. This test-control
  116079. ** returns a pointer to that string.
  116080. */
  116081. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  116082. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  116083. const char **pzRet = va_arg(ap, const char**);
  116084. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  116085. break;
  116086. }
  116087. #endif
  116088. }
  116089. va_end(ap);
  116090. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  116091. return rc;
  116092. }
  116093. /*
  116094. ** This is a utility routine, useful to VFS implementations, that checks
  116095. ** to see if a database file was a URI that contained a specific query
  116096. ** parameter, and if so obtains the value of the query parameter.
  116097. **
  116098. ** The zFilename argument is the filename pointer passed into the xOpen()
  116099. ** method of a VFS implementation. The zParam argument is the name of the
  116100. ** query parameter we seek. This routine returns the value of the zParam
  116101. ** parameter if it exists. If the parameter does not exist, this routine
  116102. ** returns a NULL pointer.
  116103. */
  116104. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  116105. if( zFilename==0 ) return 0;
  116106. zFilename += sqlite3Strlen30(zFilename) + 1;
  116107. while( zFilename[0] ){
  116108. int x = strcmp(zFilename, zParam);
  116109. zFilename += sqlite3Strlen30(zFilename) + 1;
  116110. if( x==0 ) return zFilename;
  116111. zFilename += sqlite3Strlen30(zFilename) + 1;
  116112. }
  116113. return 0;
  116114. }
  116115. /*
  116116. ** Return a boolean value for a query parameter.
  116117. */
  116118. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  116119. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  116120. bDflt = bDflt!=0;
  116121. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  116122. }
  116123. /*
  116124. ** Return a 64-bit integer value for a query parameter.
  116125. */
  116126. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  116127. const char *zFilename, /* Filename as passed to xOpen */
  116128. const char *zParam, /* URI parameter sought */
  116129. sqlite3_int64 bDflt /* return if parameter is missing */
  116130. ){
  116131. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  116132. sqlite3_int64 v;
  116133. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  116134. bDflt = v;
  116135. }
  116136. return bDflt;
  116137. }
  116138. /*
  116139. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  116140. */
  116141. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  116142. int i;
  116143. for(i=0; i<db->nDb; i++){
  116144. if( db->aDb[i].pBt
  116145. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  116146. ){
  116147. return db->aDb[i].pBt;
  116148. }
  116149. }
  116150. return 0;
  116151. }
  116152. /*
  116153. ** Return the filename of the database associated with a database
  116154. ** connection.
  116155. */
  116156. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  116157. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  116158. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  116159. }
  116160. /*
  116161. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  116162. ** no such database exists.
  116163. */
  116164. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  116165. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  116166. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  116167. }
  116168. /************** End of main.c ************************************************/
  116169. /************** Begin file notify.c ******************************************/
  116170. /*
  116171. ** 2009 March 3
  116172. **
  116173. ** The author disclaims copyright to this source code. In place of
  116174. ** a legal notice, here is a blessing:
  116175. **
  116176. ** May you do good and not evil.
  116177. ** May you find forgiveness for yourself and forgive others.
  116178. ** May you share freely, never taking more than you give.
  116179. **
  116180. *************************************************************************
  116181. **
  116182. ** This file contains the implementation of the sqlite3_unlock_notify()
  116183. ** API method and its associated functionality.
  116184. */
  116185. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  116186. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  116187. /*
  116188. ** Public interfaces:
  116189. **
  116190. ** sqlite3ConnectionBlocked()
  116191. ** sqlite3ConnectionUnlocked()
  116192. ** sqlite3ConnectionClosed()
  116193. ** sqlite3_unlock_notify()
  116194. */
  116195. #define assertMutexHeld() \
  116196. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  116197. /*
  116198. ** Head of a linked list of all sqlite3 objects created by this process
  116199. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  116200. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  116201. ** mutex is held.
  116202. */
  116203. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  116204. #ifndef NDEBUG
  116205. /*
  116206. ** This function is a complex assert() that verifies the following
  116207. ** properties of the blocked connections list:
  116208. **
  116209. ** 1) Each entry in the list has a non-NULL value for either
  116210. ** pUnlockConnection or pBlockingConnection, or both.
  116211. **
  116212. ** 2) All entries in the list that share a common value for
  116213. ** xUnlockNotify are grouped together.
  116214. **
  116215. ** 3) If the argument db is not NULL, then none of the entries in the
  116216. ** blocked connections list have pUnlockConnection or pBlockingConnection
  116217. ** set to db. This is used when closing connection db.
  116218. */
  116219. static void checkListProperties(sqlite3 *db){
  116220. sqlite3 *p;
  116221. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  116222. int seen = 0;
  116223. sqlite3 *p2;
  116224. /* Verify property (1) */
  116225. assert( p->pUnlockConnection || p->pBlockingConnection );
  116226. /* Verify property (2) */
  116227. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  116228. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  116229. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  116230. assert( db==0 || p->pUnlockConnection!=db );
  116231. assert( db==0 || p->pBlockingConnection!=db );
  116232. }
  116233. }
  116234. }
  116235. #else
  116236. # define checkListProperties(x)
  116237. #endif
  116238. /*
  116239. ** Remove connection db from the blocked connections list. If connection
  116240. ** db is not currently a part of the list, this function is a no-op.
  116241. */
  116242. static void removeFromBlockedList(sqlite3 *db){
  116243. sqlite3 **pp;
  116244. assertMutexHeld();
  116245. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  116246. if( *pp==db ){
  116247. *pp = (*pp)->pNextBlocked;
  116248. break;
  116249. }
  116250. }
  116251. }
  116252. /*
  116253. ** Add connection db to the blocked connections list. It is assumed
  116254. ** that it is not already a part of the list.
  116255. */
  116256. static void addToBlockedList(sqlite3 *db){
  116257. sqlite3 **pp;
  116258. assertMutexHeld();
  116259. for(
  116260. pp=&sqlite3BlockedList;
  116261. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  116262. pp=&(*pp)->pNextBlocked
  116263. );
  116264. db->pNextBlocked = *pp;
  116265. *pp = db;
  116266. }
  116267. /*
  116268. ** Obtain the STATIC_MASTER mutex.
  116269. */
  116270. static void enterMutex(void){
  116271. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  116272. checkListProperties(0);
  116273. }
  116274. /*
  116275. ** Release the STATIC_MASTER mutex.
  116276. */
  116277. static void leaveMutex(void){
  116278. assertMutexHeld();
  116279. checkListProperties(0);
  116280. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  116281. }
  116282. /*
  116283. ** Register an unlock-notify callback.
  116284. **
  116285. ** This is called after connection "db" has attempted some operation
  116286. ** but has received an SQLITE_LOCKED error because another connection
  116287. ** (call it pOther) in the same process was busy using the same shared
  116288. ** cache. pOther is found by looking at db->pBlockingConnection.
  116289. **
  116290. ** If there is no blocking connection, the callback is invoked immediately,
  116291. ** before this routine returns.
  116292. **
  116293. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  116294. ** a deadlock.
  116295. **
  116296. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  116297. ** its locks.
  116298. **
  116299. ** Each call to this routine overrides any prior callbacks registered
  116300. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  116301. ** cancelled.
  116302. */
  116303. SQLITE_API int sqlite3_unlock_notify(
  116304. sqlite3 *db,
  116305. void (*xNotify)(void **, int),
  116306. void *pArg
  116307. ){
  116308. int rc = SQLITE_OK;
  116309. sqlite3_mutex_enter(db->mutex);
  116310. enterMutex();
  116311. if( xNotify==0 ){
  116312. removeFromBlockedList(db);
  116313. db->pBlockingConnection = 0;
  116314. db->pUnlockConnection = 0;
  116315. db->xUnlockNotify = 0;
  116316. db->pUnlockArg = 0;
  116317. }else if( 0==db->pBlockingConnection ){
  116318. /* The blocking transaction has been concluded. Or there never was a
  116319. ** blocking transaction. In either case, invoke the notify callback
  116320. ** immediately.
  116321. */
  116322. xNotify(&pArg, 1);
  116323. }else{
  116324. sqlite3 *p;
  116325. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  116326. if( p ){
  116327. rc = SQLITE_LOCKED; /* Deadlock detected. */
  116328. }else{
  116329. db->pUnlockConnection = db->pBlockingConnection;
  116330. db->xUnlockNotify = xNotify;
  116331. db->pUnlockArg = pArg;
  116332. removeFromBlockedList(db);
  116333. addToBlockedList(db);
  116334. }
  116335. }
  116336. leaveMutex();
  116337. assert( !db->mallocFailed );
  116338. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  116339. sqlite3_mutex_leave(db->mutex);
  116340. return rc;
  116341. }
  116342. /*
  116343. ** This function is called while stepping or preparing a statement
  116344. ** associated with connection db. The operation will return SQLITE_LOCKED
  116345. ** to the user because it requires a lock that will not be available
  116346. ** until connection pBlocker concludes its current transaction.
  116347. */
  116348. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  116349. enterMutex();
  116350. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  116351. addToBlockedList(db);
  116352. }
  116353. db->pBlockingConnection = pBlocker;
  116354. leaveMutex();
  116355. }
  116356. /*
  116357. ** This function is called when
  116358. ** the transaction opened by database db has just finished. Locks held
  116359. ** by database connection db have been released.
  116360. **
  116361. ** This function loops through each entry in the blocked connections
  116362. ** list and does the following:
  116363. **
  116364. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  116365. ** set to db, then set pBlockingConnection=0.
  116366. **
  116367. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  116368. ** set to db, then invoke the configured unlock-notify callback and
  116369. ** set pUnlockConnection=0.
  116370. **
  116371. ** 3) If the two steps above mean that pBlockingConnection==0 and
  116372. ** pUnlockConnection==0, remove the entry from the blocked connections
  116373. ** list.
  116374. */
  116375. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  116376. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  116377. int nArg = 0; /* Number of entries in aArg[] */
  116378. sqlite3 **pp; /* Iterator variable */
  116379. void **aArg; /* Arguments to the unlock callback */
  116380. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  116381. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  116382. aArg = aStatic;
  116383. enterMutex(); /* Enter STATIC_MASTER mutex */
  116384. /* This loop runs once for each entry in the blocked-connections list. */
  116385. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  116386. sqlite3 *p = *pp;
  116387. /* Step 1. */
  116388. if( p->pBlockingConnection==db ){
  116389. p->pBlockingConnection = 0;
  116390. }
  116391. /* Step 2. */
  116392. if( p->pUnlockConnection==db ){
  116393. assert( p->xUnlockNotify );
  116394. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  116395. xUnlockNotify(aArg, nArg);
  116396. nArg = 0;
  116397. }
  116398. sqlite3BeginBenignMalloc();
  116399. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  116400. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  116401. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  116402. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  116403. ){
  116404. /* The aArg[] array needs to grow. */
  116405. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  116406. if( pNew ){
  116407. memcpy(pNew, aArg, nArg*sizeof(void *));
  116408. sqlite3_free(aDyn);
  116409. aDyn = aArg = pNew;
  116410. }else{
  116411. /* This occurs when the array of context pointers that need to
  116412. ** be passed to the unlock-notify callback is larger than the
  116413. ** aStatic[] array allocated on the stack and the attempt to
  116414. ** allocate a larger array from the heap has failed.
  116415. **
  116416. ** This is a difficult situation to handle. Returning an error
  116417. ** code to the caller is insufficient, as even if an error code
  116418. ** is returned the transaction on connection db will still be
  116419. ** closed and the unlock-notify callbacks on blocked connections
  116420. ** will go unissued. This might cause the application to wait
  116421. ** indefinitely for an unlock-notify callback that will never
  116422. ** arrive.
  116423. **
  116424. ** Instead, invoke the unlock-notify callback with the context
  116425. ** array already accumulated. We can then clear the array and
  116426. ** begin accumulating any further context pointers without
  116427. ** requiring any dynamic allocation. This is sub-optimal because
  116428. ** it means that instead of one callback with a large array of
  116429. ** context pointers the application will receive two or more
  116430. ** callbacks with smaller arrays of context pointers, which will
  116431. ** reduce the applications ability to prioritize multiple
  116432. ** connections. But it is the best that can be done under the
  116433. ** circumstances.
  116434. */
  116435. xUnlockNotify(aArg, nArg);
  116436. nArg = 0;
  116437. }
  116438. }
  116439. sqlite3EndBenignMalloc();
  116440. aArg[nArg++] = p->pUnlockArg;
  116441. xUnlockNotify = p->xUnlockNotify;
  116442. p->pUnlockConnection = 0;
  116443. p->xUnlockNotify = 0;
  116444. p->pUnlockArg = 0;
  116445. }
  116446. /* Step 3. */
  116447. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  116448. /* Remove connection p from the blocked connections list. */
  116449. *pp = p->pNextBlocked;
  116450. p->pNextBlocked = 0;
  116451. }else{
  116452. pp = &p->pNextBlocked;
  116453. }
  116454. }
  116455. if( nArg!=0 ){
  116456. xUnlockNotify(aArg, nArg);
  116457. }
  116458. sqlite3_free(aDyn);
  116459. leaveMutex(); /* Leave STATIC_MASTER mutex */
  116460. }
  116461. /*
  116462. ** This is called when the database connection passed as an argument is
  116463. ** being closed. The connection is removed from the blocked list.
  116464. */
  116465. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  116466. sqlite3ConnectionUnlocked(db);
  116467. enterMutex();
  116468. removeFromBlockedList(db);
  116469. checkListProperties(db);
  116470. leaveMutex();
  116471. }
  116472. #endif
  116473. /************** End of notify.c **********************************************/
  116474. /************** Begin file fts3.c ********************************************/
  116475. /*
  116476. ** 2006 Oct 10
  116477. **
  116478. ** The author disclaims copyright to this source code. In place of
  116479. ** a legal notice, here is a blessing:
  116480. **
  116481. ** May you do good and not evil.
  116482. ** May you find forgiveness for yourself and forgive others.
  116483. ** May you share freely, never taking more than you give.
  116484. **
  116485. ******************************************************************************
  116486. **
  116487. ** This is an SQLite module implementing full-text search.
  116488. */
  116489. /*
  116490. ** The code in this file is only compiled if:
  116491. **
  116492. ** * The FTS3 module is being built as an extension
  116493. ** (in which case SQLITE_CORE is not defined), or
  116494. **
  116495. ** * The FTS3 module is being built into the core of
  116496. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  116497. */
  116498. /* The full-text index is stored in a series of b+tree (-like)
  116499. ** structures called segments which map terms to doclists. The
  116500. ** structures are like b+trees in layout, but are constructed from the
  116501. ** bottom up in optimal fashion and are not updatable. Since trees
  116502. ** are built from the bottom up, things will be described from the
  116503. ** bottom up.
  116504. **
  116505. **
  116506. **** Varints ****
  116507. ** The basic unit of encoding is a variable-length integer called a
  116508. ** varint. We encode variable-length integers in little-endian order
  116509. ** using seven bits * per byte as follows:
  116510. **
  116511. ** KEY:
  116512. ** A = 0xxxxxxx 7 bits of data and one flag bit
  116513. ** B = 1xxxxxxx 7 bits of data and one flag bit
  116514. **
  116515. ** 7 bits - A
  116516. ** 14 bits - BA
  116517. ** 21 bits - BBA
  116518. ** and so on.
  116519. **
  116520. ** This is similar in concept to how sqlite encodes "varints" but
  116521. ** the encoding is not the same. SQLite varints are big-endian
  116522. ** are are limited to 9 bytes in length whereas FTS3 varints are
  116523. ** little-endian and can be up to 10 bytes in length (in theory).
  116524. **
  116525. ** Example encodings:
  116526. **
  116527. ** 1: 0x01
  116528. ** 127: 0x7f
  116529. ** 128: 0x81 0x00
  116530. **
  116531. **
  116532. **** Document lists ****
  116533. ** A doclist (document list) holds a docid-sorted list of hits for a
  116534. ** given term. Doclists hold docids and associated token positions.
  116535. ** A docid is the unique integer identifier for a single document.
  116536. ** A position is the index of a word within the document. The first
  116537. ** word of the document has a position of 0.
  116538. **
  116539. ** FTS3 used to optionally store character offsets using a compile-time
  116540. ** option. But that functionality is no longer supported.
  116541. **
  116542. ** A doclist is stored like this:
  116543. **
  116544. ** array {
  116545. ** varint docid; (delta from previous doclist)
  116546. ** array { (position list for column 0)
  116547. ** varint position; (2 more than the delta from previous position)
  116548. ** }
  116549. ** array {
  116550. ** varint POS_COLUMN; (marks start of position list for new column)
  116551. ** varint column; (index of new column)
  116552. ** array {
  116553. ** varint position; (2 more than the delta from previous position)
  116554. ** }
  116555. ** }
  116556. ** varint POS_END; (marks end of positions for this document.
  116557. ** }
  116558. **
  116559. ** Here, array { X } means zero or more occurrences of X, adjacent in
  116560. ** memory. A "position" is an index of a token in the token stream
  116561. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  116562. ** in the same logical place as the position element, and act as sentinals
  116563. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  116564. ** The positions numbers are not stored literally but rather as two more
  116565. ** than the difference from the prior position, or the just the position plus
  116566. ** 2 for the first position. Example:
  116567. **
  116568. ** label: A B C D E F G H I J K
  116569. ** value: 123 5 9 1 1 14 35 0 234 72 0
  116570. **
  116571. ** The 123 value is the first docid. For column zero in this document
  116572. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  116573. ** at D signals the start of a new column; the 1 at E indicates that the
  116574. ** new column is column number 1. There are two positions at 12 and 45
  116575. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  116576. ** 234 at I is the delta to next docid (357). It has one position 70
  116577. ** (72-2) and then terminates with the 0 at K.
  116578. **
  116579. ** A "position-list" is the list of positions for multiple columns for
  116580. ** a single docid. A "column-list" is the set of positions for a single
  116581. ** column. Hence, a position-list consists of one or more column-lists,
  116582. ** a document record consists of a docid followed by a position-list and
  116583. ** a doclist consists of one or more document records.
  116584. **
  116585. ** A bare doclist omits the position information, becoming an
  116586. ** array of varint-encoded docids.
  116587. **
  116588. **** Segment leaf nodes ****
  116589. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  116590. ** nodes are written using LeafWriter, and read using LeafReader (to
  116591. ** iterate through a single leaf node's data) and LeavesReader (to
  116592. ** iterate through a segment's entire leaf layer). Leaf nodes have
  116593. ** the format:
  116594. **
  116595. ** varint iHeight; (height from leaf level, always 0)
  116596. ** varint nTerm; (length of first term)
  116597. ** char pTerm[nTerm]; (content of first term)
  116598. ** varint nDoclist; (length of term's associated doclist)
  116599. ** char pDoclist[nDoclist]; (content of doclist)
  116600. ** array {
  116601. ** (further terms are delta-encoded)
  116602. ** varint nPrefix; (length of prefix shared with previous term)
  116603. ** varint nSuffix; (length of unshared suffix)
  116604. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  116605. ** varint nDoclist; (length of term's associated doclist)
  116606. ** char pDoclist[nDoclist]; (content of doclist)
  116607. ** }
  116608. **
  116609. ** Here, array { X } means zero or more occurrences of X, adjacent in
  116610. ** memory.
  116611. **
  116612. ** Leaf nodes are broken into blocks which are stored contiguously in
  116613. ** the %_segments table in sorted order. This means that when the end
  116614. ** of a node is reached, the next term is in the node with the next
  116615. ** greater node id.
  116616. **
  116617. ** New data is spilled to a new leaf node when the current node
  116618. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  116619. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  116620. ** node (a leaf node with a single term and doclist). The goal of
  116621. ** these settings is to pack together groups of small doclists while
  116622. ** making it efficient to directly access large doclists. The
  116623. ** assumption is that large doclists represent terms which are more
  116624. ** likely to be query targets.
  116625. **
  116626. ** TODO(shess) It may be useful for blocking decisions to be more
  116627. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  116628. ** node rather than splitting into 2k and .5k nodes. My intuition is
  116629. ** that this might extend through 2x or 4x the pagesize.
  116630. **
  116631. **
  116632. **** Segment interior nodes ****
  116633. ** Segment interior nodes store blockids for subtree nodes and terms
  116634. ** to describe what data is stored by the each subtree. Interior
  116635. ** nodes are written using InteriorWriter, and read using
  116636. ** InteriorReader. InteriorWriters are created as needed when
  116637. ** SegmentWriter creates new leaf nodes, or when an interior node
  116638. ** itself grows too big and must be split. The format of interior
  116639. ** nodes:
  116640. **
  116641. ** varint iHeight; (height from leaf level, always >0)
  116642. ** varint iBlockid; (block id of node's leftmost subtree)
  116643. ** optional {
  116644. ** varint nTerm; (length of first term)
  116645. ** char pTerm[nTerm]; (content of first term)
  116646. ** array {
  116647. ** (further terms are delta-encoded)
  116648. ** varint nPrefix; (length of shared prefix with previous term)
  116649. ** varint nSuffix; (length of unshared suffix)
  116650. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  116651. ** }
  116652. ** }
  116653. **
  116654. ** Here, optional { X } means an optional element, while array { X }
  116655. ** means zero or more occurrences of X, adjacent in memory.
  116656. **
  116657. ** An interior node encodes n terms separating n+1 subtrees. The
  116658. ** subtree blocks are contiguous, so only the first subtree's blockid
  116659. ** is encoded. The subtree at iBlockid will contain all terms less
  116660. ** than the first term encoded (or all terms if no term is encoded).
  116661. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  116662. ** than pTerm[i+1], the subtree for that term will be rooted at
  116663. ** iBlockid+i. Interior nodes only store enough term data to
  116664. ** distinguish adjacent children (if the rightmost term of the left
  116665. ** child is "something", and the leftmost term of the right child is
  116666. ** "wicked", only "w" is stored).
  116667. **
  116668. ** New data is spilled to a new interior node at the same height when
  116669. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  116670. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  116671. ** interior nodes and making the tree too skinny. The interior nodes
  116672. ** at a given height are naturally tracked by interior nodes at
  116673. ** height+1, and so on.
  116674. **
  116675. **
  116676. **** Segment directory ****
  116677. ** The segment directory in table %_segdir stores meta-information for
  116678. ** merging and deleting segments, and also the root node of the
  116679. ** segment's tree.
  116680. **
  116681. ** The root node is the top node of the segment's tree after encoding
  116682. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  116683. ** This could be either a leaf node or an interior node. If the top
  116684. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  116685. ** and a new root interior node is generated (which should always fit
  116686. ** within ROOT_MAX because it only needs space for 2 varints, the
  116687. ** height and the blockid of the previous root).
  116688. **
  116689. ** The meta-information in the segment directory is:
  116690. ** level - segment level (see below)
  116691. ** idx - index within level
  116692. ** - (level,idx uniquely identify a segment)
  116693. ** start_block - first leaf node
  116694. ** leaves_end_block - last leaf node
  116695. ** end_block - last block (including interior nodes)
  116696. ** root - contents of root node
  116697. **
  116698. ** If the root node is a leaf node, then start_block,
  116699. ** leaves_end_block, and end_block are all 0.
  116700. **
  116701. **
  116702. **** Segment merging ****
  116703. ** To amortize update costs, segments are grouped into levels and
  116704. ** merged in batches. Each increase in level represents exponentially
  116705. ** more documents.
  116706. **
  116707. ** New documents (actually, document updates) are tokenized and
  116708. ** written individually (using LeafWriter) to a level 0 segment, with
  116709. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  116710. ** level 0 segments are merged into a single level 1 segment. Level 1
  116711. ** is populated like level 0, and eventually MERGE_COUNT level 1
  116712. ** segments are merged to a single level 2 segment (representing
  116713. ** MERGE_COUNT^2 updates), and so on.
  116714. **
  116715. ** A segment merge traverses all segments at a given level in
  116716. ** parallel, performing a straightforward sorted merge. Since segment
  116717. ** leaf nodes are written in to the %_segments table in order, this
  116718. ** merge traverses the underlying sqlite disk structures efficiently.
  116719. ** After the merge, all segment blocks from the merged level are
  116720. ** deleted.
  116721. **
  116722. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  116723. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  116724. ** very similar performance numbers to 16 on insertion, though they're
  116725. ** a tiny bit slower (perhaps due to more overhead in merge-time
  116726. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  116727. ** 16, 2 about 66% slower than 16.
  116728. **
  116729. ** At query time, high MERGE_COUNT increases the number of segments
  116730. ** which need to be scanned and merged. For instance, with 100k docs
  116731. ** inserted:
  116732. **
  116733. ** MERGE_COUNT segments
  116734. ** 16 25
  116735. ** 8 12
  116736. ** 4 10
  116737. ** 2 6
  116738. **
  116739. ** This appears to have only a moderate impact on queries for very
  116740. ** frequent terms (which are somewhat dominated by segment merge
  116741. ** costs), and infrequent and non-existent terms still seem to be fast
  116742. ** even with many segments.
  116743. **
  116744. ** TODO(shess) That said, it would be nice to have a better query-side
  116745. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  116746. ** optimizations to things like doclist merging will swing the sweet
  116747. ** spot around.
  116748. **
  116749. **
  116750. **
  116751. **** Handling of deletions and updates ****
  116752. ** Since we're using a segmented structure, with no docid-oriented
  116753. ** index into the term index, we clearly cannot simply update the term
  116754. ** index when a document is deleted or updated. For deletions, we
  116755. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  116756. ** we simply write the new doclist. Segment merges overwrite older
  116757. ** data for a particular docid with newer data, so deletes or updates
  116758. ** will eventually overtake the earlier data and knock it out. The
  116759. ** query logic likewise merges doclists so that newer data knocks out
  116760. ** older data.
  116761. */
  116762. /************** Include fts3Int.h in the middle of fts3.c ********************/
  116763. /************** Begin file fts3Int.h *****************************************/
  116764. /*
  116765. ** 2009 Nov 12
  116766. **
  116767. ** The author disclaims copyright to this source code. In place of
  116768. ** a legal notice, here is a blessing:
  116769. **
  116770. ** May you do good and not evil.
  116771. ** May you find forgiveness for yourself and forgive others.
  116772. ** May you share freely, never taking more than you give.
  116773. **
  116774. ******************************************************************************
  116775. **
  116776. */
  116777. #ifndef _FTSINT_H
  116778. #define _FTSINT_H
  116779. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  116780. # define NDEBUG 1
  116781. #endif
  116782. /*
  116783. ** FTS4 is really an extension for FTS3. It is enabled using the
  116784. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  116785. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  116786. */
  116787. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  116788. # define SQLITE_ENABLE_FTS3
  116789. #endif
  116790. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  116791. /* If not building as part of the core, include sqlite3ext.h. */
  116792. #ifndef SQLITE_CORE
  116793. SQLITE_EXTENSION_INIT3
  116794. #endif
  116795. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  116796. /************** Begin file fts3_tokenizer.h **********************************/
  116797. /*
  116798. ** 2006 July 10
  116799. **
  116800. ** The author disclaims copyright to this source code.
  116801. **
  116802. *************************************************************************
  116803. ** Defines the interface to tokenizers used by fulltext-search. There
  116804. ** are three basic components:
  116805. **
  116806. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  116807. ** interface functions. This is essentially the class structure for
  116808. ** tokenizers.
  116809. **
  116810. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  116811. ** including customization information defined at creation time.
  116812. **
  116813. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  116814. ** tokens from a particular input.
  116815. */
  116816. #ifndef _FTS3_TOKENIZER_H_
  116817. #define _FTS3_TOKENIZER_H_
  116818. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  116819. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  116820. ** we will need a way to register the API consistently.
  116821. */
  116822. /*
  116823. ** Structures used by the tokenizer interface. When a new tokenizer
  116824. ** implementation is registered, the caller provides a pointer to
  116825. ** an sqlite3_tokenizer_module containing pointers to the callback
  116826. ** functions that make up an implementation.
  116827. **
  116828. ** When an fts3 table is created, it passes any arguments passed to
  116829. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  116830. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  116831. ** implementation. The xCreate() function in turn returns an
  116832. ** sqlite3_tokenizer structure representing the specific tokenizer to
  116833. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  116834. **
  116835. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  116836. ** method is called. It returns an sqlite3_tokenizer_cursor object
  116837. ** that may be used to tokenize a specific input buffer based on
  116838. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  116839. ** object.
  116840. */
  116841. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  116842. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  116843. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  116844. struct sqlite3_tokenizer_module {
  116845. /*
  116846. ** Structure version. Should always be set to 0 or 1.
  116847. */
  116848. int iVersion;
  116849. /*
  116850. ** Create a new tokenizer. The values in the argv[] array are the
  116851. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  116852. ** TABLE statement that created the fts3 table. For example, if
  116853. ** the following SQL is executed:
  116854. **
  116855. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  116856. **
  116857. ** then argc is set to 2, and the argv[] array contains pointers
  116858. ** to the strings "arg1" and "arg2".
  116859. **
  116860. ** This method should return either SQLITE_OK (0), or an SQLite error
  116861. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  116862. ** to point at the newly created tokenizer structure. The generic
  116863. ** sqlite3_tokenizer.pModule variable should not be initialized by
  116864. ** this callback. The caller will do so.
  116865. */
  116866. int (*xCreate)(
  116867. int argc, /* Size of argv array */
  116868. const char *const*argv, /* Tokenizer argument strings */
  116869. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  116870. );
  116871. /*
  116872. ** Destroy an existing tokenizer. The fts3 module calls this method
  116873. ** exactly once for each successful call to xCreate().
  116874. */
  116875. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  116876. /*
  116877. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  116878. ** is responsible for ensuring that the input buffer remains valid
  116879. ** until the cursor is closed (using the xClose() method).
  116880. */
  116881. int (*xOpen)(
  116882. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  116883. const char *pInput, int nBytes, /* Input buffer */
  116884. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  116885. );
  116886. /*
  116887. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  116888. ** method exactly once for each successful call to xOpen().
  116889. */
  116890. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  116891. /*
  116892. ** Retrieve the next token from the tokenizer cursor pCursor. This
  116893. ** method should either return SQLITE_OK and set the values of the
  116894. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  116895. ** the end of the buffer has been reached, or an SQLite error code.
  116896. **
  116897. ** *ppToken should be set to point at a buffer containing the
  116898. ** normalized version of the token (i.e. after any case-folding and/or
  116899. ** stemming has been performed). *pnBytes should be set to the length
  116900. ** of this buffer in bytes. The input text that generated the token is
  116901. ** identified by the byte offsets returned in *piStartOffset and
  116902. ** *piEndOffset. *piStartOffset should be set to the index of the first
  116903. ** byte of the token in the input buffer. *piEndOffset should be set
  116904. ** to the index of the first byte just past the end of the token in
  116905. ** the input buffer.
  116906. **
  116907. ** The buffer *ppToken is set to point at is managed by the tokenizer
  116908. ** implementation. It is only required to be valid until the next call
  116909. ** to xNext() or xClose().
  116910. */
  116911. /* TODO(shess) current implementation requires pInput to be
  116912. ** nul-terminated. This should either be fixed, or pInput/nBytes
  116913. ** should be converted to zInput.
  116914. */
  116915. int (*xNext)(
  116916. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  116917. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  116918. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  116919. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  116920. int *piPosition /* OUT: Number of tokens returned before this one */
  116921. );
  116922. /***********************************************************************
  116923. ** Methods below this point are only available if iVersion>=1.
  116924. */
  116925. /*
  116926. ** Configure the language id of a tokenizer cursor.
  116927. */
  116928. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  116929. };
  116930. struct sqlite3_tokenizer {
  116931. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  116932. /* Tokenizer implementations will typically add additional fields */
  116933. };
  116934. struct sqlite3_tokenizer_cursor {
  116935. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  116936. /* Tokenizer implementations will typically add additional fields */
  116937. };
  116938. int fts3_global_term_cnt(int iTerm, int iCol);
  116939. int fts3_term_cnt(int iTerm, int iCol);
  116940. #endif /* _FTS3_TOKENIZER_H_ */
  116941. /************** End of fts3_tokenizer.h **************************************/
  116942. /************** Continuing where we left off in fts3Int.h ********************/
  116943. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  116944. /************** Begin file fts3_hash.h ***************************************/
  116945. /*
  116946. ** 2001 September 22
  116947. **
  116948. ** The author disclaims copyright to this source code. In place of
  116949. ** a legal notice, here is a blessing:
  116950. **
  116951. ** May you do good and not evil.
  116952. ** May you find forgiveness for yourself and forgive others.
  116953. ** May you share freely, never taking more than you give.
  116954. **
  116955. *************************************************************************
  116956. ** This is the header file for the generic hash-table implementation
  116957. ** used in SQLite. We've modified it slightly to serve as a standalone
  116958. ** hash table implementation for the full-text indexing module.
  116959. **
  116960. */
  116961. #ifndef _FTS3_HASH_H_
  116962. #define _FTS3_HASH_H_
  116963. /* Forward declarations of structures. */
  116964. typedef struct Fts3Hash Fts3Hash;
  116965. typedef struct Fts3HashElem Fts3HashElem;
  116966. /* A complete hash table is an instance of the following structure.
  116967. ** The internals of this structure are intended to be opaque -- client
  116968. ** code should not attempt to access or modify the fields of this structure
  116969. ** directly. Change this structure only by using the routines below.
  116970. ** However, many of the "procedures" and "functions" for modifying and
  116971. ** accessing this structure are really macros, so we can't really make
  116972. ** this structure opaque.
  116973. */
  116974. struct Fts3Hash {
  116975. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  116976. char copyKey; /* True if copy of key made on insert */
  116977. int count; /* Number of entries in this table */
  116978. Fts3HashElem *first; /* The first element of the array */
  116979. int htsize; /* Number of buckets in the hash table */
  116980. struct _fts3ht { /* the hash table */
  116981. int count; /* Number of entries with this hash */
  116982. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  116983. } *ht;
  116984. };
  116985. /* Each element in the hash table is an instance of the following
  116986. ** structure. All elements are stored on a single doubly-linked list.
  116987. **
  116988. ** Again, this structure is intended to be opaque, but it can't really
  116989. ** be opaque because it is used by macros.
  116990. */
  116991. struct Fts3HashElem {
  116992. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  116993. void *data; /* Data associated with this element */
  116994. void *pKey; int nKey; /* Key associated with this element */
  116995. };
  116996. /*
  116997. ** There are 2 different modes of operation for a hash table:
  116998. **
  116999. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  117000. ** (including the null-terminator, if any). Case
  117001. ** is respected in comparisons.
  117002. **
  117003. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  117004. ** memcmp() is used to compare keys.
  117005. **
  117006. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  117007. */
  117008. #define FTS3_HASH_STRING 1
  117009. #define FTS3_HASH_BINARY 2
  117010. /*
  117011. ** Access routines. To delete, insert a NULL pointer.
  117012. */
  117013. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  117014. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  117015. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  117016. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  117017. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  117018. /*
  117019. ** Shorthand for the functions above
  117020. */
  117021. #define fts3HashInit sqlite3Fts3HashInit
  117022. #define fts3HashInsert sqlite3Fts3HashInsert
  117023. #define fts3HashFind sqlite3Fts3HashFind
  117024. #define fts3HashClear sqlite3Fts3HashClear
  117025. #define fts3HashFindElem sqlite3Fts3HashFindElem
  117026. /*
  117027. ** Macros for looping over all elements of a hash table. The idiom is
  117028. ** like this:
  117029. **
  117030. ** Fts3Hash h;
  117031. ** Fts3HashElem *p;
  117032. ** ...
  117033. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  117034. ** SomeStructure *pData = fts3HashData(p);
  117035. ** // do something with pData
  117036. ** }
  117037. */
  117038. #define fts3HashFirst(H) ((H)->first)
  117039. #define fts3HashNext(E) ((E)->next)
  117040. #define fts3HashData(E) ((E)->data)
  117041. #define fts3HashKey(E) ((E)->pKey)
  117042. #define fts3HashKeysize(E) ((E)->nKey)
  117043. /*
  117044. ** Number of entries in a hash table
  117045. */
  117046. #define fts3HashCount(H) ((H)->count)
  117047. #endif /* _FTS3_HASH_H_ */
  117048. /************** End of fts3_hash.h *******************************************/
  117049. /************** Continuing where we left off in fts3Int.h ********************/
  117050. /*
  117051. ** This constant determines the maximum depth of an FTS expression tree
  117052. ** that the library will create and use. FTS uses recursion to perform
  117053. ** various operations on the query tree, so the disadvantage of a large
  117054. ** limit is that it may allow very large queries to use large amounts
  117055. ** of stack space (perhaps causing a stack overflow).
  117056. */
  117057. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  117058. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  117059. #endif
  117060. /*
  117061. ** This constant controls how often segments are merged. Once there are
  117062. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  117063. ** segment of level N+1.
  117064. */
  117065. #define FTS3_MERGE_COUNT 16
  117066. /*
  117067. ** This is the maximum amount of data (in bytes) to store in the
  117068. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  117069. ** populated as documents are inserted/updated/deleted in a transaction
  117070. ** and used to create a new segment when the transaction is committed.
  117071. ** However if this limit is reached midway through a transaction, a new
  117072. ** segment is created and the hash table cleared immediately.
  117073. */
  117074. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  117075. /*
  117076. ** Macro to return the number of elements in an array. SQLite has a
  117077. ** similar macro called ArraySize(). Use a different name to avoid
  117078. ** a collision when building an amalgamation with built-in FTS3.
  117079. */
  117080. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  117081. #ifndef MIN
  117082. # define MIN(x,y) ((x)<(y)?(x):(y))
  117083. #endif
  117084. #ifndef MAX
  117085. # define MAX(x,y) ((x)>(y)?(x):(y))
  117086. #endif
  117087. /*
  117088. ** Maximum length of a varint encoded integer. The varint format is different
  117089. ** from that used by SQLite, so the maximum length is 10, not 9.
  117090. */
  117091. #define FTS3_VARINT_MAX 10
  117092. /*
  117093. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  117094. ** in the document set and zero or more prefix indexes. All indexes are stored
  117095. ** as one or more b+-trees in the %_segments and %_segdir tables.
  117096. **
  117097. ** It is possible to determine which index a b+-tree belongs to based on the
  117098. ** value stored in the "%_segdir.level" column. Given this value L, the index
  117099. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  117100. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  117101. ** between 1024 and 2047 to index 1, and so on.
  117102. **
  117103. ** It is considered impossible for an index to use more than 1024 levels. In
  117104. ** theory though this may happen, but only after at least
  117105. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  117106. */
  117107. #define FTS3_SEGDIR_MAXLEVEL 1024
  117108. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  117109. /*
  117110. ** The testcase() macro is only used by the amalgamation. If undefined,
  117111. ** make it a no-op.
  117112. */
  117113. #ifndef testcase
  117114. # define testcase(X)
  117115. #endif
  117116. /*
  117117. ** Terminator values for position-lists and column-lists.
  117118. */
  117119. #define POS_COLUMN (1) /* Column-list terminator */
  117120. #define POS_END (0) /* Position-list terminator */
  117121. /*
  117122. ** This section provides definitions to allow the
  117123. ** FTS3 extension to be compiled outside of the
  117124. ** amalgamation.
  117125. */
  117126. #ifndef SQLITE_AMALGAMATION
  117127. /*
  117128. ** Macros indicating that conditional expressions are always true or
  117129. ** false.
  117130. */
  117131. #ifdef SQLITE_COVERAGE_TEST
  117132. # define ALWAYS(x) (1)
  117133. # define NEVER(X) (0)
  117134. #else
  117135. # define ALWAYS(x) (x)
  117136. # define NEVER(x) (x)
  117137. #endif
  117138. /*
  117139. ** Internal types used by SQLite.
  117140. */
  117141. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  117142. typedef short int i16; /* 2-byte (or larger) signed integer */
  117143. typedef unsigned int u32; /* 4-byte unsigned integer */
  117144. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  117145. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  117146. /*
  117147. ** Macro used to suppress compiler warnings for unused parameters.
  117148. */
  117149. #define UNUSED_PARAMETER(x) (void)(x)
  117150. /*
  117151. ** Activate assert() only if SQLITE_TEST is enabled.
  117152. */
  117153. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  117154. # define NDEBUG 1
  117155. #endif
  117156. /*
  117157. ** The TESTONLY macro is used to enclose variable declarations or
  117158. ** other bits of code that are needed to support the arguments
  117159. ** within testcase() and assert() macros.
  117160. */
  117161. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  117162. # define TESTONLY(X) X
  117163. #else
  117164. # define TESTONLY(X)
  117165. #endif
  117166. #endif /* SQLITE_AMALGAMATION */
  117167. #ifdef SQLITE_DEBUG
  117168. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  117169. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  117170. #else
  117171. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  117172. #endif
  117173. typedef struct Fts3Table Fts3Table;
  117174. typedef struct Fts3Cursor Fts3Cursor;
  117175. typedef struct Fts3Expr Fts3Expr;
  117176. typedef struct Fts3Phrase Fts3Phrase;
  117177. typedef struct Fts3PhraseToken Fts3PhraseToken;
  117178. typedef struct Fts3Doclist Fts3Doclist;
  117179. typedef struct Fts3SegFilter Fts3SegFilter;
  117180. typedef struct Fts3DeferredToken Fts3DeferredToken;
  117181. typedef struct Fts3SegReader Fts3SegReader;
  117182. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  117183. /*
  117184. ** A connection to a fulltext index is an instance of the following
  117185. ** structure. The xCreate and xConnect methods create an instance
  117186. ** of this structure and xDestroy and xDisconnect free that instance.
  117187. ** All other methods receive a pointer to the structure as one of their
  117188. ** arguments.
  117189. */
  117190. struct Fts3Table {
  117191. sqlite3_vtab base; /* Base class used by SQLite core */
  117192. sqlite3 *db; /* The database connection */
  117193. const char *zDb; /* logical database name */
  117194. const char *zName; /* virtual table name */
  117195. int nColumn; /* number of named columns in virtual table */
  117196. char **azColumn; /* column names. malloced */
  117197. u8 *abNotindexed; /* True for 'notindexed' columns */
  117198. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  117199. char *zContentTbl; /* content=xxx option, or NULL */
  117200. char *zLanguageid; /* languageid=xxx option, or NULL */
  117201. u8 bAutoincrmerge; /* True if automerge=1 */
  117202. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  117203. /* Precompiled statements used by the implementation. Each of these
  117204. ** statements is run and reset within a single virtual table API call.
  117205. */
  117206. sqlite3_stmt *aStmt[37];
  117207. char *zReadExprlist;
  117208. char *zWriteExprlist;
  117209. int nNodeSize; /* Soft limit for node size */
  117210. u8 bFts4; /* True for FTS4, false for FTS3 */
  117211. u8 bHasStat; /* True if %_stat table exists */
  117212. u8 bHasDocsize; /* True if %_docsize table exists */
  117213. u8 bDescIdx; /* True if doclists are in reverse order */
  117214. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  117215. int nPgsz; /* Page size for host database */
  117216. char *zSegmentsTbl; /* Name of %_segments table */
  117217. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  117218. /*
  117219. ** The following array of hash tables is used to buffer pending index
  117220. ** updates during transactions. All pending updates buffered at any one
  117221. ** time must share a common language-id (see the FTS4 langid= feature).
  117222. ** The current language id is stored in variable iPrevLangid.
  117223. **
  117224. ** A single FTS4 table may have multiple full-text indexes. For each index
  117225. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  117226. ** terms that appear in the document set. Each subsequent index in aIndex[]
  117227. ** is an index of prefixes of a specific length.
  117228. **
  117229. ** Variable nPendingData contains an estimate the memory consumed by the
  117230. ** pending data structures, including hash table overhead, but not including
  117231. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  117232. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  117233. ** recently inserted record.
  117234. */
  117235. int nIndex; /* Size of aIndex[] */
  117236. struct Fts3Index {
  117237. int nPrefix; /* Prefix length (0 for main terms index) */
  117238. Fts3Hash hPending; /* Pending terms table for this index */
  117239. } *aIndex;
  117240. int nMaxPendingData; /* Max pending data before flush to disk */
  117241. int nPendingData; /* Current bytes of pending data */
  117242. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  117243. int iPrevLangid; /* Langid of recently inserted document */
  117244. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  117245. /* State variables used for validating that the transaction control
  117246. ** methods of the virtual table are called at appropriate times. These
  117247. ** values do not contribute to FTS functionality; they are used for
  117248. ** verifying the operation of the SQLite core.
  117249. */
  117250. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  117251. int mxSavepoint; /* Largest valid xSavepoint integer */
  117252. #endif
  117253. #ifdef SQLITE_TEST
  117254. /* True to disable the incremental doclist optimization. This is controled
  117255. ** by special insert command 'test-no-incr-doclist'. */
  117256. int bNoIncrDoclist;
  117257. #endif
  117258. };
  117259. /*
  117260. ** When the core wants to read from the virtual table, it creates a
  117261. ** virtual table cursor (an instance of the following structure) using
  117262. ** the xOpen method. Cursors are destroyed using the xClose method.
  117263. */
  117264. struct Fts3Cursor {
  117265. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  117266. i16 eSearch; /* Search strategy (see below) */
  117267. u8 isEof; /* True if at End Of Results */
  117268. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  117269. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  117270. Fts3Expr *pExpr; /* Parsed MATCH query string */
  117271. int iLangid; /* Language being queried for */
  117272. int nPhrase; /* Number of matchable phrases in query */
  117273. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  117274. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  117275. char *pNextId; /* Pointer into the body of aDoclist */
  117276. char *aDoclist; /* List of docids for full-text queries */
  117277. int nDoclist; /* Size of buffer at aDoclist */
  117278. u8 bDesc; /* True to sort in descending order */
  117279. int eEvalmode; /* An FTS3_EVAL_XX constant */
  117280. int nRowAvg; /* Average size of database rows, in pages */
  117281. sqlite3_int64 nDoc; /* Documents in table */
  117282. i64 iMinDocid; /* Minimum docid to return */
  117283. i64 iMaxDocid; /* Maximum docid to return */
  117284. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  117285. u32 *aMatchinfo; /* Information about most recent match */
  117286. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  117287. char *zMatchinfo; /* Matchinfo specification */
  117288. };
  117289. #define FTS3_EVAL_FILTER 0
  117290. #define FTS3_EVAL_NEXT 1
  117291. #define FTS3_EVAL_MATCHINFO 2
  117292. /*
  117293. ** The Fts3Cursor.eSearch member is always set to one of the following.
  117294. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  117295. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  117296. ** of the column to be searched. For example, in
  117297. **
  117298. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  117299. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  117300. **
  117301. ** Because the LHS of the MATCH operator is 2nd column "b",
  117302. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  117303. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  117304. ** indicating that all columns should be searched,
  117305. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  117306. */
  117307. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  117308. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  117309. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  117310. /*
  117311. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  117312. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  117313. ** above. The upper 16-bits contain a combination of the following
  117314. ** bits, used to describe extra constraints on full-text searches.
  117315. */
  117316. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  117317. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  117318. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  117319. struct Fts3Doclist {
  117320. char *aAll; /* Array containing doclist (or NULL) */
  117321. int nAll; /* Size of a[] in bytes */
  117322. char *pNextDocid; /* Pointer to next docid */
  117323. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  117324. int bFreeList; /* True if pList should be sqlite3_free()d */
  117325. char *pList; /* Pointer to position list following iDocid */
  117326. int nList; /* Length of position list */
  117327. };
  117328. /*
  117329. ** A "phrase" is a sequence of one or more tokens that must match in
  117330. ** sequence. A single token is the base case and the most common case.
  117331. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  117332. ** nToken will be the number of tokens in the string.
  117333. */
  117334. struct Fts3PhraseToken {
  117335. char *z; /* Text of the token */
  117336. int n; /* Number of bytes in buffer z */
  117337. int isPrefix; /* True if token ends with a "*" character */
  117338. int bFirst; /* True if token must appear at position 0 */
  117339. /* Variables above this point are populated when the expression is
  117340. ** parsed (by code in fts3_expr.c). Below this point the variables are
  117341. ** used when evaluating the expression. */
  117342. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  117343. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  117344. };
  117345. struct Fts3Phrase {
  117346. /* Cache of doclist for this phrase. */
  117347. Fts3Doclist doclist;
  117348. int bIncr; /* True if doclist is loaded incrementally */
  117349. int iDoclistToken;
  117350. /* Variables below this point are populated by fts3_expr.c when parsing
  117351. ** a MATCH expression. Everything above is part of the evaluation phase.
  117352. */
  117353. int nToken; /* Number of tokens in the phrase */
  117354. int iColumn; /* Index of column this phrase must match */
  117355. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  117356. };
  117357. /*
  117358. ** A tree of these objects forms the RHS of a MATCH operator.
  117359. **
  117360. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  117361. ** points to a malloced buffer, size nDoclist bytes, containing the results
  117362. ** of this phrase query in FTS3 doclist format. As usual, the initial
  117363. ** "Length" field found in doclists stored on disk is omitted from this
  117364. ** buffer.
  117365. **
  117366. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  117367. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  117368. ** where nCol is the number of columns in the queried FTS table. The array
  117369. ** is populated as follows:
  117370. **
  117371. ** aMI[iCol*3 + 0] = Undefined
  117372. ** aMI[iCol*3 + 1] = Number of occurrences
  117373. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  117374. **
  117375. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  117376. ** when the expression node is.
  117377. */
  117378. struct Fts3Expr {
  117379. int eType; /* One of the FTSQUERY_XXX values defined below */
  117380. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  117381. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  117382. Fts3Expr *pLeft; /* Left operand */
  117383. Fts3Expr *pRight; /* Right operand */
  117384. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  117385. /* The following are used by the fts3_eval.c module. */
  117386. sqlite3_int64 iDocid; /* Current docid */
  117387. u8 bEof; /* True this expression is at EOF already */
  117388. u8 bStart; /* True if iDocid is valid */
  117389. u8 bDeferred; /* True if this expression is entirely deferred */
  117390. u32 *aMI;
  117391. };
  117392. /*
  117393. ** Candidate values for Fts3Query.eType. Note that the order of the first
  117394. ** four values is in order of precedence when parsing expressions. For
  117395. ** example, the following:
  117396. **
  117397. ** "a OR b AND c NOT d NEAR e"
  117398. **
  117399. ** is equivalent to:
  117400. **
  117401. ** "a OR (b AND (c NOT (d NEAR e)))"
  117402. */
  117403. #define FTSQUERY_NEAR 1
  117404. #define FTSQUERY_NOT 2
  117405. #define FTSQUERY_AND 3
  117406. #define FTSQUERY_OR 4
  117407. #define FTSQUERY_PHRASE 5
  117408. /* fts3_write.c */
  117409. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  117410. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  117411. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  117412. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  117413. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  117414. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  117415. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  117416. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  117417. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  117418. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  117419. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  117420. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  117421. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  117422. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  117423. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  117424. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  117425. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  117426. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  117427. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  117428. #else
  117429. # define sqlite3Fts3FreeDeferredTokens(x)
  117430. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  117431. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  117432. # define sqlite3Fts3FreeDeferredDoclists(x)
  117433. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  117434. #endif
  117435. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  117436. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  117437. /* Special values interpreted by sqlite3SegReaderCursor() */
  117438. #define FTS3_SEGCURSOR_PENDING -1
  117439. #define FTS3_SEGCURSOR_ALL -2
  117440. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  117441. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  117442. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  117443. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  117444. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  117445. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  117446. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  117447. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  117448. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  117449. #define FTS3_SEGMENT_PREFIX 0x00000008
  117450. #define FTS3_SEGMENT_SCAN 0x00000010
  117451. #define FTS3_SEGMENT_FIRST 0x00000020
  117452. /* Type passed as 4th argument to SegmentReaderIterate() */
  117453. struct Fts3SegFilter {
  117454. const char *zTerm;
  117455. int nTerm;
  117456. int iCol;
  117457. int flags;
  117458. };
  117459. struct Fts3MultiSegReader {
  117460. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  117461. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  117462. int nSegment; /* Size of apSegment array */
  117463. int nAdvance; /* How many seg-readers to advance */
  117464. Fts3SegFilter *pFilter; /* Pointer to filter object */
  117465. char *aBuffer; /* Buffer to merge doclists in */
  117466. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  117467. int iColFilter; /* If >=0, filter for this column */
  117468. int bRestart;
  117469. /* Used by fts3.c only. */
  117470. int nCost; /* Cost of running iterator */
  117471. int bLookup; /* True if a lookup of a single entry. */
  117472. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  117473. char *zTerm; /* Pointer to term buffer */
  117474. int nTerm; /* Size of zTerm in bytes */
  117475. char *aDoclist; /* Pointer to doclist buffer */
  117476. int nDoclist; /* Size of aDoclist[] in bytes */
  117477. };
  117478. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  117479. /* fts3.c */
  117480. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  117481. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  117482. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  117483. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  117484. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  117485. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  117486. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  117487. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  117488. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  117489. /* fts3_tokenizer.c */
  117490. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  117491. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  117492. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  117493. sqlite3_tokenizer **, char **
  117494. );
  117495. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  117496. /* fts3_snippet.c */
  117497. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  117498. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  117499. const char *, const char *, int, int
  117500. );
  117501. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  117502. /* fts3_expr.c */
  117503. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  117504. char **, int, int, int, const char *, int, Fts3Expr **, char **
  117505. );
  117506. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  117507. #ifdef SQLITE_TEST
  117508. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  117509. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  117510. #endif
  117511. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  117512. sqlite3_tokenizer_cursor **
  117513. );
  117514. /* fts3_aux.c */
  117515. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  117516. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  117517. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  117518. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  117519. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  117520. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  117521. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  117522. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  117523. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  117524. /* fts3_tokenize_vtab.c */
  117525. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  117526. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  117527. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117528. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  117529. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  117530. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  117531. #endif
  117532. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  117533. #endif /* _FTSINT_H */
  117534. /************** End of fts3Int.h *********************************************/
  117535. /************** Continuing where we left off in fts3.c ***********************/
  117536. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117537. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  117538. # define SQLITE_CORE 1
  117539. #endif
  117540. /* #include <assert.h> */
  117541. /* #include <stdlib.h> */
  117542. /* #include <stddef.h> */
  117543. /* #include <stdio.h> */
  117544. /* #include <string.h> */
  117545. /* #include <stdarg.h> */
  117546. #ifndef SQLITE_CORE
  117547. SQLITE_EXTENSION_INIT1
  117548. #endif
  117549. static int fts3EvalNext(Fts3Cursor *pCsr);
  117550. static int fts3EvalStart(Fts3Cursor *pCsr);
  117551. static int fts3TermSegReaderCursor(
  117552. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  117553. /*
  117554. ** Write a 64-bit variable-length integer to memory starting at p[0].
  117555. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  117556. ** The number of bytes written is returned.
  117557. */
  117558. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  117559. unsigned char *q = (unsigned char *) p;
  117560. sqlite_uint64 vu = v;
  117561. do{
  117562. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  117563. vu >>= 7;
  117564. }while( vu!=0 );
  117565. q[-1] &= 0x7f; /* turn off high bit in final byte */
  117566. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  117567. return (int) (q - (unsigned char *)p);
  117568. }
  117569. /*
  117570. ** Read a 64-bit variable-length integer from memory starting at p[0].
  117571. ** Return the number of bytes read, or 0 on error.
  117572. ** The value is stored in *v.
  117573. */
  117574. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  117575. const unsigned char *q = (const unsigned char *) p;
  117576. sqlite_uint64 x = 0, y = 1;
  117577. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  117578. x += y * (*q++ & 0x7f);
  117579. y <<= 7;
  117580. }
  117581. x += y * (*q++);
  117582. *v = (sqlite_int64) x;
  117583. return (int) (q - (unsigned char *)p);
  117584. }
  117585. /*
  117586. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  117587. ** 32-bit integer before it is returned.
  117588. */
  117589. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  117590. sqlite_int64 i;
  117591. int ret = sqlite3Fts3GetVarint(p, &i);
  117592. *pi = (int) i;
  117593. return ret;
  117594. }
  117595. /*
  117596. ** Return the number of bytes required to encode v as a varint
  117597. */
  117598. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  117599. int i = 0;
  117600. do{
  117601. i++;
  117602. v >>= 7;
  117603. }while( v!=0 );
  117604. return i;
  117605. }
  117606. /*
  117607. ** Convert an SQL-style quoted string into a normal string by removing
  117608. ** the quote characters. The conversion is done in-place. If the
  117609. ** input does not begin with a quote character, then this routine
  117610. ** is a no-op.
  117611. **
  117612. ** Examples:
  117613. **
  117614. ** "abc" becomes abc
  117615. ** 'xyz' becomes xyz
  117616. ** [pqr] becomes pqr
  117617. ** `mno` becomes mno
  117618. **
  117619. */
  117620. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  117621. char quote; /* Quote character (if any ) */
  117622. quote = z[0];
  117623. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  117624. int iIn = 1; /* Index of next byte to read from input */
  117625. int iOut = 0; /* Index of next byte to write to output */
  117626. /* If the first byte was a '[', then the close-quote character is a ']' */
  117627. if( quote=='[' ) quote = ']';
  117628. while( ALWAYS(z[iIn]) ){
  117629. if( z[iIn]==quote ){
  117630. if( z[iIn+1]!=quote ) break;
  117631. z[iOut++] = quote;
  117632. iIn += 2;
  117633. }else{
  117634. z[iOut++] = z[iIn++];
  117635. }
  117636. }
  117637. z[iOut] = '\0';
  117638. }
  117639. }
  117640. /*
  117641. ** Read a single varint from the doclist at *pp and advance *pp to point
  117642. ** to the first byte past the end of the varint. Add the value of the varint
  117643. ** to *pVal.
  117644. */
  117645. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  117646. sqlite3_int64 iVal;
  117647. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  117648. *pVal += iVal;
  117649. }
  117650. /*
  117651. ** When this function is called, *pp points to the first byte following a
  117652. ** varint that is part of a doclist (or position-list, or any other list
  117653. ** of varints). This function moves *pp to point to the start of that varint,
  117654. ** and sets *pVal by the varint value.
  117655. **
  117656. ** Argument pStart points to the first byte of the doclist that the
  117657. ** varint is part of.
  117658. */
  117659. static void fts3GetReverseVarint(
  117660. char **pp,
  117661. char *pStart,
  117662. sqlite3_int64 *pVal
  117663. ){
  117664. sqlite3_int64 iVal;
  117665. char *p;
  117666. /* Pointer p now points at the first byte past the varint we are
  117667. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  117668. ** clear on character p[-1]. */
  117669. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  117670. p++;
  117671. *pp = p;
  117672. sqlite3Fts3GetVarint(p, &iVal);
  117673. *pVal = iVal;
  117674. }
  117675. /*
  117676. ** The xDisconnect() virtual table method.
  117677. */
  117678. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  117679. Fts3Table *p = (Fts3Table *)pVtab;
  117680. int i;
  117681. assert( p->nPendingData==0 );
  117682. assert( p->pSegments==0 );
  117683. /* Free any prepared statements held */
  117684. for(i=0; i<SizeofArray(p->aStmt); i++){
  117685. sqlite3_finalize(p->aStmt[i]);
  117686. }
  117687. sqlite3_free(p->zSegmentsTbl);
  117688. sqlite3_free(p->zReadExprlist);
  117689. sqlite3_free(p->zWriteExprlist);
  117690. sqlite3_free(p->zContentTbl);
  117691. sqlite3_free(p->zLanguageid);
  117692. /* Invoke the tokenizer destructor to free the tokenizer. */
  117693. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  117694. sqlite3_free(p);
  117695. return SQLITE_OK;
  117696. }
  117697. /*
  117698. ** Construct one or more SQL statements from the format string given
  117699. ** and then evaluate those statements. The success code is written
  117700. ** into *pRc.
  117701. **
  117702. ** If *pRc is initially non-zero then this routine is a no-op.
  117703. */
  117704. static void fts3DbExec(
  117705. int *pRc, /* Success code */
  117706. sqlite3 *db, /* Database in which to run SQL */
  117707. const char *zFormat, /* Format string for SQL */
  117708. ... /* Arguments to the format string */
  117709. ){
  117710. va_list ap;
  117711. char *zSql;
  117712. if( *pRc ) return;
  117713. va_start(ap, zFormat);
  117714. zSql = sqlite3_vmprintf(zFormat, ap);
  117715. va_end(ap);
  117716. if( zSql==0 ){
  117717. *pRc = SQLITE_NOMEM;
  117718. }else{
  117719. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  117720. sqlite3_free(zSql);
  117721. }
  117722. }
  117723. /*
  117724. ** The xDestroy() virtual table method.
  117725. */
  117726. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  117727. Fts3Table *p = (Fts3Table *)pVtab;
  117728. int rc = SQLITE_OK; /* Return code */
  117729. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  117730. sqlite3 *db = p->db; /* Database handle */
  117731. /* Drop the shadow tables */
  117732. if( p->zContentTbl==0 ){
  117733. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  117734. }
  117735. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  117736. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  117737. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  117738. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  117739. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  117740. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  117741. ** Otherwise, return an SQLite error code.
  117742. */
  117743. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  117744. }
  117745. /*
  117746. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  117747. ** passed as the first argument. This is done as part of the xConnect()
  117748. ** and xCreate() methods.
  117749. **
  117750. ** If *pRc is non-zero when this function is called, it is a no-op.
  117751. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  117752. ** before returning.
  117753. */
  117754. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  117755. if( *pRc==SQLITE_OK ){
  117756. int i; /* Iterator variable */
  117757. int rc; /* Return code */
  117758. char *zSql; /* SQL statement passed to declare_vtab() */
  117759. char *zCols; /* List of user defined columns */
  117760. const char *zLanguageid;
  117761. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  117762. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  117763. /* Create a list of user columns for the virtual table */
  117764. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  117765. for(i=1; zCols && i<p->nColumn; i++){
  117766. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  117767. }
  117768. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  117769. zSql = sqlite3_mprintf(
  117770. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  117771. zCols, p->zName, zLanguageid
  117772. );
  117773. if( !zCols || !zSql ){
  117774. rc = SQLITE_NOMEM;
  117775. }else{
  117776. rc = sqlite3_declare_vtab(p->db, zSql);
  117777. }
  117778. sqlite3_free(zSql);
  117779. sqlite3_free(zCols);
  117780. *pRc = rc;
  117781. }
  117782. }
  117783. /*
  117784. ** Create the %_stat table if it does not already exist.
  117785. */
  117786. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  117787. fts3DbExec(pRc, p->db,
  117788. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  117789. "(id INTEGER PRIMARY KEY, value BLOB);",
  117790. p->zDb, p->zName
  117791. );
  117792. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  117793. }
  117794. /*
  117795. ** Create the backing store tables (%_content, %_segments and %_segdir)
  117796. ** required by the FTS3 table passed as the only argument. This is done
  117797. ** as part of the vtab xCreate() method.
  117798. **
  117799. ** If the p->bHasDocsize boolean is true (indicating that this is an
  117800. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  117801. ** %_stat tables required by FTS4.
  117802. */
  117803. static int fts3CreateTables(Fts3Table *p){
  117804. int rc = SQLITE_OK; /* Return code */
  117805. int i; /* Iterator variable */
  117806. sqlite3 *db = p->db; /* The database connection */
  117807. if( p->zContentTbl==0 ){
  117808. const char *zLanguageid = p->zLanguageid;
  117809. char *zContentCols; /* Columns of %_content table */
  117810. /* Create a list of user columns for the content table */
  117811. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  117812. for(i=0; zContentCols && i<p->nColumn; i++){
  117813. char *z = p->azColumn[i];
  117814. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  117815. }
  117816. if( zLanguageid && zContentCols ){
  117817. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  117818. }
  117819. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  117820. /* Create the content table */
  117821. fts3DbExec(&rc, db,
  117822. "CREATE TABLE %Q.'%q_content'(%s)",
  117823. p->zDb, p->zName, zContentCols
  117824. );
  117825. sqlite3_free(zContentCols);
  117826. }
  117827. /* Create other tables */
  117828. fts3DbExec(&rc, db,
  117829. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  117830. p->zDb, p->zName
  117831. );
  117832. fts3DbExec(&rc, db,
  117833. "CREATE TABLE %Q.'%q_segdir'("
  117834. "level INTEGER,"
  117835. "idx INTEGER,"
  117836. "start_block INTEGER,"
  117837. "leaves_end_block INTEGER,"
  117838. "end_block INTEGER,"
  117839. "root BLOB,"
  117840. "PRIMARY KEY(level, idx)"
  117841. ");",
  117842. p->zDb, p->zName
  117843. );
  117844. if( p->bHasDocsize ){
  117845. fts3DbExec(&rc, db,
  117846. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  117847. p->zDb, p->zName
  117848. );
  117849. }
  117850. assert( p->bHasStat==p->bFts4 );
  117851. if( p->bHasStat ){
  117852. sqlite3Fts3CreateStatTable(&rc, p);
  117853. }
  117854. return rc;
  117855. }
  117856. /*
  117857. ** Store the current database page-size in bytes in p->nPgsz.
  117858. **
  117859. ** If *pRc is non-zero when this function is called, it is a no-op.
  117860. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  117861. ** before returning.
  117862. */
  117863. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  117864. if( *pRc==SQLITE_OK ){
  117865. int rc; /* Return code */
  117866. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  117867. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  117868. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  117869. if( !zSql ){
  117870. rc = SQLITE_NOMEM;
  117871. }else{
  117872. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  117873. if( rc==SQLITE_OK ){
  117874. sqlite3_step(pStmt);
  117875. p->nPgsz = sqlite3_column_int(pStmt, 0);
  117876. rc = sqlite3_finalize(pStmt);
  117877. }else if( rc==SQLITE_AUTH ){
  117878. p->nPgsz = 1024;
  117879. rc = SQLITE_OK;
  117880. }
  117881. }
  117882. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  117883. sqlite3_free(zSql);
  117884. *pRc = rc;
  117885. }
  117886. }
  117887. /*
  117888. ** "Special" FTS4 arguments are column specifications of the following form:
  117889. **
  117890. ** <key> = <value>
  117891. **
  117892. ** There may not be whitespace surrounding the "=" character. The <value>
  117893. ** term may be quoted, but the <key> may not.
  117894. */
  117895. static int fts3IsSpecialColumn(
  117896. const char *z,
  117897. int *pnKey,
  117898. char **pzValue
  117899. ){
  117900. char *zValue;
  117901. const char *zCsr = z;
  117902. while( *zCsr!='=' ){
  117903. if( *zCsr=='\0' ) return 0;
  117904. zCsr++;
  117905. }
  117906. *pnKey = (int)(zCsr-z);
  117907. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  117908. if( zValue ){
  117909. sqlite3Fts3Dequote(zValue);
  117910. }
  117911. *pzValue = zValue;
  117912. return 1;
  117913. }
  117914. /*
  117915. ** Append the output of a printf() style formatting to an existing string.
  117916. */
  117917. static void fts3Appendf(
  117918. int *pRc, /* IN/OUT: Error code */
  117919. char **pz, /* IN/OUT: Pointer to string buffer */
  117920. const char *zFormat, /* Printf format string to append */
  117921. ... /* Arguments for printf format string */
  117922. ){
  117923. if( *pRc==SQLITE_OK ){
  117924. va_list ap;
  117925. char *z;
  117926. va_start(ap, zFormat);
  117927. z = sqlite3_vmprintf(zFormat, ap);
  117928. va_end(ap);
  117929. if( z && *pz ){
  117930. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  117931. sqlite3_free(z);
  117932. z = z2;
  117933. }
  117934. if( z==0 ) *pRc = SQLITE_NOMEM;
  117935. sqlite3_free(*pz);
  117936. *pz = z;
  117937. }
  117938. }
  117939. /*
  117940. ** Return a copy of input string zInput enclosed in double-quotes (") and
  117941. ** with all double quote characters escaped. For example:
  117942. **
  117943. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  117944. **
  117945. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  117946. ** is the callers responsibility to call sqlite3_free() to release this
  117947. ** memory.
  117948. */
  117949. static char *fts3QuoteId(char const *zInput){
  117950. int nRet;
  117951. char *zRet;
  117952. nRet = 2 + (int)strlen(zInput)*2 + 1;
  117953. zRet = sqlite3_malloc(nRet);
  117954. if( zRet ){
  117955. int i;
  117956. char *z = zRet;
  117957. *(z++) = '"';
  117958. for(i=0; zInput[i]; i++){
  117959. if( zInput[i]=='"' ) *(z++) = '"';
  117960. *(z++) = zInput[i];
  117961. }
  117962. *(z++) = '"';
  117963. *(z++) = '\0';
  117964. }
  117965. return zRet;
  117966. }
  117967. /*
  117968. ** Return a list of comma separated SQL expressions and a FROM clause that
  117969. ** could be used in a SELECT statement such as the following:
  117970. **
  117971. ** SELECT <list of expressions> FROM %_content AS x ...
  117972. **
  117973. ** to return the docid, followed by each column of text data in order
  117974. ** from left to write. If parameter zFunc is not NULL, then instead of
  117975. ** being returned directly each column of text data is passed to an SQL
  117976. ** function named zFunc first. For example, if zFunc is "unzip" and the
  117977. ** table has the three user-defined columns "a", "b", and "c", the following
  117978. ** string is returned:
  117979. **
  117980. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  117981. **
  117982. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  117983. ** is the responsibility of the caller to eventually free it.
  117984. **
  117985. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  117986. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  117987. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  117988. ** no error occurs, *pRc is left unmodified.
  117989. */
  117990. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  117991. char *zRet = 0;
  117992. char *zFree = 0;
  117993. char *zFunction;
  117994. int i;
  117995. if( p->zContentTbl==0 ){
  117996. if( !zFunc ){
  117997. zFunction = "";
  117998. }else{
  117999. zFree = zFunction = fts3QuoteId(zFunc);
  118000. }
  118001. fts3Appendf(pRc, &zRet, "docid");
  118002. for(i=0; i<p->nColumn; i++){
  118003. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  118004. }
  118005. if( p->zLanguageid ){
  118006. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  118007. }
  118008. sqlite3_free(zFree);
  118009. }else{
  118010. fts3Appendf(pRc, &zRet, "rowid");
  118011. for(i=0; i<p->nColumn; i++){
  118012. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  118013. }
  118014. if( p->zLanguageid ){
  118015. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  118016. }
  118017. }
  118018. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  118019. p->zDb,
  118020. (p->zContentTbl ? p->zContentTbl : p->zName),
  118021. (p->zContentTbl ? "" : "_content")
  118022. );
  118023. return zRet;
  118024. }
  118025. /*
  118026. ** Return a list of N comma separated question marks, where N is the number
  118027. ** of columns in the %_content table (one for the docid plus one for each
  118028. ** user-defined text column).
  118029. **
  118030. ** If argument zFunc is not NULL, then all but the first question mark
  118031. ** is preceded by zFunc and an open bracket, and followed by a closed
  118032. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  118033. ** user-defined text columns, the following string is returned:
  118034. **
  118035. ** "?, zip(?), zip(?), zip(?)"
  118036. **
  118037. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  118038. ** is the responsibility of the caller to eventually free it.
  118039. **
  118040. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  118041. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  118042. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  118043. ** no error occurs, *pRc is left unmodified.
  118044. */
  118045. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  118046. char *zRet = 0;
  118047. char *zFree = 0;
  118048. char *zFunction;
  118049. int i;
  118050. if( !zFunc ){
  118051. zFunction = "";
  118052. }else{
  118053. zFree = zFunction = fts3QuoteId(zFunc);
  118054. }
  118055. fts3Appendf(pRc, &zRet, "?");
  118056. for(i=0; i<p->nColumn; i++){
  118057. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  118058. }
  118059. if( p->zLanguageid ){
  118060. fts3Appendf(pRc, &zRet, ", ?");
  118061. }
  118062. sqlite3_free(zFree);
  118063. return zRet;
  118064. }
  118065. /*
  118066. ** This function interprets the string at (*pp) as a non-negative integer
  118067. ** value. It reads the integer and sets *pnOut to the value read, then
  118068. ** sets *pp to point to the byte immediately following the last byte of
  118069. ** the integer value.
  118070. **
  118071. ** Only decimal digits ('0'..'9') may be part of an integer value.
  118072. **
  118073. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  118074. ** the output value undefined. Otherwise SQLITE_OK is returned.
  118075. **
  118076. ** This function is used when parsing the "prefix=" FTS4 parameter.
  118077. */
  118078. static int fts3GobbleInt(const char **pp, int *pnOut){
  118079. const char *p; /* Iterator pointer */
  118080. int nInt = 0; /* Output value */
  118081. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  118082. nInt = nInt * 10 + (p[0] - '0');
  118083. }
  118084. if( p==*pp ) return SQLITE_ERROR;
  118085. *pnOut = nInt;
  118086. *pp = p;
  118087. return SQLITE_OK;
  118088. }
  118089. /*
  118090. ** This function is called to allocate an array of Fts3Index structures
  118091. ** representing the indexes maintained by the current FTS table. FTS tables
  118092. ** always maintain the main "terms" index, but may also maintain one or
  118093. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  118094. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  118095. **
  118096. ** Argument zParam is passed the value of the "prefix=" option if one was
  118097. ** specified, or NULL otherwise.
  118098. **
  118099. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  118100. ** the allocated array. *pnIndex is set to the number of elements in the
  118101. ** array. If an error does occur, an SQLite error code is returned.
  118102. **
  118103. ** Regardless of whether or not an error is returned, it is the responsibility
  118104. ** of the caller to call sqlite3_free() on the output array to free it.
  118105. */
  118106. static int fts3PrefixParameter(
  118107. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  118108. int *pnIndex, /* OUT: size of *apIndex[] array */
  118109. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  118110. ){
  118111. struct Fts3Index *aIndex; /* Allocated array */
  118112. int nIndex = 1; /* Number of entries in array */
  118113. if( zParam && zParam[0] ){
  118114. const char *p;
  118115. nIndex++;
  118116. for(p=zParam; *p; p++){
  118117. if( *p==',' ) nIndex++;
  118118. }
  118119. }
  118120. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  118121. *apIndex = aIndex;
  118122. *pnIndex = nIndex;
  118123. if( !aIndex ){
  118124. return SQLITE_NOMEM;
  118125. }
  118126. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  118127. if( zParam ){
  118128. const char *p = zParam;
  118129. int i;
  118130. for(i=1; i<nIndex; i++){
  118131. int nPrefix;
  118132. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  118133. aIndex[i].nPrefix = nPrefix;
  118134. p++;
  118135. }
  118136. }
  118137. return SQLITE_OK;
  118138. }
  118139. /*
  118140. ** This function is called when initializing an FTS4 table that uses the
  118141. ** content=xxx option. It determines the number of and names of the columns
  118142. ** of the new FTS4 table.
  118143. **
  118144. ** The third argument passed to this function is the value passed to the
  118145. ** config=xxx option (i.e. "xxx"). This function queries the database for
  118146. ** a table of that name. If found, the output variables are populated
  118147. ** as follows:
  118148. **
  118149. ** *pnCol: Set to the number of columns table xxx has,
  118150. **
  118151. ** *pnStr: Set to the total amount of space required to store a copy
  118152. ** of each columns name, including the nul-terminator.
  118153. **
  118154. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  118155. ** the name of the corresponding column in table xxx. The array
  118156. ** and its contents are allocated using a single allocation. It
  118157. ** is the responsibility of the caller to free this allocation
  118158. ** by eventually passing the *pazCol value to sqlite3_free().
  118159. **
  118160. ** If the table cannot be found, an error code is returned and the output
  118161. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  118162. ** returned (and the output variables are undefined).
  118163. */
  118164. static int fts3ContentColumns(
  118165. sqlite3 *db, /* Database handle */
  118166. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  118167. const char *zTbl, /* Name of content table */
  118168. const char ***pazCol, /* OUT: Malloc'd array of column names */
  118169. int *pnCol, /* OUT: Size of array *pazCol */
  118170. int *pnStr /* OUT: Bytes of string content */
  118171. ){
  118172. int rc = SQLITE_OK; /* Return code */
  118173. char *zSql; /* "SELECT *" statement on zTbl */
  118174. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  118175. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  118176. if( !zSql ){
  118177. rc = SQLITE_NOMEM;
  118178. }else{
  118179. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  118180. }
  118181. sqlite3_free(zSql);
  118182. if( rc==SQLITE_OK ){
  118183. const char **azCol; /* Output array */
  118184. int nStr = 0; /* Size of all column names (incl. 0x00) */
  118185. int nCol; /* Number of table columns */
  118186. int i; /* Used to iterate through columns */
  118187. /* Loop through the returned columns. Set nStr to the number of bytes of
  118188. ** space required to store a copy of each column name, including the
  118189. ** nul-terminator byte. */
  118190. nCol = sqlite3_column_count(pStmt);
  118191. for(i=0; i<nCol; i++){
  118192. const char *zCol = sqlite3_column_name(pStmt, i);
  118193. nStr += (int)strlen(zCol) + 1;
  118194. }
  118195. /* Allocate and populate the array to return. */
  118196. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  118197. if( azCol==0 ){
  118198. rc = SQLITE_NOMEM;
  118199. }else{
  118200. char *p = (char *)&azCol[nCol];
  118201. for(i=0; i<nCol; i++){
  118202. const char *zCol = sqlite3_column_name(pStmt, i);
  118203. int n = (int)strlen(zCol)+1;
  118204. memcpy(p, zCol, n);
  118205. azCol[i] = p;
  118206. p += n;
  118207. }
  118208. }
  118209. sqlite3_finalize(pStmt);
  118210. /* Set the output variables. */
  118211. *pnCol = nCol;
  118212. *pnStr = nStr;
  118213. *pazCol = azCol;
  118214. }
  118215. return rc;
  118216. }
  118217. /*
  118218. ** This function is the implementation of both the xConnect and xCreate
  118219. ** methods of the FTS3 virtual table.
  118220. **
  118221. ** The argv[] array contains the following:
  118222. **
  118223. ** argv[0] -> module name ("fts3" or "fts4")
  118224. ** argv[1] -> database name
  118225. ** argv[2] -> table name
  118226. ** argv[...] -> "column name" and other module argument fields.
  118227. */
  118228. static int fts3InitVtab(
  118229. int isCreate, /* True for xCreate, false for xConnect */
  118230. sqlite3 *db, /* The SQLite database connection */
  118231. void *pAux, /* Hash table containing tokenizers */
  118232. int argc, /* Number of elements in argv array */
  118233. const char * const *argv, /* xCreate/xConnect argument array */
  118234. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  118235. char **pzErr /* Write any error message here */
  118236. ){
  118237. Fts3Hash *pHash = (Fts3Hash *)pAux;
  118238. Fts3Table *p = 0; /* Pointer to allocated vtab */
  118239. int rc = SQLITE_OK; /* Return code */
  118240. int i; /* Iterator variable */
  118241. int nByte; /* Size of allocation used for *p */
  118242. int iCol; /* Column index */
  118243. int nString = 0; /* Bytes required to hold all column names */
  118244. int nCol = 0; /* Number of columns in the FTS table */
  118245. char *zCsr; /* Space for holding column names */
  118246. int nDb; /* Bytes required to hold database name */
  118247. int nName; /* Bytes required to hold table name */
  118248. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  118249. const char **aCol; /* Array of column names */
  118250. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  118251. int nIndex; /* Size of aIndex[] array */
  118252. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  118253. /* The results of parsing supported FTS4 key=value options: */
  118254. int bNoDocsize = 0; /* True to omit %_docsize table */
  118255. int bDescIdx = 0; /* True to store descending indexes */
  118256. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  118257. char *zCompress = 0; /* compress=? parameter (or NULL) */
  118258. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  118259. char *zContent = 0; /* content=? parameter (or NULL) */
  118260. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  118261. char **azNotindexed = 0; /* The set of notindexed= columns */
  118262. int nNotindexed = 0; /* Size of azNotindexed[] array */
  118263. assert( strlen(argv[0])==4 );
  118264. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  118265. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  118266. );
  118267. nDb = (int)strlen(argv[1]) + 1;
  118268. nName = (int)strlen(argv[2]) + 1;
  118269. nByte = sizeof(const char *) * (argc-2);
  118270. aCol = (const char **)sqlite3_malloc(nByte);
  118271. if( aCol ){
  118272. memset((void*)aCol, 0, nByte);
  118273. azNotindexed = (char **)sqlite3_malloc(nByte);
  118274. }
  118275. if( azNotindexed ){
  118276. memset(azNotindexed, 0, nByte);
  118277. }
  118278. if( !aCol || !azNotindexed ){
  118279. rc = SQLITE_NOMEM;
  118280. goto fts3_init_out;
  118281. }
  118282. /* Loop through all of the arguments passed by the user to the FTS3/4
  118283. ** module (i.e. all the column names and special arguments). This loop
  118284. ** does the following:
  118285. **
  118286. ** + Figures out the number of columns the FTSX table will have, and
  118287. ** the number of bytes of space that must be allocated to store copies
  118288. ** of the column names.
  118289. **
  118290. ** + If there is a tokenizer specification included in the arguments,
  118291. ** initializes the tokenizer pTokenizer.
  118292. */
  118293. for(i=3; rc==SQLITE_OK && i<argc; i++){
  118294. char const *z = argv[i];
  118295. int nKey;
  118296. char *zVal;
  118297. /* Check if this is a tokenizer specification */
  118298. if( !pTokenizer
  118299. && strlen(z)>8
  118300. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  118301. && 0==sqlite3Fts3IsIdChar(z[8])
  118302. ){
  118303. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  118304. }
  118305. /* Check if it is an FTS4 special argument. */
  118306. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  118307. struct Fts4Option {
  118308. const char *zOpt;
  118309. int nOpt;
  118310. } aFts4Opt[] = {
  118311. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  118312. { "prefix", 6 }, /* 1 -> PREFIX */
  118313. { "compress", 8 }, /* 2 -> COMPRESS */
  118314. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  118315. { "order", 5 }, /* 4 -> ORDER */
  118316. { "content", 7 }, /* 5 -> CONTENT */
  118317. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  118318. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  118319. };
  118320. int iOpt;
  118321. if( !zVal ){
  118322. rc = SQLITE_NOMEM;
  118323. }else{
  118324. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  118325. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  118326. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  118327. break;
  118328. }
  118329. }
  118330. if( iOpt==SizeofArray(aFts4Opt) ){
  118331. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  118332. rc = SQLITE_ERROR;
  118333. }else{
  118334. switch( iOpt ){
  118335. case 0: /* MATCHINFO */
  118336. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  118337. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  118338. rc = SQLITE_ERROR;
  118339. }
  118340. bNoDocsize = 1;
  118341. break;
  118342. case 1: /* PREFIX */
  118343. sqlite3_free(zPrefix);
  118344. zPrefix = zVal;
  118345. zVal = 0;
  118346. break;
  118347. case 2: /* COMPRESS */
  118348. sqlite3_free(zCompress);
  118349. zCompress = zVal;
  118350. zVal = 0;
  118351. break;
  118352. case 3: /* UNCOMPRESS */
  118353. sqlite3_free(zUncompress);
  118354. zUncompress = zVal;
  118355. zVal = 0;
  118356. break;
  118357. case 4: /* ORDER */
  118358. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  118359. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  118360. ){
  118361. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  118362. rc = SQLITE_ERROR;
  118363. }
  118364. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  118365. break;
  118366. case 5: /* CONTENT */
  118367. sqlite3_free(zContent);
  118368. zContent = zVal;
  118369. zVal = 0;
  118370. break;
  118371. case 6: /* LANGUAGEID */
  118372. assert( iOpt==6 );
  118373. sqlite3_free(zLanguageid);
  118374. zLanguageid = zVal;
  118375. zVal = 0;
  118376. break;
  118377. case 7: /* NOTINDEXED */
  118378. azNotindexed[nNotindexed++] = zVal;
  118379. zVal = 0;
  118380. break;
  118381. }
  118382. }
  118383. sqlite3_free(zVal);
  118384. }
  118385. }
  118386. /* Otherwise, the argument is a column name. */
  118387. else {
  118388. nString += (int)(strlen(z) + 1);
  118389. aCol[nCol++] = z;
  118390. }
  118391. }
  118392. /* If a content=xxx option was specified, the following:
  118393. **
  118394. ** 1. Ignore any compress= and uncompress= options.
  118395. **
  118396. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  118397. ** TABLE statement, use all columns from the content table.
  118398. */
  118399. if( rc==SQLITE_OK && zContent ){
  118400. sqlite3_free(zCompress);
  118401. sqlite3_free(zUncompress);
  118402. zCompress = 0;
  118403. zUncompress = 0;
  118404. if( nCol==0 ){
  118405. sqlite3_free((void*)aCol);
  118406. aCol = 0;
  118407. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  118408. /* If a languageid= option was specified, remove the language id
  118409. ** column from the aCol[] array. */
  118410. if( rc==SQLITE_OK && zLanguageid ){
  118411. int j;
  118412. for(j=0; j<nCol; j++){
  118413. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  118414. int k;
  118415. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  118416. nCol--;
  118417. break;
  118418. }
  118419. }
  118420. }
  118421. }
  118422. }
  118423. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118424. if( nCol==0 ){
  118425. assert( nString==0 );
  118426. aCol[0] = "content";
  118427. nString = 8;
  118428. nCol = 1;
  118429. }
  118430. if( pTokenizer==0 ){
  118431. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  118432. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118433. }
  118434. assert( pTokenizer );
  118435. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  118436. if( rc==SQLITE_ERROR ){
  118437. assert( zPrefix );
  118438. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  118439. }
  118440. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118441. /* Allocate and populate the Fts3Table structure. */
  118442. nByte = sizeof(Fts3Table) + /* Fts3Table */
  118443. nCol * sizeof(char *) + /* azColumn */
  118444. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  118445. nCol * sizeof(u8) + /* abNotindexed */
  118446. nName + /* zName */
  118447. nDb + /* zDb */
  118448. nString; /* Space for azColumn strings */
  118449. p = (Fts3Table*)sqlite3_malloc(nByte);
  118450. if( p==0 ){
  118451. rc = SQLITE_NOMEM;
  118452. goto fts3_init_out;
  118453. }
  118454. memset(p, 0, nByte);
  118455. p->db = db;
  118456. p->nColumn = nCol;
  118457. p->nPendingData = 0;
  118458. p->azColumn = (char **)&p[1];
  118459. p->pTokenizer = pTokenizer;
  118460. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  118461. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  118462. p->bHasStat = isFts4;
  118463. p->bFts4 = isFts4;
  118464. p->bDescIdx = bDescIdx;
  118465. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  118466. p->zContentTbl = zContent;
  118467. p->zLanguageid = zLanguageid;
  118468. zContent = 0;
  118469. zLanguageid = 0;
  118470. TESTONLY( p->inTransaction = -1 );
  118471. TESTONLY( p->mxSavepoint = -1 );
  118472. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  118473. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  118474. p->nIndex = nIndex;
  118475. for(i=0; i<nIndex; i++){
  118476. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  118477. }
  118478. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  118479. /* Fill in the zName and zDb fields of the vtab structure. */
  118480. zCsr = (char *)&p->abNotindexed[nCol];
  118481. p->zName = zCsr;
  118482. memcpy(zCsr, argv[2], nName);
  118483. zCsr += nName;
  118484. p->zDb = zCsr;
  118485. memcpy(zCsr, argv[1], nDb);
  118486. zCsr += nDb;
  118487. /* Fill in the azColumn array */
  118488. for(iCol=0; iCol<nCol; iCol++){
  118489. char *z;
  118490. int n = 0;
  118491. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  118492. memcpy(zCsr, z, n);
  118493. zCsr[n] = '\0';
  118494. sqlite3Fts3Dequote(zCsr);
  118495. p->azColumn[iCol] = zCsr;
  118496. zCsr += n+1;
  118497. assert( zCsr <= &((char *)p)[nByte] );
  118498. }
  118499. /* Fill in the abNotindexed array */
  118500. for(iCol=0; iCol<nCol; iCol++){
  118501. int n = (int)strlen(p->azColumn[iCol]);
  118502. for(i=0; i<nNotindexed; i++){
  118503. char *zNot = azNotindexed[i];
  118504. if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
  118505. p->abNotindexed[iCol] = 1;
  118506. sqlite3_free(zNot);
  118507. azNotindexed[i] = 0;
  118508. }
  118509. }
  118510. }
  118511. for(i=0; i<nNotindexed; i++){
  118512. if( azNotindexed[i] ){
  118513. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  118514. rc = SQLITE_ERROR;
  118515. }
  118516. }
  118517. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  118518. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  118519. rc = SQLITE_ERROR;
  118520. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  118521. }
  118522. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  118523. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  118524. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118525. /* If this is an xCreate call, create the underlying tables in the
  118526. ** database. TODO: For xConnect(), it could verify that said tables exist.
  118527. */
  118528. if( isCreate ){
  118529. rc = fts3CreateTables(p);
  118530. }
  118531. /* Check to see if a legacy fts3 table has been "upgraded" by the
  118532. ** addition of a %_stat table so that it can use incremental merge.
  118533. */
  118534. if( !isFts4 && !isCreate ){
  118535. int rc2 = SQLITE_OK;
  118536. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  118537. p->zDb, p->zName);
  118538. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  118539. }
  118540. /* Figure out the page-size for the database. This is required in order to
  118541. ** estimate the cost of loading large doclists from the database. */
  118542. fts3DatabasePageSize(&rc, p);
  118543. p->nNodeSize = p->nPgsz-35;
  118544. /* Declare the table schema to SQLite. */
  118545. fts3DeclareVtab(&rc, p);
  118546. fts3_init_out:
  118547. sqlite3_free(zPrefix);
  118548. sqlite3_free(aIndex);
  118549. sqlite3_free(zCompress);
  118550. sqlite3_free(zUncompress);
  118551. sqlite3_free(zContent);
  118552. sqlite3_free(zLanguageid);
  118553. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  118554. sqlite3_free((void *)aCol);
  118555. sqlite3_free((void *)azNotindexed);
  118556. if( rc!=SQLITE_OK ){
  118557. if( p ){
  118558. fts3DisconnectMethod((sqlite3_vtab *)p);
  118559. }else if( pTokenizer ){
  118560. pTokenizer->pModule->xDestroy(pTokenizer);
  118561. }
  118562. }else{
  118563. assert( p->pSegments==0 );
  118564. *ppVTab = &p->base;
  118565. }
  118566. return rc;
  118567. }
  118568. /*
  118569. ** The xConnect() and xCreate() methods for the virtual table. All the
  118570. ** work is done in function fts3InitVtab().
  118571. */
  118572. static int fts3ConnectMethod(
  118573. sqlite3 *db, /* Database connection */
  118574. void *pAux, /* Pointer to tokenizer hash table */
  118575. int argc, /* Number of elements in argv array */
  118576. const char * const *argv, /* xCreate/xConnect argument array */
  118577. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  118578. char **pzErr /* OUT: sqlite3_malloc'd error message */
  118579. ){
  118580. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  118581. }
  118582. static int fts3CreateMethod(
  118583. sqlite3 *db, /* Database connection */
  118584. void *pAux, /* Pointer to tokenizer hash table */
  118585. int argc, /* Number of elements in argv array */
  118586. const char * const *argv, /* xCreate/xConnect argument array */
  118587. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  118588. char **pzErr /* OUT: sqlite3_malloc'd error message */
  118589. ){
  118590. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  118591. }
  118592. /*
  118593. ** Implementation of the xBestIndex method for FTS3 tables. There
  118594. ** are three possible strategies, in order of preference:
  118595. **
  118596. ** 1. Direct lookup by rowid or docid.
  118597. ** 2. Full-text search using a MATCH operator on a non-docid column.
  118598. ** 3. Linear scan of %_content table.
  118599. */
  118600. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  118601. Fts3Table *p = (Fts3Table *)pVTab;
  118602. int i; /* Iterator variable */
  118603. int iCons = -1; /* Index of constraint to use */
  118604. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  118605. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  118606. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  118607. int iIdx;
  118608. /* By default use a full table scan. This is an expensive option,
  118609. ** so search through the constraints to see if a more efficient
  118610. ** strategy is possible.
  118611. */
  118612. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  118613. pInfo->estimatedCost = 5000000;
  118614. for(i=0; i<pInfo->nConstraint; i++){
  118615. int bDocid; /* True if this constraint is on docid */
  118616. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  118617. if( pCons->usable==0 ) continue;
  118618. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  118619. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  118620. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  118621. pInfo->idxNum = FTS3_DOCID_SEARCH;
  118622. pInfo->estimatedCost = 1.0;
  118623. iCons = i;
  118624. }
  118625. /* A MATCH constraint. Use a full-text search.
  118626. **
  118627. ** If there is more than one MATCH constraint available, use the first
  118628. ** one encountered. If there is both a MATCH constraint and a direct
  118629. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  118630. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  118631. ** it would lead to an "unable to use function MATCH in the requested
  118632. ** context" error.
  118633. */
  118634. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  118635. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  118636. ){
  118637. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  118638. pInfo->estimatedCost = 2.0;
  118639. iCons = i;
  118640. }
  118641. /* Equality constraint on the langid column */
  118642. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  118643. && pCons->iColumn==p->nColumn + 2
  118644. ){
  118645. iLangidCons = i;
  118646. }
  118647. if( bDocid ){
  118648. switch( pCons->op ){
  118649. case SQLITE_INDEX_CONSTRAINT_GE:
  118650. case SQLITE_INDEX_CONSTRAINT_GT:
  118651. iDocidGe = i;
  118652. break;
  118653. case SQLITE_INDEX_CONSTRAINT_LE:
  118654. case SQLITE_INDEX_CONSTRAINT_LT:
  118655. iDocidLe = i;
  118656. break;
  118657. }
  118658. }
  118659. }
  118660. iIdx = 1;
  118661. if( iCons>=0 ){
  118662. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  118663. pInfo->aConstraintUsage[iCons].omit = 1;
  118664. }
  118665. if( iLangidCons>=0 ){
  118666. pInfo->idxNum |= FTS3_HAVE_LANGID;
  118667. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  118668. }
  118669. if( iDocidGe>=0 ){
  118670. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  118671. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  118672. }
  118673. if( iDocidLe>=0 ){
  118674. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  118675. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  118676. }
  118677. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  118678. ** docid) order. Both ascending and descending are possible.
  118679. */
  118680. if( pInfo->nOrderBy==1 ){
  118681. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  118682. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  118683. if( pOrder->desc ){
  118684. pInfo->idxStr = "DESC";
  118685. }else{
  118686. pInfo->idxStr = "ASC";
  118687. }
  118688. pInfo->orderByConsumed = 1;
  118689. }
  118690. }
  118691. assert( p->pSegments==0 );
  118692. return SQLITE_OK;
  118693. }
  118694. /*
  118695. ** Implementation of xOpen method.
  118696. */
  118697. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  118698. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  118699. UNUSED_PARAMETER(pVTab);
  118700. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  118701. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  118702. ** if the allocation fails, return SQLITE_NOMEM.
  118703. */
  118704. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  118705. if( !pCsr ){
  118706. return SQLITE_NOMEM;
  118707. }
  118708. memset(pCsr, 0, sizeof(Fts3Cursor));
  118709. return SQLITE_OK;
  118710. }
  118711. /*
  118712. ** Close the cursor. For additional information see the documentation
  118713. ** on the xClose method of the virtual table interface.
  118714. */
  118715. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  118716. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  118717. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  118718. sqlite3_finalize(pCsr->pStmt);
  118719. sqlite3Fts3ExprFree(pCsr->pExpr);
  118720. sqlite3Fts3FreeDeferredTokens(pCsr);
  118721. sqlite3_free(pCsr->aDoclist);
  118722. sqlite3_free(pCsr->aMatchinfo);
  118723. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  118724. sqlite3_free(pCsr);
  118725. return SQLITE_OK;
  118726. }
  118727. /*
  118728. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  118729. ** compose and prepare an SQL statement of the form:
  118730. **
  118731. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  118732. **
  118733. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  118734. ** it. If an error occurs, return an SQLite error code.
  118735. **
  118736. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  118737. */
  118738. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  118739. int rc = SQLITE_OK;
  118740. if( pCsr->pStmt==0 ){
  118741. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  118742. char *zSql;
  118743. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  118744. if( !zSql ) return SQLITE_NOMEM;
  118745. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  118746. sqlite3_free(zSql);
  118747. }
  118748. *ppStmt = pCsr->pStmt;
  118749. return rc;
  118750. }
  118751. /*
  118752. ** Position the pCsr->pStmt statement so that it is on the row
  118753. ** of the %_content table that contains the last match. Return
  118754. ** SQLITE_OK on success.
  118755. */
  118756. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  118757. int rc = SQLITE_OK;
  118758. if( pCsr->isRequireSeek ){
  118759. sqlite3_stmt *pStmt = 0;
  118760. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  118761. if( rc==SQLITE_OK ){
  118762. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  118763. pCsr->isRequireSeek = 0;
  118764. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  118765. return SQLITE_OK;
  118766. }else{
  118767. rc = sqlite3_reset(pCsr->pStmt);
  118768. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  118769. /* If no row was found and no error has occurred, then the %_content
  118770. ** table is missing a row that is present in the full-text index.
  118771. ** The data structures are corrupt. */
  118772. rc = FTS_CORRUPT_VTAB;
  118773. pCsr->isEof = 1;
  118774. }
  118775. }
  118776. }
  118777. }
  118778. if( rc!=SQLITE_OK && pContext ){
  118779. sqlite3_result_error_code(pContext, rc);
  118780. }
  118781. return rc;
  118782. }
  118783. /*
  118784. ** This function is used to process a single interior node when searching
  118785. ** a b-tree for a term or term prefix. The node data is passed to this
  118786. ** function via the zNode/nNode parameters. The term to search for is
  118787. ** passed in zTerm/nTerm.
  118788. **
  118789. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  118790. ** of the child node that heads the sub-tree that may contain the term.
  118791. **
  118792. ** If piLast is not NULL, then *piLast is set to the right-most child node
  118793. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  118794. ** a prefix.
  118795. **
  118796. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  118797. */
  118798. static int fts3ScanInteriorNode(
  118799. const char *zTerm, /* Term to select leaves for */
  118800. int nTerm, /* Size of term zTerm in bytes */
  118801. const char *zNode, /* Buffer containing segment interior node */
  118802. int nNode, /* Size of buffer at zNode */
  118803. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  118804. sqlite3_int64 *piLast /* OUT: Selected child node */
  118805. ){
  118806. int rc = SQLITE_OK; /* Return code */
  118807. const char *zCsr = zNode; /* Cursor to iterate through node */
  118808. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  118809. char *zBuffer = 0; /* Buffer to load terms into */
  118810. int nAlloc = 0; /* Size of allocated buffer */
  118811. int isFirstTerm = 1; /* True when processing first term on page */
  118812. sqlite3_int64 iChild; /* Block id of child node to descend to */
  118813. /* Skip over the 'height' varint that occurs at the start of every
  118814. ** interior node. Then load the blockid of the left-child of the b-tree
  118815. ** node into variable iChild.
  118816. **
  118817. ** Even if the data structure on disk is corrupted, this (reading two
  118818. ** varints from the buffer) does not risk an overread. If zNode is a
  118819. ** root node, then the buffer comes from a SELECT statement. SQLite does
  118820. ** not make this guarantee explicitly, but in practice there are always
  118821. ** either more than 20 bytes of allocated space following the nNode bytes of
  118822. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  118823. ** table, then there are always 20 bytes of zeroed padding following the
  118824. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  118825. */
  118826. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  118827. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  118828. if( zCsr>zEnd ){
  118829. return FTS_CORRUPT_VTAB;
  118830. }
  118831. while( zCsr<zEnd && (piFirst || piLast) ){
  118832. int cmp; /* memcmp() result */
  118833. int nSuffix; /* Size of term suffix */
  118834. int nPrefix = 0; /* Size of term prefix */
  118835. int nBuffer; /* Total term size */
  118836. /* Load the next term on the node into zBuffer. Use realloc() to expand
  118837. ** the size of zBuffer if required. */
  118838. if( !isFirstTerm ){
  118839. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  118840. }
  118841. isFirstTerm = 0;
  118842. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  118843. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  118844. rc = FTS_CORRUPT_VTAB;
  118845. goto finish_scan;
  118846. }
  118847. if( nPrefix+nSuffix>nAlloc ){
  118848. char *zNew;
  118849. nAlloc = (nPrefix+nSuffix) * 2;
  118850. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  118851. if( !zNew ){
  118852. rc = SQLITE_NOMEM;
  118853. goto finish_scan;
  118854. }
  118855. zBuffer = zNew;
  118856. }
  118857. assert( zBuffer );
  118858. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  118859. nBuffer = nPrefix + nSuffix;
  118860. zCsr += nSuffix;
  118861. /* Compare the term we are searching for with the term just loaded from
  118862. ** the interior node. If the specified term is greater than or equal
  118863. ** to the term from the interior node, then all terms on the sub-tree
  118864. ** headed by node iChild are smaller than zTerm. No need to search
  118865. ** iChild.
  118866. **
  118867. ** If the interior node term is larger than the specified term, then
  118868. ** the tree headed by iChild may contain the specified term.
  118869. */
  118870. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  118871. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  118872. *piFirst = iChild;
  118873. piFirst = 0;
  118874. }
  118875. if( piLast && cmp<0 ){
  118876. *piLast = iChild;
  118877. piLast = 0;
  118878. }
  118879. iChild++;
  118880. };
  118881. if( piFirst ) *piFirst = iChild;
  118882. if( piLast ) *piLast = iChild;
  118883. finish_scan:
  118884. sqlite3_free(zBuffer);
  118885. return rc;
  118886. }
  118887. /*
  118888. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  118889. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  118890. ** contains a term. This function searches the sub-tree headed by the zNode
  118891. ** node for the range of leaf nodes that may contain the specified term
  118892. ** or terms for which the specified term is a prefix.
  118893. **
  118894. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  118895. ** left-most leaf node in the tree that may contain the specified term.
  118896. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  118897. ** right-most leaf node that may contain a term for which the specified
  118898. ** term is a prefix.
  118899. **
  118900. ** It is possible that the range of returned leaf nodes does not contain
  118901. ** the specified term or any terms for which it is a prefix. However, if the
  118902. ** segment does contain any such terms, they are stored within the identified
  118903. ** range. Because this function only inspects interior segment nodes (and
  118904. ** never loads leaf nodes into memory), it is not possible to be sure.
  118905. **
  118906. ** If an error occurs, an error code other than SQLITE_OK is returned.
  118907. */
  118908. static int fts3SelectLeaf(
  118909. Fts3Table *p, /* Virtual table handle */
  118910. const char *zTerm, /* Term to select leaves for */
  118911. int nTerm, /* Size of term zTerm in bytes */
  118912. const char *zNode, /* Buffer containing segment interior node */
  118913. int nNode, /* Size of buffer at zNode */
  118914. sqlite3_int64 *piLeaf, /* Selected leaf node */
  118915. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  118916. ){
  118917. int rc; /* Return code */
  118918. int iHeight; /* Height of this node in tree */
  118919. assert( piLeaf || piLeaf2 );
  118920. sqlite3Fts3GetVarint32(zNode, &iHeight);
  118921. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  118922. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  118923. if( rc==SQLITE_OK && iHeight>1 ){
  118924. char *zBlob = 0; /* Blob read from %_segments table */
  118925. int nBlob; /* Size of zBlob in bytes */
  118926. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  118927. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  118928. if( rc==SQLITE_OK ){
  118929. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  118930. }
  118931. sqlite3_free(zBlob);
  118932. piLeaf = 0;
  118933. zBlob = 0;
  118934. }
  118935. if( rc==SQLITE_OK ){
  118936. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  118937. }
  118938. if( rc==SQLITE_OK ){
  118939. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  118940. }
  118941. sqlite3_free(zBlob);
  118942. }
  118943. return rc;
  118944. }
  118945. /*
  118946. ** This function is used to create delta-encoded serialized lists of FTS3
  118947. ** varints. Each call to this function appends a single varint to a list.
  118948. */
  118949. static void fts3PutDeltaVarint(
  118950. char **pp, /* IN/OUT: Output pointer */
  118951. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  118952. sqlite3_int64 iVal /* Write this value to the list */
  118953. ){
  118954. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  118955. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  118956. *piPrev = iVal;
  118957. }
  118958. /*
  118959. ** When this function is called, *ppPoslist is assumed to point to the
  118960. ** start of a position-list. After it returns, *ppPoslist points to the
  118961. ** first byte after the position-list.
  118962. **
  118963. ** A position list is list of positions (delta encoded) and columns for
  118964. ** a single document record of a doclist. So, in other words, this
  118965. ** routine advances *ppPoslist so that it points to the next docid in
  118966. ** the doclist, or to the first byte past the end of the doclist.
  118967. **
  118968. ** If pp is not NULL, then the contents of the position list are copied
  118969. ** to *pp. *pp is set to point to the first byte past the last byte copied
  118970. ** before this function returns.
  118971. */
  118972. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  118973. char *pEnd = *ppPoslist;
  118974. char c = 0;
  118975. /* The end of a position list is marked by a zero encoded as an FTS3
  118976. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  118977. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  118978. ** of some other, multi-byte, value.
  118979. **
  118980. ** The following while-loop moves pEnd to point to the first byte that is not
  118981. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  118982. ** pEnd once more so that it points to the byte immediately following the
  118983. ** last byte in the position-list.
  118984. */
  118985. while( *pEnd | c ){
  118986. c = *pEnd++ & 0x80;
  118987. testcase( c!=0 && (*pEnd)==0 );
  118988. }
  118989. pEnd++; /* Advance past the POS_END terminator byte */
  118990. if( pp ){
  118991. int n = (int)(pEnd - *ppPoslist);
  118992. char *p = *pp;
  118993. memcpy(p, *ppPoslist, n);
  118994. p += n;
  118995. *pp = p;
  118996. }
  118997. *ppPoslist = pEnd;
  118998. }
  118999. /*
  119000. ** When this function is called, *ppPoslist is assumed to point to the
  119001. ** start of a column-list. After it returns, *ppPoslist points to the
  119002. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  119003. **
  119004. ** A column-list is list of delta-encoded positions for a single column
  119005. ** within a single document within a doclist.
  119006. **
  119007. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  119008. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  119009. ** the POS_COLUMN or POS_END that terminates the column-list.
  119010. **
  119011. ** If pp is not NULL, then the contents of the column-list are copied
  119012. ** to *pp. *pp is set to point to the first byte past the last byte copied
  119013. ** before this function returns. The POS_COLUMN or POS_END terminator
  119014. ** is not copied into *pp.
  119015. */
  119016. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  119017. char *pEnd = *ppPoslist;
  119018. char c = 0;
  119019. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  119020. ** not part of a multi-byte varint.
  119021. */
  119022. while( 0xFE & (*pEnd | c) ){
  119023. c = *pEnd++ & 0x80;
  119024. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  119025. }
  119026. if( pp ){
  119027. int n = (int)(pEnd - *ppPoslist);
  119028. char *p = *pp;
  119029. memcpy(p, *ppPoslist, n);
  119030. p += n;
  119031. *pp = p;
  119032. }
  119033. *ppPoslist = pEnd;
  119034. }
  119035. /*
  119036. ** Value used to signify the end of an position-list. This is safe because
  119037. ** it is not possible to have a document with 2^31 terms.
  119038. */
  119039. #define POSITION_LIST_END 0x7fffffff
  119040. /*
  119041. ** This function is used to help parse position-lists. When this function is
  119042. ** called, *pp may point to the start of the next varint in the position-list
  119043. ** being parsed, or it may point to 1 byte past the end of the position-list
  119044. ** (in which case **pp will be a terminator bytes POS_END (0) or
  119045. ** (1)).
  119046. **
  119047. ** If *pp points past the end of the current position-list, set *pi to
  119048. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  119049. ** increment the current value of *pi by the value read, and set *pp to
  119050. ** point to the next value before returning.
  119051. **
  119052. ** Before calling this routine *pi must be initialized to the value of
  119053. ** the previous position, or zero if we are reading the first position
  119054. ** in the position-list. Because positions are delta-encoded, the value
  119055. ** of the previous position is needed in order to compute the value of
  119056. ** the next position.
  119057. */
  119058. static void fts3ReadNextPos(
  119059. char **pp, /* IN/OUT: Pointer into position-list buffer */
  119060. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  119061. ){
  119062. if( (**pp)&0xFE ){
  119063. fts3GetDeltaVarint(pp, pi);
  119064. *pi -= 2;
  119065. }else{
  119066. *pi = POSITION_LIST_END;
  119067. }
  119068. }
  119069. /*
  119070. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  119071. ** the value of iCol encoded as a varint to *pp. This will start a new
  119072. ** column list.
  119073. **
  119074. ** Set *pp to point to the byte just after the last byte written before
  119075. ** returning (do not modify it if iCol==0). Return the total number of bytes
  119076. ** written (0 if iCol==0).
  119077. */
  119078. static int fts3PutColNumber(char **pp, int iCol){
  119079. int n = 0; /* Number of bytes written */
  119080. if( iCol ){
  119081. char *p = *pp; /* Output pointer */
  119082. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  119083. *p = 0x01;
  119084. *pp = &p[n];
  119085. }
  119086. return n;
  119087. }
  119088. /*
  119089. ** Compute the union of two position lists. The output written
  119090. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  119091. ** order and with any duplicates removed. All pointers are
  119092. ** updated appropriately. The caller is responsible for insuring
  119093. ** that there is enough space in *pp to hold the complete output.
  119094. */
  119095. static void fts3PoslistMerge(
  119096. char **pp, /* Output buffer */
  119097. char **pp1, /* Left input list */
  119098. char **pp2 /* Right input list */
  119099. ){
  119100. char *p = *pp;
  119101. char *p1 = *pp1;
  119102. char *p2 = *pp2;
  119103. while( *p1 || *p2 ){
  119104. int iCol1; /* The current column index in pp1 */
  119105. int iCol2; /* The current column index in pp2 */
  119106. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  119107. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  119108. else iCol1 = 0;
  119109. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  119110. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  119111. else iCol2 = 0;
  119112. if( iCol1==iCol2 ){
  119113. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  119114. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  119115. sqlite3_int64 iPrev = 0;
  119116. int n = fts3PutColNumber(&p, iCol1);
  119117. p1 += n;
  119118. p2 += n;
  119119. /* At this point, both p1 and p2 point to the start of column-lists
  119120. ** for the same column (the column with index iCol1 and iCol2).
  119121. ** A column-list is a list of non-negative delta-encoded varints, each
  119122. ** incremented by 2 before being stored. Each list is terminated by a
  119123. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  119124. ** and writes the results to buffer p. p is left pointing to the byte
  119125. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  119126. ** written to the output.
  119127. */
  119128. fts3GetDeltaVarint(&p1, &i1);
  119129. fts3GetDeltaVarint(&p2, &i2);
  119130. do {
  119131. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  119132. iPrev -= 2;
  119133. if( i1==i2 ){
  119134. fts3ReadNextPos(&p1, &i1);
  119135. fts3ReadNextPos(&p2, &i2);
  119136. }else if( i1<i2 ){
  119137. fts3ReadNextPos(&p1, &i1);
  119138. }else{
  119139. fts3ReadNextPos(&p2, &i2);
  119140. }
  119141. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  119142. }else if( iCol1<iCol2 ){
  119143. p1 += fts3PutColNumber(&p, iCol1);
  119144. fts3ColumnlistCopy(&p, &p1);
  119145. }else{
  119146. p2 += fts3PutColNumber(&p, iCol2);
  119147. fts3ColumnlistCopy(&p, &p2);
  119148. }
  119149. }
  119150. *p++ = POS_END;
  119151. *pp = p;
  119152. *pp1 = p1 + 1;
  119153. *pp2 = p2 + 1;
  119154. }
  119155. /*
  119156. ** This function is used to merge two position lists into one. When it is
  119157. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  119158. ** the part of a doclist that follows each document id. For example, if a row
  119159. ** contains:
  119160. **
  119161. ** 'a b c'|'x y z'|'a b b a'
  119162. **
  119163. ** Then the position list for this row for token 'b' would consist of:
  119164. **
  119165. ** 0x02 0x01 0x02 0x03 0x03 0x00
  119166. **
  119167. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  119168. ** byte following the 0x00 terminator of their respective position lists.
  119169. **
  119170. ** If isSaveLeft is 0, an entry is added to the output position list for
  119171. ** each position in *pp2 for which there exists one or more positions in
  119172. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  119173. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  119174. ** slots before it.
  119175. **
  119176. ** e.g. nToken==1 searches for adjacent positions.
  119177. */
  119178. static int fts3PoslistPhraseMerge(
  119179. char **pp, /* IN/OUT: Preallocated output buffer */
  119180. int nToken, /* Maximum difference in token positions */
  119181. int isSaveLeft, /* Save the left position */
  119182. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  119183. char **pp1, /* IN/OUT: Left input list */
  119184. char **pp2 /* IN/OUT: Right input list */
  119185. ){
  119186. char *p = *pp;
  119187. char *p1 = *pp1;
  119188. char *p2 = *pp2;
  119189. int iCol1 = 0;
  119190. int iCol2 = 0;
  119191. /* Never set both isSaveLeft and isExact for the same invocation. */
  119192. assert( isSaveLeft==0 || isExact==0 );
  119193. assert( p!=0 && *p1!=0 && *p2!=0 );
  119194. if( *p1==POS_COLUMN ){
  119195. p1++;
  119196. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119197. }
  119198. if( *p2==POS_COLUMN ){
  119199. p2++;
  119200. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119201. }
  119202. while( 1 ){
  119203. if( iCol1==iCol2 ){
  119204. char *pSave = p;
  119205. sqlite3_int64 iPrev = 0;
  119206. sqlite3_int64 iPos1 = 0;
  119207. sqlite3_int64 iPos2 = 0;
  119208. if( iCol1 ){
  119209. *p++ = POS_COLUMN;
  119210. p += sqlite3Fts3PutVarint(p, iCol1);
  119211. }
  119212. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  119213. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  119214. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  119215. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  119216. while( 1 ){
  119217. if( iPos2==iPos1+nToken
  119218. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  119219. ){
  119220. sqlite3_int64 iSave;
  119221. iSave = isSaveLeft ? iPos1 : iPos2;
  119222. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  119223. pSave = 0;
  119224. assert( p );
  119225. }
  119226. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  119227. if( (*p2&0xFE)==0 ) break;
  119228. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  119229. }else{
  119230. if( (*p1&0xFE)==0 ) break;
  119231. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  119232. }
  119233. }
  119234. if( pSave ){
  119235. assert( pp && p );
  119236. p = pSave;
  119237. }
  119238. fts3ColumnlistCopy(0, &p1);
  119239. fts3ColumnlistCopy(0, &p2);
  119240. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  119241. if( 0==*p1 || 0==*p2 ) break;
  119242. p1++;
  119243. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119244. p2++;
  119245. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119246. }
  119247. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  119248. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  119249. ** end of the position list, or the 0x01 that precedes the next
  119250. ** column-number in the position list.
  119251. */
  119252. else if( iCol1<iCol2 ){
  119253. fts3ColumnlistCopy(0, &p1);
  119254. if( 0==*p1 ) break;
  119255. p1++;
  119256. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119257. }else{
  119258. fts3ColumnlistCopy(0, &p2);
  119259. if( 0==*p2 ) break;
  119260. p2++;
  119261. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119262. }
  119263. }
  119264. fts3PoslistCopy(0, &p2);
  119265. fts3PoslistCopy(0, &p1);
  119266. *pp1 = p1;
  119267. *pp2 = p2;
  119268. if( *pp==p ){
  119269. return 0;
  119270. }
  119271. *p++ = 0x00;
  119272. *pp = p;
  119273. return 1;
  119274. }
  119275. /*
  119276. ** Merge two position-lists as required by the NEAR operator. The argument
  119277. ** position lists correspond to the left and right phrases of an expression
  119278. ** like:
  119279. **
  119280. ** "phrase 1" NEAR "phrase number 2"
  119281. **
  119282. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  119283. ** expression and *pp2 to the right. As usual, the indexes in the position
  119284. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  119285. ** in the example above).
  119286. **
  119287. ** The output position list - written to *pp - is a copy of *pp2 with those
  119288. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  119289. */
  119290. static int fts3PoslistNearMerge(
  119291. char **pp, /* Output buffer */
  119292. char *aTmp, /* Temporary buffer space */
  119293. int nRight, /* Maximum difference in token positions */
  119294. int nLeft, /* Maximum difference in token positions */
  119295. char **pp1, /* IN/OUT: Left input list */
  119296. char **pp2 /* IN/OUT: Right input list */
  119297. ){
  119298. char *p1 = *pp1;
  119299. char *p2 = *pp2;
  119300. char *pTmp1 = aTmp;
  119301. char *pTmp2;
  119302. char *aTmp2;
  119303. int res = 1;
  119304. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  119305. aTmp2 = pTmp2 = pTmp1;
  119306. *pp1 = p1;
  119307. *pp2 = p2;
  119308. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  119309. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  119310. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  119311. }else if( pTmp1!=aTmp ){
  119312. fts3PoslistCopy(pp, &aTmp);
  119313. }else if( pTmp2!=aTmp2 ){
  119314. fts3PoslistCopy(pp, &aTmp2);
  119315. }else{
  119316. res = 0;
  119317. }
  119318. return res;
  119319. }
  119320. /*
  119321. ** An instance of this function is used to merge together the (potentially
  119322. ** large number of) doclists for each term that matches a prefix query.
  119323. ** See function fts3TermSelectMerge() for details.
  119324. */
  119325. typedef struct TermSelect TermSelect;
  119326. struct TermSelect {
  119327. char *aaOutput[16]; /* Malloc'd output buffers */
  119328. int anOutput[16]; /* Size each output buffer in bytes */
  119329. };
  119330. /*
  119331. ** This function is used to read a single varint from a buffer. Parameter
  119332. ** pEnd points 1 byte past the end of the buffer. When this function is
  119333. ** called, if *pp points to pEnd or greater, then the end of the buffer
  119334. ** has been reached. In this case *pp is set to 0 and the function returns.
  119335. **
  119336. ** If *pp does not point to or past pEnd, then a single varint is read
  119337. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  119338. **
  119339. ** If bDescIdx is false, the value read is added to *pVal before returning.
  119340. ** If it is true, the value read is subtracted from *pVal before this
  119341. ** function returns.
  119342. */
  119343. static void fts3GetDeltaVarint3(
  119344. char **pp, /* IN/OUT: Point to read varint from */
  119345. char *pEnd, /* End of buffer */
  119346. int bDescIdx, /* True if docids are descending */
  119347. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  119348. ){
  119349. if( *pp>=pEnd ){
  119350. *pp = 0;
  119351. }else{
  119352. sqlite3_int64 iVal;
  119353. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  119354. if( bDescIdx ){
  119355. *pVal -= iVal;
  119356. }else{
  119357. *pVal += iVal;
  119358. }
  119359. }
  119360. }
  119361. /*
  119362. ** This function is used to write a single varint to a buffer. The varint
  119363. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  119364. ** end of the value written.
  119365. **
  119366. ** If *pbFirst is zero when this function is called, the value written to
  119367. ** the buffer is that of parameter iVal.
  119368. **
  119369. ** If *pbFirst is non-zero when this function is called, then the value
  119370. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  119371. ** (if bDescIdx is non-zero).
  119372. **
  119373. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  119374. ** to the value of parameter iVal.
  119375. */
  119376. static void fts3PutDeltaVarint3(
  119377. char **pp, /* IN/OUT: Output pointer */
  119378. int bDescIdx, /* True for descending docids */
  119379. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  119380. int *pbFirst, /* IN/OUT: True after first int written */
  119381. sqlite3_int64 iVal /* Write this value to the list */
  119382. ){
  119383. sqlite3_int64 iWrite;
  119384. if( bDescIdx==0 || *pbFirst==0 ){
  119385. iWrite = iVal - *piPrev;
  119386. }else{
  119387. iWrite = *piPrev - iVal;
  119388. }
  119389. assert( *pbFirst || *piPrev==0 );
  119390. assert( *pbFirst==0 || iWrite>0 );
  119391. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  119392. *piPrev = iVal;
  119393. *pbFirst = 1;
  119394. }
  119395. /*
  119396. ** This macro is used by various functions that merge doclists. The two
  119397. ** arguments are 64-bit docid values. If the value of the stack variable
  119398. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  119399. ** Otherwise, (i2-i1).
  119400. **
  119401. ** Using this makes it easier to write code that can merge doclists that are
  119402. ** sorted in either ascending or descending order.
  119403. */
  119404. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  119405. /*
  119406. ** This function does an "OR" merge of two doclists (output contains all
  119407. ** positions contained in either argument doclist). If the docids in the
  119408. ** input doclists are sorted in ascending order, parameter bDescDoclist
  119409. ** should be false. If they are sorted in ascending order, it should be
  119410. ** passed a non-zero value.
  119411. **
  119412. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  119413. ** containing the output doclist and SQLITE_OK is returned. In this case
  119414. ** *pnOut is set to the number of bytes in the output doclist.
  119415. **
  119416. ** If an error occurs, an SQLite error code is returned. The output values
  119417. ** are undefined in this case.
  119418. */
  119419. static int fts3DoclistOrMerge(
  119420. int bDescDoclist, /* True if arguments are desc */
  119421. char *a1, int n1, /* First doclist */
  119422. char *a2, int n2, /* Second doclist */
  119423. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  119424. ){
  119425. sqlite3_int64 i1 = 0;
  119426. sqlite3_int64 i2 = 0;
  119427. sqlite3_int64 iPrev = 0;
  119428. char *pEnd1 = &a1[n1];
  119429. char *pEnd2 = &a2[n2];
  119430. char *p1 = a1;
  119431. char *p2 = a2;
  119432. char *p;
  119433. char *aOut;
  119434. int bFirstOut = 0;
  119435. *paOut = 0;
  119436. *pnOut = 0;
  119437. /* Allocate space for the output. Both the input and output doclists
  119438. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  119439. ** then the first docid in each list is simply encoded as a varint. For
  119440. ** each subsequent docid, the varint stored is the difference between the
  119441. ** current and previous docid (a positive number - since the list is in
  119442. ** ascending order).
  119443. **
  119444. ** The first docid written to the output is therefore encoded using the
  119445. ** same number of bytes as it is in whichever of the input lists it is
  119446. ** read from. And each subsequent docid read from the same input list
  119447. ** consumes either the same or less bytes as it did in the input (since
  119448. ** the difference between it and the previous value in the output must
  119449. ** be a positive value less than or equal to the delta value read from
  119450. ** the input list). The same argument applies to all but the first docid
  119451. ** read from the 'other' list. And to the contents of all position lists
  119452. ** that will be copied and merged from the input to the output.
  119453. **
  119454. ** However, if the first docid copied to the output is a negative number,
  119455. ** then the encoding of the first docid from the 'other' input list may
  119456. ** be larger in the output than it was in the input (since the delta value
  119457. ** may be a larger positive integer than the actual docid).
  119458. **
  119459. ** The space required to store the output is therefore the sum of the
  119460. ** sizes of the two inputs, plus enough space for exactly one of the input
  119461. ** docids to grow.
  119462. **
  119463. ** A symetric argument may be made if the doclists are in descending
  119464. ** order.
  119465. */
  119466. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  119467. if( !aOut ) return SQLITE_NOMEM;
  119468. p = aOut;
  119469. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  119470. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  119471. while( p1 || p2 ){
  119472. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  119473. if( p2 && p1 && iDiff==0 ){
  119474. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119475. fts3PoslistMerge(&p, &p1, &p2);
  119476. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119477. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119478. }else if( !p2 || (p1 && iDiff<0) ){
  119479. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119480. fts3PoslistCopy(&p, &p1);
  119481. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119482. }else{
  119483. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  119484. fts3PoslistCopy(&p, &p2);
  119485. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119486. }
  119487. }
  119488. *paOut = aOut;
  119489. *pnOut = (int)(p-aOut);
  119490. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  119491. return SQLITE_OK;
  119492. }
  119493. /*
  119494. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  119495. ** the output contains a copy of each position from the right-hand input
  119496. ** doclist for which there is a position in the left-hand input doclist
  119497. ** exactly nDist tokens before it.
  119498. **
  119499. ** If the docids in the input doclists are sorted in ascending order,
  119500. ** parameter bDescDoclist should be false. If they are sorted in ascending
  119501. ** order, it should be passed a non-zero value.
  119502. **
  119503. ** The right-hand input doclist is overwritten by this function.
  119504. */
  119505. static void fts3DoclistPhraseMerge(
  119506. int bDescDoclist, /* True if arguments are desc */
  119507. int nDist, /* Distance from left to right (1=adjacent) */
  119508. char *aLeft, int nLeft, /* Left doclist */
  119509. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  119510. ){
  119511. sqlite3_int64 i1 = 0;
  119512. sqlite3_int64 i2 = 0;
  119513. sqlite3_int64 iPrev = 0;
  119514. char *pEnd1 = &aLeft[nLeft];
  119515. char *pEnd2 = &aRight[*pnRight];
  119516. char *p1 = aLeft;
  119517. char *p2 = aRight;
  119518. char *p;
  119519. int bFirstOut = 0;
  119520. char *aOut = aRight;
  119521. assert( nDist>0 );
  119522. p = aOut;
  119523. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  119524. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  119525. while( p1 && p2 ){
  119526. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  119527. if( iDiff==0 ){
  119528. char *pSave = p;
  119529. sqlite3_int64 iPrevSave = iPrev;
  119530. int bFirstOutSave = bFirstOut;
  119531. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119532. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  119533. p = pSave;
  119534. iPrev = iPrevSave;
  119535. bFirstOut = bFirstOutSave;
  119536. }
  119537. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119538. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119539. }else if( iDiff<0 ){
  119540. fts3PoslistCopy(0, &p1);
  119541. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119542. }else{
  119543. fts3PoslistCopy(0, &p2);
  119544. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119545. }
  119546. }
  119547. *pnRight = (int)(p - aOut);
  119548. }
  119549. /*
  119550. ** Argument pList points to a position list nList bytes in size. This
  119551. ** function checks to see if the position list contains any entries for
  119552. ** a token in position 0 (of any column). If so, it writes argument iDelta
  119553. ** to the output buffer pOut, followed by a position list consisting only
  119554. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  119555. ** The value returned is the number of bytes written to pOut (if any).
  119556. */
  119557. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  119558. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  119559. char *pList, /* Position list (no 0x00 term) */
  119560. int nList, /* Size of pList in bytes */
  119561. char *pOut /* Write output here */
  119562. ){
  119563. int nOut = 0;
  119564. int bWritten = 0; /* True once iDelta has been written */
  119565. char *p = pList;
  119566. char *pEnd = &pList[nList];
  119567. if( *p!=0x01 ){
  119568. if( *p==0x02 ){
  119569. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  119570. pOut[nOut++] = 0x02;
  119571. bWritten = 1;
  119572. }
  119573. fts3ColumnlistCopy(0, &p);
  119574. }
  119575. while( p<pEnd && *p==0x01 ){
  119576. sqlite3_int64 iCol;
  119577. p++;
  119578. p += sqlite3Fts3GetVarint(p, &iCol);
  119579. if( *p==0x02 ){
  119580. if( bWritten==0 ){
  119581. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  119582. bWritten = 1;
  119583. }
  119584. pOut[nOut++] = 0x01;
  119585. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  119586. pOut[nOut++] = 0x02;
  119587. }
  119588. fts3ColumnlistCopy(0, &p);
  119589. }
  119590. if( bWritten ){
  119591. pOut[nOut++] = 0x00;
  119592. }
  119593. return nOut;
  119594. }
  119595. /*
  119596. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  119597. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  119598. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  119599. **
  119600. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  119601. ** the responsibility of the caller to free any doclists left in the
  119602. ** TermSelect.aaOutput[] array.
  119603. */
  119604. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  119605. char *aOut = 0;
  119606. int nOut = 0;
  119607. int i;
  119608. /* Loop through the doclists in the aaOutput[] array. Merge them all
  119609. ** into a single doclist.
  119610. */
  119611. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  119612. if( pTS->aaOutput[i] ){
  119613. if( !aOut ){
  119614. aOut = pTS->aaOutput[i];
  119615. nOut = pTS->anOutput[i];
  119616. pTS->aaOutput[i] = 0;
  119617. }else{
  119618. int nNew;
  119619. char *aNew;
  119620. int rc = fts3DoclistOrMerge(p->bDescIdx,
  119621. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  119622. );
  119623. if( rc!=SQLITE_OK ){
  119624. sqlite3_free(aOut);
  119625. return rc;
  119626. }
  119627. sqlite3_free(pTS->aaOutput[i]);
  119628. sqlite3_free(aOut);
  119629. pTS->aaOutput[i] = 0;
  119630. aOut = aNew;
  119631. nOut = nNew;
  119632. }
  119633. }
  119634. }
  119635. pTS->aaOutput[0] = aOut;
  119636. pTS->anOutput[0] = nOut;
  119637. return SQLITE_OK;
  119638. }
  119639. /*
  119640. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  119641. ** as the first argument. The merge is an "OR" merge (see function
  119642. ** fts3DoclistOrMerge() for details).
  119643. **
  119644. ** This function is called with the doclist for each term that matches
  119645. ** a queried prefix. It merges all these doclists into one, the doclist
  119646. ** for the specified prefix. Since there can be a very large number of
  119647. ** doclists to merge, the merging is done pair-wise using the TermSelect
  119648. ** object.
  119649. **
  119650. ** This function returns SQLITE_OK if the merge is successful, or an
  119651. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  119652. */
  119653. static int fts3TermSelectMerge(
  119654. Fts3Table *p, /* FTS table handle */
  119655. TermSelect *pTS, /* TermSelect object to merge into */
  119656. char *aDoclist, /* Pointer to doclist */
  119657. int nDoclist /* Size of aDoclist in bytes */
  119658. ){
  119659. if( pTS->aaOutput[0]==0 ){
  119660. /* If this is the first term selected, copy the doclist to the output
  119661. ** buffer using memcpy(). */
  119662. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  119663. pTS->anOutput[0] = nDoclist;
  119664. if( pTS->aaOutput[0] ){
  119665. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  119666. }else{
  119667. return SQLITE_NOMEM;
  119668. }
  119669. }else{
  119670. char *aMerge = aDoclist;
  119671. int nMerge = nDoclist;
  119672. int iOut;
  119673. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  119674. if( pTS->aaOutput[iOut]==0 ){
  119675. assert( iOut>0 );
  119676. pTS->aaOutput[iOut] = aMerge;
  119677. pTS->anOutput[iOut] = nMerge;
  119678. break;
  119679. }else{
  119680. char *aNew;
  119681. int nNew;
  119682. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  119683. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  119684. );
  119685. if( rc!=SQLITE_OK ){
  119686. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  119687. return rc;
  119688. }
  119689. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  119690. sqlite3_free(pTS->aaOutput[iOut]);
  119691. pTS->aaOutput[iOut] = 0;
  119692. aMerge = aNew;
  119693. nMerge = nNew;
  119694. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  119695. pTS->aaOutput[iOut] = aMerge;
  119696. pTS->anOutput[iOut] = nMerge;
  119697. }
  119698. }
  119699. }
  119700. }
  119701. return SQLITE_OK;
  119702. }
  119703. /*
  119704. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  119705. */
  119706. static int fts3SegReaderCursorAppend(
  119707. Fts3MultiSegReader *pCsr,
  119708. Fts3SegReader *pNew
  119709. ){
  119710. if( (pCsr->nSegment%16)==0 ){
  119711. Fts3SegReader **apNew;
  119712. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  119713. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  119714. if( !apNew ){
  119715. sqlite3Fts3SegReaderFree(pNew);
  119716. return SQLITE_NOMEM;
  119717. }
  119718. pCsr->apSegment = apNew;
  119719. }
  119720. pCsr->apSegment[pCsr->nSegment++] = pNew;
  119721. return SQLITE_OK;
  119722. }
  119723. /*
  119724. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  119725. ** 8th argument.
  119726. **
  119727. ** This function returns SQLITE_OK if successful, or an SQLite error code
  119728. ** otherwise.
  119729. */
  119730. static int fts3SegReaderCursor(
  119731. Fts3Table *p, /* FTS3 table handle */
  119732. int iLangid, /* Language id */
  119733. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  119734. int iLevel, /* Level of segments to scan */
  119735. const char *zTerm, /* Term to query for */
  119736. int nTerm, /* Size of zTerm in bytes */
  119737. int isPrefix, /* True for a prefix search */
  119738. int isScan, /* True to scan from zTerm to EOF */
  119739. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  119740. ){
  119741. int rc = SQLITE_OK; /* Error code */
  119742. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  119743. int rc2; /* Result of sqlite3_reset() */
  119744. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  119745. ** for the pending-terms. If this is a scan, then this call must be being
  119746. ** made by an fts4aux module, not an FTS table. In this case calling
  119747. ** Fts3SegReaderPending might segfault, as the data structures used by
  119748. ** fts4aux are not completely populated. So it's easiest to filter these
  119749. ** calls out here. */
  119750. if( iLevel<0 && p->aIndex ){
  119751. Fts3SegReader *pSeg = 0;
  119752. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  119753. if( rc==SQLITE_OK && pSeg ){
  119754. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  119755. }
  119756. }
  119757. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  119758. if( rc==SQLITE_OK ){
  119759. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  119760. }
  119761. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  119762. Fts3SegReader *pSeg = 0;
  119763. /* Read the values returned by the SELECT into local variables. */
  119764. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  119765. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  119766. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  119767. int nRoot = sqlite3_column_bytes(pStmt, 4);
  119768. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  119769. /* If zTerm is not NULL, and this segment is not stored entirely on its
  119770. ** root node, the range of leaves scanned can be reduced. Do this. */
  119771. if( iStartBlock && zTerm ){
  119772. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  119773. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  119774. if( rc!=SQLITE_OK ) goto finished;
  119775. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  119776. }
  119777. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  119778. (isPrefix==0 && isScan==0),
  119779. iStartBlock, iLeavesEndBlock,
  119780. iEndBlock, zRoot, nRoot, &pSeg
  119781. );
  119782. if( rc!=SQLITE_OK ) goto finished;
  119783. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  119784. }
  119785. }
  119786. finished:
  119787. rc2 = sqlite3_reset(pStmt);
  119788. if( rc==SQLITE_DONE ) rc = rc2;
  119789. return rc;
  119790. }
  119791. /*
  119792. ** Set up a cursor object for iterating through a full-text index or a
  119793. ** single level therein.
  119794. */
  119795. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  119796. Fts3Table *p, /* FTS3 table handle */
  119797. int iLangid, /* Language-id to search */
  119798. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  119799. int iLevel, /* Level of segments to scan */
  119800. const char *zTerm, /* Term to query for */
  119801. int nTerm, /* Size of zTerm in bytes */
  119802. int isPrefix, /* True for a prefix search */
  119803. int isScan, /* True to scan from zTerm to EOF */
  119804. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  119805. ){
  119806. assert( iIndex>=0 && iIndex<p->nIndex );
  119807. assert( iLevel==FTS3_SEGCURSOR_ALL
  119808. || iLevel==FTS3_SEGCURSOR_PENDING
  119809. || iLevel>=0
  119810. );
  119811. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  119812. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  119813. assert( isPrefix==0 || isScan==0 );
  119814. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  119815. return fts3SegReaderCursor(
  119816. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  119817. );
  119818. }
  119819. /*
  119820. ** In addition to its current configuration, have the Fts3MultiSegReader
  119821. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  119822. **
  119823. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  119824. */
  119825. static int fts3SegReaderCursorAddZero(
  119826. Fts3Table *p, /* FTS virtual table handle */
  119827. int iLangid,
  119828. const char *zTerm, /* Term to scan doclist of */
  119829. int nTerm, /* Number of bytes in zTerm */
  119830. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  119831. ){
  119832. return fts3SegReaderCursor(p,
  119833. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  119834. );
  119835. }
  119836. /*
  119837. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  119838. ** if isPrefix is true, to scan the doclist for all terms for which
  119839. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  119840. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  119841. ** an SQLite error code.
  119842. **
  119843. ** It is the responsibility of the caller to free this object by eventually
  119844. ** passing it to fts3SegReaderCursorFree()
  119845. **
  119846. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  119847. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  119848. */
  119849. static int fts3TermSegReaderCursor(
  119850. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  119851. const char *zTerm, /* Term to query for */
  119852. int nTerm, /* Size of zTerm in bytes */
  119853. int isPrefix, /* True for a prefix search */
  119854. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  119855. ){
  119856. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  119857. int rc = SQLITE_NOMEM; /* Return code */
  119858. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  119859. if( pSegcsr ){
  119860. int i;
  119861. int bFound = 0; /* True once an index has been found */
  119862. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  119863. if( isPrefix ){
  119864. for(i=1; bFound==0 && i<p->nIndex; i++){
  119865. if( p->aIndex[i].nPrefix==nTerm ){
  119866. bFound = 1;
  119867. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119868. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  119869. );
  119870. pSegcsr->bLookup = 1;
  119871. }
  119872. }
  119873. for(i=1; bFound==0 && i<p->nIndex; i++){
  119874. if( p->aIndex[i].nPrefix==nTerm+1 ){
  119875. bFound = 1;
  119876. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119877. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  119878. );
  119879. if( rc==SQLITE_OK ){
  119880. rc = fts3SegReaderCursorAddZero(
  119881. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  119882. );
  119883. }
  119884. }
  119885. }
  119886. }
  119887. if( bFound==0 ){
  119888. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119889. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  119890. );
  119891. pSegcsr->bLookup = !isPrefix;
  119892. }
  119893. }
  119894. *ppSegcsr = pSegcsr;
  119895. return rc;
  119896. }
  119897. /*
  119898. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  119899. */
  119900. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  119901. sqlite3Fts3SegReaderFinish(pSegcsr);
  119902. sqlite3_free(pSegcsr);
  119903. }
  119904. /*
  119905. ** This function retrieves the doclist for the specified term (or term
  119906. ** prefix) from the database.
  119907. */
  119908. static int fts3TermSelect(
  119909. Fts3Table *p, /* Virtual table handle */
  119910. Fts3PhraseToken *pTok, /* Token to query for */
  119911. int iColumn, /* Column to query (or -ve for all columns) */
  119912. int *pnOut, /* OUT: Size of buffer at *ppOut */
  119913. char **ppOut /* OUT: Malloced result buffer */
  119914. ){
  119915. int rc; /* Return code */
  119916. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  119917. TermSelect tsc; /* Object for pair-wise doclist merging */
  119918. Fts3SegFilter filter; /* Segment term filter configuration */
  119919. pSegcsr = pTok->pSegcsr;
  119920. memset(&tsc, 0, sizeof(TermSelect));
  119921. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  119922. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  119923. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  119924. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  119925. filter.iCol = iColumn;
  119926. filter.zTerm = pTok->z;
  119927. filter.nTerm = pTok->n;
  119928. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  119929. while( SQLITE_OK==rc
  119930. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  119931. ){
  119932. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  119933. }
  119934. if( rc==SQLITE_OK ){
  119935. rc = fts3TermSelectFinishMerge(p, &tsc);
  119936. }
  119937. if( rc==SQLITE_OK ){
  119938. *ppOut = tsc.aaOutput[0];
  119939. *pnOut = tsc.anOutput[0];
  119940. }else{
  119941. int i;
  119942. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  119943. sqlite3_free(tsc.aaOutput[i]);
  119944. }
  119945. }
  119946. fts3SegReaderCursorFree(pSegcsr);
  119947. pTok->pSegcsr = 0;
  119948. return rc;
  119949. }
  119950. /*
  119951. ** This function counts the total number of docids in the doclist stored
  119952. ** in buffer aList[], size nList bytes.
  119953. **
  119954. ** If the isPoslist argument is true, then it is assumed that the doclist
  119955. ** contains a position-list following each docid. Otherwise, it is assumed
  119956. ** that the doclist is simply a list of docids stored as delta encoded
  119957. ** varints.
  119958. */
  119959. static int fts3DoclistCountDocids(char *aList, int nList){
  119960. int nDoc = 0; /* Return value */
  119961. if( aList ){
  119962. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  119963. char *p = aList; /* Cursor */
  119964. while( p<aEnd ){
  119965. nDoc++;
  119966. while( (*p++)&0x80 ); /* Skip docid varint */
  119967. fts3PoslistCopy(0, &p); /* Skip over position list */
  119968. }
  119969. }
  119970. return nDoc;
  119971. }
  119972. /*
  119973. ** Advance the cursor to the next row in the %_content table that
  119974. ** matches the search criteria. For a MATCH search, this will be
  119975. ** the next row that matches. For a full-table scan, this will be
  119976. ** simply the next row in the %_content table. For a docid lookup,
  119977. ** this routine simply sets the EOF flag.
  119978. **
  119979. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  119980. ** even if we reach end-of-file. The fts3EofMethod() will be called
  119981. ** subsequently to determine whether or not an EOF was hit.
  119982. */
  119983. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  119984. int rc;
  119985. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  119986. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  119987. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  119988. pCsr->isEof = 1;
  119989. rc = sqlite3_reset(pCsr->pStmt);
  119990. }else{
  119991. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  119992. rc = SQLITE_OK;
  119993. }
  119994. }else{
  119995. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  119996. }
  119997. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  119998. return rc;
  119999. }
  120000. /*
  120001. ** The following are copied from sqliteInt.h.
  120002. **
  120003. ** Constants for the largest and smallest possible 64-bit signed integers.
  120004. ** These macros are designed to work correctly on both 32-bit and 64-bit
  120005. ** compilers.
  120006. */
  120007. #ifndef SQLITE_AMALGAMATION
  120008. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  120009. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  120010. #endif
  120011. /*
  120012. ** If the numeric type of argument pVal is "integer", then return it
  120013. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  120014. ** the second parameter, iDefault.
  120015. */
  120016. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  120017. if( pVal ){
  120018. int eType = sqlite3_value_numeric_type(pVal);
  120019. if( eType==SQLITE_INTEGER ){
  120020. return sqlite3_value_int64(pVal);
  120021. }
  120022. }
  120023. return iDefault;
  120024. }
  120025. /*
  120026. ** This is the xFilter interface for the virtual table. See
  120027. ** the virtual table xFilter method documentation for additional
  120028. ** information.
  120029. **
  120030. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  120031. ** the %_content table.
  120032. **
  120033. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  120034. ** in the %_content table.
  120035. **
  120036. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  120037. ** column on the left-hand side of the MATCH operator is column
  120038. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  120039. ** side of the MATCH operator.
  120040. */
  120041. static int fts3FilterMethod(
  120042. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  120043. int idxNum, /* Strategy index */
  120044. const char *idxStr, /* Unused */
  120045. int nVal, /* Number of elements in apVal */
  120046. sqlite3_value **apVal /* Arguments for the indexing scheme */
  120047. ){
  120048. int rc;
  120049. char *zSql; /* SQL statement used to access %_content */
  120050. int eSearch;
  120051. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  120052. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  120053. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  120054. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  120055. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  120056. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  120057. int iIdx;
  120058. UNUSED_PARAMETER(idxStr);
  120059. UNUSED_PARAMETER(nVal);
  120060. eSearch = (idxNum & 0x0000FFFF);
  120061. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  120062. assert( p->pSegments==0 );
  120063. /* Collect arguments into local variables */
  120064. iIdx = 0;
  120065. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  120066. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  120067. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  120068. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  120069. assert( iIdx==nVal );
  120070. /* In case the cursor has been used before, clear it now. */
  120071. sqlite3_finalize(pCsr->pStmt);
  120072. sqlite3_free(pCsr->aDoclist);
  120073. sqlite3Fts3ExprFree(pCsr->pExpr);
  120074. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  120075. /* Set the lower and upper bounds on docids to return */
  120076. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  120077. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  120078. if( idxStr ){
  120079. pCsr->bDesc = (idxStr[0]=='D');
  120080. }else{
  120081. pCsr->bDesc = p->bDescIdx;
  120082. }
  120083. pCsr->eSearch = (i16)eSearch;
  120084. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  120085. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  120086. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  120087. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  120088. return SQLITE_NOMEM;
  120089. }
  120090. pCsr->iLangid = 0;
  120091. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  120092. assert( p->base.zErrMsg==0 );
  120093. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  120094. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  120095. &p->base.zErrMsg
  120096. );
  120097. if( rc!=SQLITE_OK ){
  120098. return rc;
  120099. }
  120100. rc = fts3EvalStart(pCsr);
  120101. sqlite3Fts3SegmentsClose(p);
  120102. if( rc!=SQLITE_OK ) return rc;
  120103. pCsr->pNextId = pCsr->aDoclist;
  120104. pCsr->iPrevId = 0;
  120105. }
  120106. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  120107. ** statement loops through all rows of the %_content table. For a
  120108. ** full-text query or docid lookup, the statement retrieves a single
  120109. ** row by docid.
  120110. */
  120111. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  120112. zSql = sqlite3_mprintf(
  120113. "SELECT %s ORDER BY rowid %s",
  120114. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  120115. );
  120116. if( zSql ){
  120117. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  120118. sqlite3_free(zSql);
  120119. }else{
  120120. rc = SQLITE_NOMEM;
  120121. }
  120122. }else if( eSearch==FTS3_DOCID_SEARCH ){
  120123. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  120124. if( rc==SQLITE_OK ){
  120125. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  120126. }
  120127. }
  120128. if( rc!=SQLITE_OK ) return rc;
  120129. return fts3NextMethod(pCursor);
  120130. }
  120131. /*
  120132. ** This is the xEof method of the virtual table. SQLite calls this
  120133. ** routine to find out if it has reached the end of a result set.
  120134. */
  120135. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  120136. return ((Fts3Cursor *)pCursor)->isEof;
  120137. }
  120138. /*
  120139. ** This is the xRowid method. The SQLite core calls this routine to
  120140. ** retrieve the rowid for the current row of the result set. fts3
  120141. ** exposes %_content.docid as the rowid for the virtual table. The
  120142. ** rowid should be written to *pRowid.
  120143. */
  120144. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  120145. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  120146. *pRowid = pCsr->iPrevId;
  120147. return SQLITE_OK;
  120148. }
  120149. /*
  120150. ** This is the xColumn method, called by SQLite to request a value from
  120151. ** the row that the supplied cursor currently points to.
  120152. **
  120153. ** If:
  120154. **
  120155. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  120156. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  120157. ** (iCol == p->nColumn+1) -> Docid column
  120158. ** (iCol == p->nColumn+2) -> Langid column
  120159. */
  120160. static int fts3ColumnMethod(
  120161. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  120162. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  120163. int iCol /* Index of column to read value from */
  120164. ){
  120165. int rc = SQLITE_OK; /* Return Code */
  120166. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  120167. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  120168. /* The column value supplied by SQLite must be in range. */
  120169. assert( iCol>=0 && iCol<=p->nColumn+2 );
  120170. if( iCol==p->nColumn+1 ){
  120171. /* This call is a request for the "docid" column. Since "docid" is an
  120172. ** alias for "rowid", use the xRowid() method to obtain the value.
  120173. */
  120174. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  120175. }else if( iCol==p->nColumn ){
  120176. /* The extra column whose name is the same as the table.
  120177. ** Return a blob which is a pointer to the cursor. */
  120178. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  120179. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  120180. sqlite3_result_int64(pCtx, pCsr->iLangid);
  120181. }else{
  120182. /* The requested column is either a user column (one that contains
  120183. ** indexed data), or the language-id column. */
  120184. rc = fts3CursorSeek(0, pCsr);
  120185. if( rc==SQLITE_OK ){
  120186. if( iCol==p->nColumn+2 ){
  120187. int iLangid = 0;
  120188. if( p->zLanguageid ){
  120189. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  120190. }
  120191. sqlite3_result_int(pCtx, iLangid);
  120192. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  120193. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  120194. }
  120195. }
  120196. }
  120197. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  120198. return rc;
  120199. }
  120200. /*
  120201. ** This function is the implementation of the xUpdate callback used by
  120202. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  120203. ** inserted, updated or deleted.
  120204. */
  120205. static int fts3UpdateMethod(
  120206. sqlite3_vtab *pVtab, /* Virtual table handle */
  120207. int nArg, /* Size of argument array */
  120208. sqlite3_value **apVal, /* Array of arguments */
  120209. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  120210. ){
  120211. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  120212. }
  120213. /*
  120214. ** Implementation of xSync() method. Flush the contents of the pending-terms
  120215. ** hash-table to the database.
  120216. */
  120217. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  120218. /* Following an incremental-merge operation, assuming that the input
  120219. ** segments are not completely consumed (the usual case), they are updated
  120220. ** in place to remove the entries that have already been merged. This
  120221. ** involves updating the leaf block that contains the smallest unmerged
  120222. ** entry and each block (if any) between the leaf and the root node. So
  120223. ** if the height of the input segment b-trees is N, and input segments
  120224. ** are merged eight at a time, updating the input segments at the end
  120225. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  120226. ** small - often between 0 and 2. So the overhead of the incremental
  120227. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  120228. ** dwarfing the actual productive work accomplished, the incremental merge
  120229. ** is only attempted if it will write at least 64 leaf blocks. Hence
  120230. ** nMinMerge.
  120231. **
  120232. ** Of course, updating the input segments also involves deleting a bunch
  120233. ** of blocks from the segments table. But this is not considered overhead
  120234. ** as it would also be required by a crisis-merge that used the same input
  120235. ** segments.
  120236. */
  120237. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  120238. Fts3Table *p = (Fts3Table*)pVtab;
  120239. int rc = sqlite3Fts3PendingTermsFlush(p);
  120240. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  120241. int mxLevel = 0; /* Maximum relative level value in db */
  120242. int A; /* Incr-merge parameter A */
  120243. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  120244. assert( rc==SQLITE_OK || mxLevel==0 );
  120245. A = p->nLeafAdd * mxLevel;
  120246. A += (A/2);
  120247. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  120248. }
  120249. sqlite3Fts3SegmentsClose(p);
  120250. return rc;
  120251. }
  120252. /*
  120253. ** Implementation of xBegin() method. This is a no-op.
  120254. */
  120255. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  120256. Fts3Table *p = (Fts3Table*)pVtab;
  120257. UNUSED_PARAMETER(pVtab);
  120258. assert( p->pSegments==0 );
  120259. assert( p->nPendingData==0 );
  120260. assert( p->inTransaction!=1 );
  120261. TESTONLY( p->inTransaction = 1 );
  120262. TESTONLY( p->mxSavepoint = -1; );
  120263. p->nLeafAdd = 0;
  120264. return SQLITE_OK;
  120265. }
  120266. /*
  120267. ** Implementation of xCommit() method. This is a no-op. The contents of
  120268. ** the pending-terms hash-table have already been flushed into the database
  120269. ** by fts3SyncMethod().
  120270. */
  120271. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  120272. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  120273. UNUSED_PARAMETER(pVtab);
  120274. assert( p->nPendingData==0 );
  120275. assert( p->inTransaction!=0 );
  120276. assert( p->pSegments==0 );
  120277. TESTONLY( p->inTransaction = 0 );
  120278. TESTONLY( p->mxSavepoint = -1; );
  120279. return SQLITE_OK;
  120280. }
  120281. /*
  120282. ** Implementation of xRollback(). Discard the contents of the pending-terms
  120283. ** hash-table. Any changes made to the database are reverted by SQLite.
  120284. */
  120285. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  120286. Fts3Table *p = (Fts3Table*)pVtab;
  120287. sqlite3Fts3PendingTermsClear(p);
  120288. assert( p->inTransaction!=0 );
  120289. TESTONLY( p->inTransaction = 0 );
  120290. TESTONLY( p->mxSavepoint = -1; );
  120291. return SQLITE_OK;
  120292. }
  120293. /*
  120294. ** When called, *ppPoslist must point to the byte immediately following the
  120295. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  120296. ** moves *ppPoslist so that it instead points to the first byte of the
  120297. ** same position list.
  120298. */
  120299. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  120300. char *p = &(*ppPoslist)[-2];
  120301. char c = 0;
  120302. while( p>pStart && (c=*p--)==0 );
  120303. while( p>pStart && (*p & 0x80) | c ){
  120304. c = *p--;
  120305. }
  120306. if( p>pStart ){ p = &p[2]; }
  120307. while( *p++&0x80 );
  120308. *ppPoslist = p;
  120309. }
  120310. /*
  120311. ** Helper function used by the implementation of the overloaded snippet(),
  120312. ** offsets() and optimize() SQL functions.
  120313. **
  120314. ** If the value passed as the third argument is a blob of size
  120315. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  120316. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  120317. ** message is written to context pContext and SQLITE_ERROR returned. The
  120318. ** string passed via zFunc is used as part of the error message.
  120319. */
  120320. static int fts3FunctionArg(
  120321. sqlite3_context *pContext, /* SQL function call context */
  120322. const char *zFunc, /* Function name */
  120323. sqlite3_value *pVal, /* argv[0] passed to function */
  120324. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  120325. ){
  120326. Fts3Cursor *pRet;
  120327. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  120328. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  120329. ){
  120330. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  120331. sqlite3_result_error(pContext, zErr, -1);
  120332. sqlite3_free(zErr);
  120333. return SQLITE_ERROR;
  120334. }
  120335. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  120336. *ppCsr = pRet;
  120337. return SQLITE_OK;
  120338. }
  120339. /*
  120340. ** Implementation of the snippet() function for FTS3
  120341. */
  120342. static void fts3SnippetFunc(
  120343. sqlite3_context *pContext, /* SQLite function call context */
  120344. int nVal, /* Size of apVal[] array */
  120345. sqlite3_value **apVal /* Array of arguments */
  120346. ){
  120347. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120348. const char *zStart = "<b>";
  120349. const char *zEnd = "</b>";
  120350. const char *zEllipsis = "<b>...</b>";
  120351. int iCol = -1;
  120352. int nToken = 15; /* Default number of tokens in snippet */
  120353. /* There must be at least one argument passed to this function (otherwise
  120354. ** the non-overloaded version would have been called instead of this one).
  120355. */
  120356. assert( nVal>=1 );
  120357. if( nVal>6 ){
  120358. sqlite3_result_error(pContext,
  120359. "wrong number of arguments to function snippet()", -1);
  120360. return;
  120361. }
  120362. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  120363. switch( nVal ){
  120364. case 6: nToken = sqlite3_value_int(apVal[5]);
  120365. case 5: iCol = sqlite3_value_int(apVal[4]);
  120366. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  120367. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  120368. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  120369. }
  120370. if( !zEllipsis || !zEnd || !zStart ){
  120371. sqlite3_result_error_nomem(pContext);
  120372. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  120373. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  120374. }
  120375. }
  120376. /*
  120377. ** Implementation of the offsets() function for FTS3
  120378. */
  120379. static void fts3OffsetsFunc(
  120380. sqlite3_context *pContext, /* SQLite function call context */
  120381. int nVal, /* Size of argument array */
  120382. sqlite3_value **apVal /* Array of arguments */
  120383. ){
  120384. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120385. UNUSED_PARAMETER(nVal);
  120386. assert( nVal==1 );
  120387. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  120388. assert( pCsr );
  120389. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  120390. sqlite3Fts3Offsets(pContext, pCsr);
  120391. }
  120392. }
  120393. /*
  120394. ** Implementation of the special optimize() function for FTS3. This
  120395. ** function merges all segments in the database to a single segment.
  120396. ** Example usage is:
  120397. **
  120398. ** SELECT optimize(t) FROM t LIMIT 1;
  120399. **
  120400. ** where 't' is the name of an FTS3 table.
  120401. */
  120402. static void fts3OptimizeFunc(
  120403. sqlite3_context *pContext, /* SQLite function call context */
  120404. int nVal, /* Size of argument array */
  120405. sqlite3_value **apVal /* Array of arguments */
  120406. ){
  120407. int rc; /* Return code */
  120408. Fts3Table *p; /* Virtual table handle */
  120409. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  120410. UNUSED_PARAMETER(nVal);
  120411. assert( nVal==1 );
  120412. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  120413. p = (Fts3Table *)pCursor->base.pVtab;
  120414. assert( p );
  120415. rc = sqlite3Fts3Optimize(p);
  120416. switch( rc ){
  120417. case SQLITE_OK:
  120418. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  120419. break;
  120420. case SQLITE_DONE:
  120421. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  120422. break;
  120423. default:
  120424. sqlite3_result_error_code(pContext, rc);
  120425. break;
  120426. }
  120427. }
  120428. /*
  120429. ** Implementation of the matchinfo() function for FTS3
  120430. */
  120431. static void fts3MatchinfoFunc(
  120432. sqlite3_context *pContext, /* SQLite function call context */
  120433. int nVal, /* Size of argument array */
  120434. sqlite3_value **apVal /* Array of arguments */
  120435. ){
  120436. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120437. assert( nVal==1 || nVal==2 );
  120438. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  120439. const char *zArg = 0;
  120440. if( nVal>1 ){
  120441. zArg = (const char *)sqlite3_value_text(apVal[1]);
  120442. }
  120443. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  120444. }
  120445. }
  120446. /*
  120447. ** This routine implements the xFindFunction method for the FTS3
  120448. ** virtual table.
  120449. */
  120450. static int fts3FindFunctionMethod(
  120451. sqlite3_vtab *pVtab, /* Virtual table handle */
  120452. int nArg, /* Number of SQL function arguments */
  120453. const char *zName, /* Name of SQL function */
  120454. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  120455. void **ppArg /* Unused */
  120456. ){
  120457. struct Overloaded {
  120458. const char *zName;
  120459. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  120460. } aOverload[] = {
  120461. { "snippet", fts3SnippetFunc },
  120462. { "offsets", fts3OffsetsFunc },
  120463. { "optimize", fts3OptimizeFunc },
  120464. { "matchinfo", fts3MatchinfoFunc },
  120465. };
  120466. int i; /* Iterator variable */
  120467. UNUSED_PARAMETER(pVtab);
  120468. UNUSED_PARAMETER(nArg);
  120469. UNUSED_PARAMETER(ppArg);
  120470. for(i=0; i<SizeofArray(aOverload); i++){
  120471. if( strcmp(zName, aOverload[i].zName)==0 ){
  120472. *pxFunc = aOverload[i].xFunc;
  120473. return 1;
  120474. }
  120475. }
  120476. /* No function of the specified name was found. Return 0. */
  120477. return 0;
  120478. }
  120479. /*
  120480. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  120481. */
  120482. static int fts3RenameMethod(
  120483. sqlite3_vtab *pVtab, /* Virtual table handle */
  120484. const char *zName /* New name of table */
  120485. ){
  120486. Fts3Table *p = (Fts3Table *)pVtab;
  120487. sqlite3 *db = p->db; /* Database connection */
  120488. int rc; /* Return Code */
  120489. /* As it happens, the pending terms table is always empty here. This is
  120490. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  120491. ** always opens a savepoint transaction. And the xSavepoint() method
  120492. ** flushes the pending terms table. But leave the (no-op) call to
  120493. ** PendingTermsFlush() in in case that changes.
  120494. */
  120495. assert( p->nPendingData==0 );
  120496. rc = sqlite3Fts3PendingTermsFlush(p);
  120497. if( p->zContentTbl==0 ){
  120498. fts3DbExec(&rc, db,
  120499. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  120500. p->zDb, p->zName, zName
  120501. );
  120502. }
  120503. if( p->bHasDocsize ){
  120504. fts3DbExec(&rc, db,
  120505. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  120506. p->zDb, p->zName, zName
  120507. );
  120508. }
  120509. if( p->bHasStat ){
  120510. fts3DbExec(&rc, db,
  120511. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  120512. p->zDb, p->zName, zName
  120513. );
  120514. }
  120515. fts3DbExec(&rc, db,
  120516. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  120517. p->zDb, p->zName, zName
  120518. );
  120519. fts3DbExec(&rc, db,
  120520. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  120521. p->zDb, p->zName, zName
  120522. );
  120523. return rc;
  120524. }
  120525. /*
  120526. ** The xSavepoint() method.
  120527. **
  120528. ** Flush the contents of the pending-terms table to disk.
  120529. */
  120530. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120531. int rc = SQLITE_OK;
  120532. UNUSED_PARAMETER(iSavepoint);
  120533. assert( ((Fts3Table *)pVtab)->inTransaction );
  120534. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  120535. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  120536. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  120537. rc = fts3SyncMethod(pVtab);
  120538. }
  120539. return rc;
  120540. }
  120541. /*
  120542. ** The xRelease() method.
  120543. **
  120544. ** This is a no-op.
  120545. */
  120546. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120547. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  120548. UNUSED_PARAMETER(iSavepoint);
  120549. UNUSED_PARAMETER(pVtab);
  120550. assert( p->inTransaction );
  120551. assert( p->mxSavepoint >= iSavepoint );
  120552. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  120553. return SQLITE_OK;
  120554. }
  120555. /*
  120556. ** The xRollbackTo() method.
  120557. **
  120558. ** Discard the contents of the pending terms table.
  120559. */
  120560. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120561. Fts3Table *p = (Fts3Table*)pVtab;
  120562. UNUSED_PARAMETER(iSavepoint);
  120563. assert( p->inTransaction );
  120564. assert( p->mxSavepoint >= iSavepoint );
  120565. TESTONLY( p->mxSavepoint = iSavepoint );
  120566. sqlite3Fts3PendingTermsClear(p);
  120567. return SQLITE_OK;
  120568. }
  120569. static const sqlite3_module fts3Module = {
  120570. /* iVersion */ 2,
  120571. /* xCreate */ fts3CreateMethod,
  120572. /* xConnect */ fts3ConnectMethod,
  120573. /* xBestIndex */ fts3BestIndexMethod,
  120574. /* xDisconnect */ fts3DisconnectMethod,
  120575. /* xDestroy */ fts3DestroyMethod,
  120576. /* xOpen */ fts3OpenMethod,
  120577. /* xClose */ fts3CloseMethod,
  120578. /* xFilter */ fts3FilterMethod,
  120579. /* xNext */ fts3NextMethod,
  120580. /* xEof */ fts3EofMethod,
  120581. /* xColumn */ fts3ColumnMethod,
  120582. /* xRowid */ fts3RowidMethod,
  120583. /* xUpdate */ fts3UpdateMethod,
  120584. /* xBegin */ fts3BeginMethod,
  120585. /* xSync */ fts3SyncMethod,
  120586. /* xCommit */ fts3CommitMethod,
  120587. /* xRollback */ fts3RollbackMethod,
  120588. /* xFindFunction */ fts3FindFunctionMethod,
  120589. /* xRename */ fts3RenameMethod,
  120590. /* xSavepoint */ fts3SavepointMethod,
  120591. /* xRelease */ fts3ReleaseMethod,
  120592. /* xRollbackTo */ fts3RollbackToMethod,
  120593. };
  120594. /*
  120595. ** This function is registered as the module destructor (called when an
  120596. ** FTS3 enabled database connection is closed). It frees the memory
  120597. ** allocated for the tokenizer hash table.
  120598. */
  120599. static void hashDestroy(void *p){
  120600. Fts3Hash *pHash = (Fts3Hash *)p;
  120601. sqlite3Fts3HashClear(pHash);
  120602. sqlite3_free(pHash);
  120603. }
  120604. /*
  120605. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  120606. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  120607. ** respectively. The following three forward declarations are for functions
  120608. ** declared in these files used to retrieve the respective implementations.
  120609. **
  120610. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  120611. ** to by the argument to point to the "simple" tokenizer implementation.
  120612. ** And so on.
  120613. */
  120614. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120615. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120616. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120617. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  120618. #endif
  120619. #ifdef SQLITE_ENABLE_ICU
  120620. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120621. #endif
  120622. /*
  120623. ** Initialize the fts3 extension. If this extension is built as part
  120624. ** of the sqlite library, then this function is called directly by
  120625. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  120626. ** function is called by the sqlite3_extension_init() entry point.
  120627. */
  120628. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  120629. int rc = SQLITE_OK;
  120630. Fts3Hash *pHash = 0;
  120631. const sqlite3_tokenizer_module *pSimple = 0;
  120632. const sqlite3_tokenizer_module *pPorter = 0;
  120633. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120634. const sqlite3_tokenizer_module *pUnicode = 0;
  120635. #endif
  120636. #ifdef SQLITE_ENABLE_ICU
  120637. const sqlite3_tokenizer_module *pIcu = 0;
  120638. sqlite3Fts3IcuTokenizerModule(&pIcu);
  120639. #endif
  120640. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120641. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  120642. #endif
  120643. #ifdef SQLITE_TEST
  120644. rc = sqlite3Fts3InitTerm(db);
  120645. if( rc!=SQLITE_OK ) return rc;
  120646. #endif
  120647. rc = sqlite3Fts3InitAux(db);
  120648. if( rc!=SQLITE_OK ) return rc;
  120649. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  120650. sqlite3Fts3PorterTokenizerModule(&pPorter);
  120651. /* Allocate and initialize the hash-table used to store tokenizers. */
  120652. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  120653. if( !pHash ){
  120654. rc = SQLITE_NOMEM;
  120655. }else{
  120656. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  120657. }
  120658. /* Load the built-in tokenizers into the hash table */
  120659. if( rc==SQLITE_OK ){
  120660. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  120661. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  120662. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120663. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  120664. #endif
  120665. #ifdef SQLITE_ENABLE_ICU
  120666. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  120667. #endif
  120668. ){
  120669. rc = SQLITE_NOMEM;
  120670. }
  120671. }
  120672. #ifdef SQLITE_TEST
  120673. if( rc==SQLITE_OK ){
  120674. rc = sqlite3Fts3ExprInitTestInterface(db);
  120675. }
  120676. #endif
  120677. /* Create the virtual table wrapper around the hash-table and overload
  120678. ** the two scalar functions. If this is successful, register the
  120679. ** module with sqlite.
  120680. */
  120681. if( SQLITE_OK==rc
  120682. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  120683. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  120684. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  120685. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  120686. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  120687. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  120688. ){
  120689. rc = sqlite3_create_module_v2(
  120690. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  120691. );
  120692. if( rc==SQLITE_OK ){
  120693. rc = sqlite3_create_module_v2(
  120694. db, "fts4", &fts3Module, (void *)pHash, 0
  120695. );
  120696. }
  120697. if( rc==SQLITE_OK ){
  120698. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  120699. }
  120700. return rc;
  120701. }
  120702. /* An error has occurred. Delete the hash table and return the error code. */
  120703. assert( rc!=SQLITE_OK );
  120704. if( pHash ){
  120705. sqlite3Fts3HashClear(pHash);
  120706. sqlite3_free(pHash);
  120707. }
  120708. return rc;
  120709. }
  120710. /*
  120711. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  120712. ** by pExpr.
  120713. **
  120714. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  120715. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  120716. ** Fts3SegReader objects internally to provide an interface to seek or scan
  120717. ** within the union of all segments of a b-tree. Hence the name.
  120718. **
  120719. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  120720. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  120721. ** there exists prefix b-tree of the right length) then it may be traversed
  120722. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  120723. ** doclist and then traversed.
  120724. */
  120725. static void fts3EvalAllocateReaders(
  120726. Fts3Cursor *pCsr, /* FTS cursor handle */
  120727. Fts3Expr *pExpr, /* Allocate readers for this expression */
  120728. int *pnToken, /* OUT: Total number of tokens in phrase. */
  120729. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  120730. int *pRc /* IN/OUT: Error code */
  120731. ){
  120732. if( pExpr && SQLITE_OK==*pRc ){
  120733. if( pExpr->eType==FTSQUERY_PHRASE ){
  120734. int i;
  120735. int nToken = pExpr->pPhrase->nToken;
  120736. *pnToken += nToken;
  120737. for(i=0; i<nToken; i++){
  120738. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  120739. int rc = fts3TermSegReaderCursor(pCsr,
  120740. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  120741. );
  120742. if( rc!=SQLITE_OK ){
  120743. *pRc = rc;
  120744. return;
  120745. }
  120746. }
  120747. assert( pExpr->pPhrase->iDoclistToken==0 );
  120748. pExpr->pPhrase->iDoclistToken = -1;
  120749. }else{
  120750. *pnOr += (pExpr->eType==FTSQUERY_OR);
  120751. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  120752. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  120753. }
  120754. }
  120755. }
  120756. /*
  120757. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  120758. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  120759. **
  120760. ** This function assumes that pList points to a buffer allocated using
  120761. ** sqlite3_malloc(). This function takes responsibility for eventually
  120762. ** freeing the buffer.
  120763. */
  120764. static void fts3EvalPhraseMergeToken(
  120765. Fts3Table *pTab, /* FTS Table pointer */
  120766. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  120767. int iToken, /* Token pList/nList corresponds to */
  120768. char *pList, /* Pointer to doclist */
  120769. int nList /* Number of bytes in pList */
  120770. ){
  120771. assert( iToken!=p->iDoclistToken );
  120772. if( pList==0 ){
  120773. sqlite3_free(p->doclist.aAll);
  120774. p->doclist.aAll = 0;
  120775. p->doclist.nAll = 0;
  120776. }
  120777. else if( p->iDoclistToken<0 ){
  120778. p->doclist.aAll = pList;
  120779. p->doclist.nAll = nList;
  120780. }
  120781. else if( p->doclist.aAll==0 ){
  120782. sqlite3_free(pList);
  120783. }
  120784. else {
  120785. char *pLeft;
  120786. char *pRight;
  120787. int nLeft;
  120788. int nRight;
  120789. int nDiff;
  120790. if( p->iDoclistToken<iToken ){
  120791. pLeft = p->doclist.aAll;
  120792. nLeft = p->doclist.nAll;
  120793. pRight = pList;
  120794. nRight = nList;
  120795. nDiff = iToken - p->iDoclistToken;
  120796. }else{
  120797. pRight = p->doclist.aAll;
  120798. nRight = p->doclist.nAll;
  120799. pLeft = pList;
  120800. nLeft = nList;
  120801. nDiff = p->iDoclistToken - iToken;
  120802. }
  120803. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  120804. sqlite3_free(pLeft);
  120805. p->doclist.aAll = pRight;
  120806. p->doclist.nAll = nRight;
  120807. }
  120808. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  120809. }
  120810. /*
  120811. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  120812. ** does not take deferred tokens into account.
  120813. **
  120814. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120815. */
  120816. static int fts3EvalPhraseLoad(
  120817. Fts3Cursor *pCsr, /* FTS Cursor handle */
  120818. Fts3Phrase *p /* Phrase object */
  120819. ){
  120820. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  120821. int iToken;
  120822. int rc = SQLITE_OK;
  120823. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  120824. Fts3PhraseToken *pToken = &p->aToken[iToken];
  120825. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  120826. if( pToken->pSegcsr ){
  120827. int nThis = 0;
  120828. char *pThis = 0;
  120829. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  120830. if( rc==SQLITE_OK ){
  120831. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  120832. }
  120833. }
  120834. assert( pToken->pSegcsr==0 );
  120835. }
  120836. return rc;
  120837. }
  120838. /*
  120839. ** This function is called on each phrase after the position lists for
  120840. ** any deferred tokens have been loaded into memory. It updates the phrases
  120841. ** current position list to include only those positions that are really
  120842. ** instances of the phrase (after considering deferred tokens). If this
  120843. ** means that the phrase does not appear in the current row, doclist.pList
  120844. ** and doclist.nList are both zeroed.
  120845. **
  120846. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120847. */
  120848. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  120849. int iToken; /* Used to iterate through phrase tokens */
  120850. char *aPoslist = 0; /* Position list for deferred tokens */
  120851. int nPoslist = 0; /* Number of bytes in aPoslist */
  120852. int iPrev = -1; /* Token number of previous deferred token */
  120853. assert( pPhrase->doclist.bFreeList==0 );
  120854. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  120855. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  120856. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  120857. if( pDeferred ){
  120858. char *pList;
  120859. int nList;
  120860. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  120861. if( rc!=SQLITE_OK ) return rc;
  120862. if( pList==0 ){
  120863. sqlite3_free(aPoslist);
  120864. pPhrase->doclist.pList = 0;
  120865. pPhrase->doclist.nList = 0;
  120866. return SQLITE_OK;
  120867. }else if( aPoslist==0 ){
  120868. aPoslist = pList;
  120869. nPoslist = nList;
  120870. }else{
  120871. char *aOut = pList;
  120872. char *p1 = aPoslist;
  120873. char *p2 = aOut;
  120874. assert( iPrev>=0 );
  120875. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  120876. sqlite3_free(aPoslist);
  120877. aPoslist = pList;
  120878. nPoslist = (int)(aOut - aPoslist);
  120879. if( nPoslist==0 ){
  120880. sqlite3_free(aPoslist);
  120881. pPhrase->doclist.pList = 0;
  120882. pPhrase->doclist.nList = 0;
  120883. return SQLITE_OK;
  120884. }
  120885. }
  120886. iPrev = iToken;
  120887. }
  120888. }
  120889. if( iPrev>=0 ){
  120890. int nMaxUndeferred = pPhrase->iDoclistToken;
  120891. if( nMaxUndeferred<0 ){
  120892. pPhrase->doclist.pList = aPoslist;
  120893. pPhrase->doclist.nList = nPoslist;
  120894. pPhrase->doclist.iDocid = pCsr->iPrevId;
  120895. pPhrase->doclist.bFreeList = 1;
  120896. }else{
  120897. int nDistance;
  120898. char *p1;
  120899. char *p2;
  120900. char *aOut;
  120901. if( nMaxUndeferred>iPrev ){
  120902. p1 = aPoslist;
  120903. p2 = pPhrase->doclist.pList;
  120904. nDistance = nMaxUndeferred - iPrev;
  120905. }else{
  120906. p1 = pPhrase->doclist.pList;
  120907. p2 = aPoslist;
  120908. nDistance = iPrev - nMaxUndeferred;
  120909. }
  120910. aOut = (char *)sqlite3_malloc(nPoslist+8);
  120911. if( !aOut ){
  120912. sqlite3_free(aPoslist);
  120913. return SQLITE_NOMEM;
  120914. }
  120915. pPhrase->doclist.pList = aOut;
  120916. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  120917. pPhrase->doclist.bFreeList = 1;
  120918. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  120919. }else{
  120920. sqlite3_free(aOut);
  120921. pPhrase->doclist.pList = 0;
  120922. pPhrase->doclist.nList = 0;
  120923. }
  120924. sqlite3_free(aPoslist);
  120925. }
  120926. }
  120927. return SQLITE_OK;
  120928. }
  120929. /*
  120930. ** Maximum number of tokens a phrase may have to be considered for the
  120931. ** incremental doclists strategy.
  120932. */
  120933. #define MAX_INCR_PHRASE_TOKENS 4
  120934. /*
  120935. ** This function is called for each Fts3Phrase in a full-text query
  120936. ** expression to initialize the mechanism for returning rows. Once this
  120937. ** function has been called successfully on an Fts3Phrase, it may be
  120938. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  120939. **
  120940. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  120941. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  120942. ** memory within this call.
  120943. **
  120944. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120945. */
  120946. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  120947. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  120948. int rc = SQLITE_OK; /* Error code */
  120949. int i;
  120950. /* Determine if doclists may be loaded from disk incrementally. This is
  120951. ** possible if the bOptOk argument is true, the FTS doclists will be
  120952. ** scanned in forward order, and the phrase consists of
  120953. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  120954. ** tokens or prefix tokens that cannot use a prefix-index. */
  120955. int bHaveIncr = 0;
  120956. int bIncrOk = (bOptOk
  120957. && pCsr->bDesc==pTab->bDescIdx
  120958. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  120959. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  120960. #ifdef SQLITE_TEST
  120961. && pTab->bNoIncrDoclist==0
  120962. #endif
  120963. );
  120964. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  120965. Fts3PhraseToken *pToken = &p->aToken[i];
  120966. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  120967. bIncrOk = 0;
  120968. }
  120969. if( pToken->pSegcsr ) bHaveIncr = 1;
  120970. }
  120971. if( bIncrOk && bHaveIncr ){
  120972. /* Use the incremental approach. */
  120973. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  120974. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  120975. Fts3PhraseToken *pToken = &p->aToken[i];
  120976. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  120977. if( pSegcsr ){
  120978. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  120979. }
  120980. }
  120981. p->bIncr = 1;
  120982. }else{
  120983. /* Load the full doclist for the phrase into memory. */
  120984. rc = fts3EvalPhraseLoad(pCsr, p);
  120985. p->bIncr = 0;
  120986. }
  120987. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  120988. return rc;
  120989. }
  120990. /*
  120991. ** This function is used to iterate backwards (from the end to start)
  120992. ** through doclists. It is used by this module to iterate through phrase
  120993. ** doclists in reverse and by the fts3_write.c module to iterate through
  120994. ** pending-terms lists when writing to databases with "order=desc".
  120995. **
  120996. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  120997. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  120998. ** function iterates from the end of the doclist to the beginning.
  120999. */
  121000. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  121001. int bDescIdx, /* True if the doclist is desc */
  121002. char *aDoclist, /* Pointer to entire doclist */
  121003. int nDoclist, /* Length of aDoclist in bytes */
  121004. char **ppIter, /* IN/OUT: Iterator pointer */
  121005. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  121006. int *pnList, /* OUT: List length pointer */
  121007. u8 *pbEof /* OUT: End-of-file flag */
  121008. ){
  121009. char *p = *ppIter;
  121010. assert( nDoclist>0 );
  121011. assert( *pbEof==0 );
  121012. assert( p || *piDocid==0 );
  121013. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  121014. if( p==0 ){
  121015. sqlite3_int64 iDocid = 0;
  121016. char *pNext = 0;
  121017. char *pDocid = aDoclist;
  121018. char *pEnd = &aDoclist[nDoclist];
  121019. int iMul = 1;
  121020. while( pDocid<pEnd ){
  121021. sqlite3_int64 iDelta;
  121022. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  121023. iDocid += (iMul * iDelta);
  121024. pNext = pDocid;
  121025. fts3PoslistCopy(0, &pDocid);
  121026. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  121027. iMul = (bDescIdx ? -1 : 1);
  121028. }
  121029. *pnList = (int)(pEnd - pNext);
  121030. *ppIter = pNext;
  121031. *piDocid = iDocid;
  121032. }else{
  121033. int iMul = (bDescIdx ? -1 : 1);
  121034. sqlite3_int64 iDelta;
  121035. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  121036. *piDocid -= (iMul * iDelta);
  121037. if( p==aDoclist ){
  121038. *pbEof = 1;
  121039. }else{
  121040. char *pSave = p;
  121041. fts3ReversePoslist(aDoclist, &p);
  121042. *pnList = (int)(pSave - p);
  121043. }
  121044. *ppIter = p;
  121045. }
  121046. }
  121047. /*
  121048. ** Iterate forwards through a doclist.
  121049. */
  121050. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  121051. int bDescIdx, /* True if the doclist is desc */
  121052. char *aDoclist, /* Pointer to entire doclist */
  121053. int nDoclist, /* Length of aDoclist in bytes */
  121054. char **ppIter, /* IN/OUT: Iterator pointer */
  121055. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  121056. u8 *pbEof /* OUT: End-of-file flag */
  121057. ){
  121058. char *p = *ppIter;
  121059. assert( nDoclist>0 );
  121060. assert( *pbEof==0 );
  121061. assert( p || *piDocid==0 );
  121062. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  121063. if( p==0 ){
  121064. p = aDoclist;
  121065. p += sqlite3Fts3GetVarint(p, piDocid);
  121066. }else{
  121067. fts3PoslistCopy(0, &p);
  121068. if( p>=&aDoclist[nDoclist] ){
  121069. *pbEof = 1;
  121070. }else{
  121071. sqlite3_int64 iVar;
  121072. p += sqlite3Fts3GetVarint(p, &iVar);
  121073. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  121074. }
  121075. }
  121076. *ppIter = p;
  121077. }
  121078. /*
  121079. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  121080. ** to true if EOF is reached.
  121081. */
  121082. static void fts3EvalDlPhraseNext(
  121083. Fts3Table *pTab,
  121084. Fts3Doclist *pDL,
  121085. u8 *pbEof
  121086. ){
  121087. char *pIter; /* Used to iterate through aAll */
  121088. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  121089. if( pDL->pNextDocid ){
  121090. pIter = pDL->pNextDocid;
  121091. }else{
  121092. pIter = pDL->aAll;
  121093. }
  121094. if( pIter>=pEnd ){
  121095. /* We have already reached the end of this doclist. EOF. */
  121096. *pbEof = 1;
  121097. }else{
  121098. sqlite3_int64 iDelta;
  121099. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  121100. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  121101. pDL->iDocid += iDelta;
  121102. }else{
  121103. pDL->iDocid -= iDelta;
  121104. }
  121105. pDL->pList = pIter;
  121106. fts3PoslistCopy(0, &pIter);
  121107. pDL->nList = (int)(pIter - pDL->pList);
  121108. /* pIter now points just past the 0x00 that terminates the position-
  121109. ** list for document pDL->iDocid. However, if this position-list was
  121110. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  121111. ** point to the start of the next docid value. The following line deals
  121112. ** with this case by advancing pIter past the zero-padding added by
  121113. ** fts3EvalNearTrim(). */
  121114. while( pIter<pEnd && *pIter==0 ) pIter++;
  121115. pDL->pNextDocid = pIter;
  121116. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  121117. *pbEof = 0;
  121118. }
  121119. }
  121120. /*
  121121. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  121122. */
  121123. typedef struct TokenDoclist TokenDoclist;
  121124. struct TokenDoclist {
  121125. int bIgnore;
  121126. sqlite3_int64 iDocid;
  121127. char *pList;
  121128. int nList;
  121129. };
  121130. /*
  121131. ** Token pToken is an incrementally loaded token that is part of a
  121132. ** multi-token phrase. Advance it to the next matching document in the
  121133. ** database and populate output variable *p with the details of the new
  121134. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  121135. **
  121136. ** If an error occurs, return an SQLite error code. Otherwise, return
  121137. ** SQLITE_OK.
  121138. */
  121139. static int incrPhraseTokenNext(
  121140. Fts3Table *pTab, /* Virtual table handle */
  121141. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  121142. int iToken, /* Specific token to advance */
  121143. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  121144. u8 *pbEof /* OUT: True if iterator is at EOF */
  121145. ){
  121146. int rc = SQLITE_OK;
  121147. if( pPhrase->iDoclistToken==iToken ){
  121148. assert( p->bIgnore==0 );
  121149. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  121150. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  121151. p->pList = pPhrase->doclist.pList;
  121152. p->nList = pPhrase->doclist.nList;
  121153. p->iDocid = pPhrase->doclist.iDocid;
  121154. }else{
  121155. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  121156. assert( pToken->pDeferred==0 );
  121157. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  121158. if( pToken->pSegcsr ){
  121159. assert( p->bIgnore==0 );
  121160. rc = sqlite3Fts3MsrIncrNext(
  121161. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  121162. );
  121163. if( p->pList==0 ) *pbEof = 1;
  121164. }else{
  121165. p->bIgnore = 1;
  121166. }
  121167. }
  121168. return rc;
  121169. }
  121170. /*
  121171. ** The phrase iterator passed as the second argument:
  121172. **
  121173. ** * features at least one token that uses an incremental doclist, and
  121174. **
  121175. ** * does not contain any deferred tokens.
  121176. **
  121177. ** Advance it to the next matching documnent in the database and populate
  121178. ** the Fts3Doclist.pList and nList fields.
  121179. **
  121180. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  121181. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  121182. ** successfully advanced, *pbEof is set to 0.
  121183. **
  121184. ** If an error occurs, return an SQLite error code. Otherwise, return
  121185. ** SQLITE_OK.
  121186. */
  121187. static int fts3EvalIncrPhraseNext(
  121188. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121189. Fts3Phrase *p, /* Phrase object to advance to next docid */
  121190. u8 *pbEof /* OUT: Set to 1 if EOF */
  121191. ){
  121192. int rc = SQLITE_OK;
  121193. Fts3Doclist *pDL = &p->doclist;
  121194. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121195. u8 bEof = 0;
  121196. /* This is only called if it is guaranteed that the phrase has at least
  121197. ** one incremental token. In which case the bIncr flag is set. */
  121198. assert( p->bIncr==1 );
  121199. if( p->nToken==1 && p->bIncr ){
  121200. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  121201. &pDL->iDocid, &pDL->pList, &pDL->nList
  121202. );
  121203. if( pDL->pList==0 ) bEof = 1;
  121204. }else{
  121205. int bDescDoclist = pCsr->bDesc;
  121206. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  121207. memset(a, 0, sizeof(a));
  121208. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  121209. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  121210. while( bEof==0 ){
  121211. int bMaxSet = 0;
  121212. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  121213. int i; /* Used to iterate through tokens */
  121214. /* Advance the iterator for each token in the phrase once. */
  121215. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  121216. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  121217. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  121218. iMax = a[i].iDocid;
  121219. bMaxSet = 1;
  121220. }
  121221. }
  121222. assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
  121223. assert( rc!=SQLITE_OK || bMaxSet );
  121224. /* Keep advancing iterators until they all point to the same document */
  121225. for(i=0; i<p->nToken; i++){
  121226. while( rc==SQLITE_OK && bEof==0
  121227. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  121228. ){
  121229. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  121230. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  121231. iMax = a[i].iDocid;
  121232. i = 0;
  121233. }
  121234. }
  121235. }
  121236. /* Check if the current entries really are a phrase match */
  121237. if( bEof==0 ){
  121238. int nList = 0;
  121239. int nByte = a[p->nToken-1].nList;
  121240. char *aDoclist = sqlite3_malloc(nByte+1);
  121241. if( !aDoclist ) return SQLITE_NOMEM;
  121242. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  121243. for(i=0; i<(p->nToken-1); i++){
  121244. if( a[i].bIgnore==0 ){
  121245. char *pL = a[i].pList;
  121246. char *pR = aDoclist;
  121247. char *pOut = aDoclist;
  121248. int nDist = p->nToken-1-i;
  121249. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  121250. if( res==0 ) break;
  121251. nList = (int)(pOut - aDoclist);
  121252. }
  121253. }
  121254. if( i==(p->nToken-1) ){
  121255. pDL->iDocid = iMax;
  121256. pDL->pList = aDoclist;
  121257. pDL->nList = nList;
  121258. pDL->bFreeList = 1;
  121259. break;
  121260. }
  121261. sqlite3_free(aDoclist);
  121262. }
  121263. }
  121264. }
  121265. *pbEof = bEof;
  121266. return rc;
  121267. }
  121268. /*
  121269. ** Attempt to move the phrase iterator to point to the next matching docid.
  121270. ** If an error occurs, return an SQLite error code. Otherwise, return
  121271. ** SQLITE_OK.
  121272. **
  121273. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  121274. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  121275. ** successfully advanced, *pbEof is set to 0.
  121276. */
  121277. static int fts3EvalPhraseNext(
  121278. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121279. Fts3Phrase *p, /* Phrase object to advance to next docid */
  121280. u8 *pbEof /* OUT: Set to 1 if EOF */
  121281. ){
  121282. int rc = SQLITE_OK;
  121283. Fts3Doclist *pDL = &p->doclist;
  121284. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121285. if( p->bIncr ){
  121286. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  121287. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  121288. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  121289. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  121290. );
  121291. pDL->pList = pDL->pNextDocid;
  121292. }else{
  121293. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  121294. }
  121295. return rc;
  121296. }
  121297. /*
  121298. **
  121299. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121300. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  121301. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  121302. ** expressions for which all descendent tokens are deferred.
  121303. **
  121304. ** If parameter bOptOk is zero, then it is guaranteed that the
  121305. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  121306. ** each phrase in the expression (subject to deferred token processing).
  121307. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  121308. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  121309. **
  121310. ** If an error occurs within this function, *pRc is set to an SQLite error
  121311. ** code before returning.
  121312. */
  121313. static void fts3EvalStartReaders(
  121314. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121315. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  121316. int *pRc /* IN/OUT: Error code */
  121317. ){
  121318. if( pExpr && SQLITE_OK==*pRc ){
  121319. if( pExpr->eType==FTSQUERY_PHRASE ){
  121320. int i;
  121321. int nToken = pExpr->pPhrase->nToken;
  121322. for(i=0; i<nToken; i++){
  121323. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  121324. }
  121325. pExpr->bDeferred = (i==nToken);
  121326. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  121327. }else{
  121328. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  121329. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  121330. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  121331. }
  121332. }
  121333. }
  121334. /*
  121335. ** An array of the following structures is assembled as part of the process
  121336. ** of selecting tokens to defer before the query starts executing (as part
  121337. ** of the xFilter() method). There is one element in the array for each
  121338. ** token in the FTS expression.
  121339. **
  121340. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  121341. ** to phrases that are connected only by AND and NEAR operators (not OR or
  121342. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  121343. ** separately. The root of a tokens AND/NEAR cluster is stored in
  121344. ** Fts3TokenAndCost.pRoot.
  121345. */
  121346. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  121347. struct Fts3TokenAndCost {
  121348. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  121349. int iToken; /* Position of token in phrase */
  121350. Fts3PhraseToken *pToken; /* The token itself */
  121351. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  121352. int nOvfl; /* Number of overflow pages to load doclist */
  121353. int iCol; /* The column the token must match */
  121354. };
  121355. /*
  121356. ** This function is used to populate an allocated Fts3TokenAndCost array.
  121357. **
  121358. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121359. ** Otherwise, if an error occurs during execution, *pRc is set to an
  121360. ** SQLite error code.
  121361. */
  121362. static void fts3EvalTokenCosts(
  121363. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121364. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  121365. Fts3Expr *pExpr, /* Expression to consider */
  121366. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  121367. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  121368. int *pRc /* IN/OUT: Error code */
  121369. ){
  121370. if( *pRc==SQLITE_OK ){
  121371. if( pExpr->eType==FTSQUERY_PHRASE ){
  121372. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121373. int i;
  121374. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  121375. Fts3TokenAndCost *pTC = (*ppTC)++;
  121376. pTC->pPhrase = pPhrase;
  121377. pTC->iToken = i;
  121378. pTC->pRoot = pRoot;
  121379. pTC->pToken = &pPhrase->aToken[i];
  121380. pTC->iCol = pPhrase->iColumn;
  121381. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  121382. }
  121383. }else if( pExpr->eType!=FTSQUERY_NOT ){
  121384. assert( pExpr->eType==FTSQUERY_OR
  121385. || pExpr->eType==FTSQUERY_AND
  121386. || pExpr->eType==FTSQUERY_NEAR
  121387. );
  121388. assert( pExpr->pLeft && pExpr->pRight );
  121389. if( pExpr->eType==FTSQUERY_OR ){
  121390. pRoot = pExpr->pLeft;
  121391. **ppOr = pRoot;
  121392. (*ppOr)++;
  121393. }
  121394. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  121395. if( pExpr->eType==FTSQUERY_OR ){
  121396. pRoot = pExpr->pRight;
  121397. **ppOr = pRoot;
  121398. (*ppOr)++;
  121399. }
  121400. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  121401. }
  121402. }
  121403. }
  121404. /*
  121405. ** Determine the average document (row) size in pages. If successful,
  121406. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  121407. ** an SQLite error code.
  121408. **
  121409. ** The average document size in pages is calculated by first calculating
  121410. ** determining the average size in bytes, B. If B is less than the amount
  121411. ** of data that will fit on a single leaf page of an intkey table in
  121412. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  121413. ** the number of overflow pages consumed by a record B bytes in size.
  121414. */
  121415. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  121416. if( pCsr->nRowAvg==0 ){
  121417. /* The average document size, which is required to calculate the cost
  121418. ** of each doclist, has not yet been determined. Read the required
  121419. ** data from the %_stat table to calculate it.
  121420. **
  121421. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  121422. ** varints, where nCol is the number of columns in the FTS3 table.
  121423. ** The first varint is the number of documents currently stored in
  121424. ** the table. The following nCol varints contain the total amount of
  121425. ** data stored in all rows of each column of the table, from left
  121426. ** to right.
  121427. */
  121428. int rc;
  121429. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  121430. sqlite3_stmt *pStmt;
  121431. sqlite3_int64 nDoc = 0;
  121432. sqlite3_int64 nByte = 0;
  121433. const char *pEnd;
  121434. const char *a;
  121435. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  121436. if( rc!=SQLITE_OK ) return rc;
  121437. a = sqlite3_column_blob(pStmt, 0);
  121438. assert( a );
  121439. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  121440. a += sqlite3Fts3GetVarint(a, &nDoc);
  121441. while( a<pEnd ){
  121442. a += sqlite3Fts3GetVarint(a, &nByte);
  121443. }
  121444. if( nDoc==0 || nByte==0 ){
  121445. sqlite3_reset(pStmt);
  121446. return FTS_CORRUPT_VTAB;
  121447. }
  121448. pCsr->nDoc = nDoc;
  121449. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  121450. assert( pCsr->nRowAvg>0 );
  121451. rc = sqlite3_reset(pStmt);
  121452. if( rc!=SQLITE_OK ) return rc;
  121453. }
  121454. *pnPage = pCsr->nRowAvg;
  121455. return SQLITE_OK;
  121456. }
  121457. /*
  121458. ** This function is called to select the tokens (if any) that will be
  121459. ** deferred. The array aTC[] has already been populated when this is
  121460. ** called.
  121461. **
  121462. ** This function is called once for each AND/NEAR cluster in the
  121463. ** expression. Each invocation determines which tokens to defer within
  121464. ** the cluster with root node pRoot. See comments above the definition
  121465. ** of struct Fts3TokenAndCost for more details.
  121466. **
  121467. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  121468. ** called on each token to defer. Otherwise, an SQLite error code is
  121469. ** returned.
  121470. */
  121471. static int fts3EvalSelectDeferred(
  121472. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121473. Fts3Expr *pRoot, /* Consider tokens with this root node */
  121474. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  121475. int nTC /* Number of entries in aTC[] */
  121476. ){
  121477. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121478. int nDocSize = 0; /* Number of pages per doc loaded */
  121479. int rc = SQLITE_OK; /* Return code */
  121480. int ii; /* Iterator variable for various purposes */
  121481. int nOvfl = 0; /* Total overflow pages used by doclists */
  121482. int nToken = 0; /* Total number of tokens in cluster */
  121483. int nMinEst = 0; /* The minimum count for any phrase so far. */
  121484. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  121485. /* Tokens are never deferred for FTS tables created using the content=xxx
  121486. ** option. The reason being that it is not guaranteed that the content
  121487. ** table actually contains the same data as the index. To prevent this from
  121488. ** causing any problems, the deferred token optimization is completely
  121489. ** disabled for content=xxx tables. */
  121490. if( pTab->zContentTbl ){
  121491. return SQLITE_OK;
  121492. }
  121493. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  121494. ** associated with the tokens spill onto overflow pages, or if there is
  121495. ** only 1 token, exit early. No tokens to defer in this case. */
  121496. for(ii=0; ii<nTC; ii++){
  121497. if( aTC[ii].pRoot==pRoot ){
  121498. nOvfl += aTC[ii].nOvfl;
  121499. nToken++;
  121500. }
  121501. }
  121502. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  121503. /* Obtain the average docsize (in pages). */
  121504. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  121505. assert( rc!=SQLITE_OK || nDocSize>0 );
  121506. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  121507. ** of the number of overflow pages that will be loaded by the pager layer
  121508. ** to retrieve the entire doclist for the token from the full-text index.
  121509. ** Load the doclists for tokens that are either:
  121510. **
  121511. ** a. The cheapest token in the entire query (i.e. the one visited by the
  121512. ** first iteration of this loop), or
  121513. **
  121514. ** b. Part of a multi-token phrase.
  121515. **
  121516. ** After each token doclist is loaded, merge it with the others from the
  121517. ** same phrase and count the number of documents that the merged doclist
  121518. ** contains. Set variable "nMinEst" to the smallest number of documents in
  121519. ** any phrase doclist for which 1 or more token doclists have been loaded.
  121520. ** Let nOther be the number of other phrases for which it is certain that
  121521. ** one or more tokens will not be deferred.
  121522. **
  121523. ** Then, for each token, defer it if loading the doclist would result in
  121524. ** loading N or more overflow pages into memory, where N is computed as:
  121525. **
  121526. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  121527. */
  121528. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  121529. int iTC; /* Used to iterate through aTC[] array. */
  121530. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  121531. /* Set pTC to point to the cheapest remaining token. */
  121532. for(iTC=0; iTC<nTC; iTC++){
  121533. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  121534. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  121535. ){
  121536. pTC = &aTC[iTC];
  121537. }
  121538. }
  121539. assert( pTC );
  121540. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  121541. /* The number of overflow pages to load for this (and therefore all
  121542. ** subsequent) tokens is greater than the estimated number of pages
  121543. ** that will be loaded if all subsequent tokens are deferred.
  121544. */
  121545. Fts3PhraseToken *pToken = pTC->pToken;
  121546. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  121547. fts3SegReaderCursorFree(pToken->pSegcsr);
  121548. pToken->pSegcsr = 0;
  121549. }else{
  121550. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  121551. ** for-loop. Except, limit the value to 2^24 to prevent it from
  121552. ** overflowing the 32-bit integer it is stored in. */
  121553. if( ii<12 ) nLoad4 = nLoad4*4;
  121554. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  121555. /* Either this is the cheapest token in the entire query, or it is
  121556. ** part of a multi-token phrase. Either way, the entire doclist will
  121557. ** (eventually) be loaded into memory. It may as well be now. */
  121558. Fts3PhraseToken *pToken = pTC->pToken;
  121559. int nList = 0;
  121560. char *pList = 0;
  121561. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  121562. assert( rc==SQLITE_OK || pList==0 );
  121563. if( rc==SQLITE_OK ){
  121564. int nCount;
  121565. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  121566. nCount = fts3DoclistCountDocids(
  121567. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  121568. );
  121569. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  121570. }
  121571. }
  121572. }
  121573. pTC->pToken = 0;
  121574. }
  121575. return rc;
  121576. }
  121577. /*
  121578. ** This function is called from within the xFilter method. It initializes
  121579. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  121580. ** the results of a query, the caller does:
  121581. **
  121582. ** fts3EvalStart(pCsr);
  121583. ** while( 1 ){
  121584. ** fts3EvalNext(pCsr);
  121585. ** if( pCsr->bEof ) break;
  121586. ** ... return row pCsr->iPrevId to the caller ...
  121587. ** }
  121588. */
  121589. static int fts3EvalStart(Fts3Cursor *pCsr){
  121590. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121591. int rc = SQLITE_OK;
  121592. int nToken = 0;
  121593. int nOr = 0;
  121594. /* Allocate a MultiSegReader for each token in the expression. */
  121595. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  121596. /* Determine which, if any, tokens in the expression should be deferred. */
  121597. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121598. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  121599. Fts3TokenAndCost *aTC;
  121600. Fts3Expr **apOr;
  121601. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  121602. sizeof(Fts3TokenAndCost) * nToken
  121603. + sizeof(Fts3Expr *) * nOr * 2
  121604. );
  121605. apOr = (Fts3Expr **)&aTC[nToken];
  121606. if( !aTC ){
  121607. rc = SQLITE_NOMEM;
  121608. }else{
  121609. int ii;
  121610. Fts3TokenAndCost *pTC = aTC;
  121611. Fts3Expr **ppOr = apOr;
  121612. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  121613. nToken = (int)(pTC-aTC);
  121614. nOr = (int)(ppOr-apOr);
  121615. if( rc==SQLITE_OK ){
  121616. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  121617. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  121618. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  121619. }
  121620. }
  121621. sqlite3_free(aTC);
  121622. }
  121623. }
  121624. #endif
  121625. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  121626. return rc;
  121627. }
  121628. /*
  121629. ** Invalidate the current position list for phrase pPhrase.
  121630. */
  121631. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  121632. if( pPhrase->doclist.bFreeList ){
  121633. sqlite3_free(pPhrase->doclist.pList);
  121634. }
  121635. pPhrase->doclist.pList = 0;
  121636. pPhrase->doclist.nList = 0;
  121637. pPhrase->doclist.bFreeList = 0;
  121638. }
  121639. /*
  121640. ** This function is called to edit the position list associated with
  121641. ** the phrase object passed as the fifth argument according to a NEAR
  121642. ** condition. For example:
  121643. **
  121644. ** abc NEAR/5 "def ghi"
  121645. **
  121646. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  121647. ** the example above). When this function is called, *paPoslist points to
  121648. ** the position list, and *pnToken is the number of phrase tokens in, the
  121649. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  121650. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  121651. ** the position list associated with phrase "abc".
  121652. **
  121653. ** All positions in the pPhrase position list that are not sufficiently
  121654. ** close to a position in the *paPoslist position list are removed. If this
  121655. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  121656. **
  121657. ** Before returning, *paPoslist is set to point to the position lsit
  121658. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  121659. ** pPhrase.
  121660. */
  121661. static int fts3EvalNearTrim(
  121662. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  121663. char *aTmp, /* Temporary space to use */
  121664. char **paPoslist, /* IN/OUT: Position list */
  121665. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  121666. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  121667. ){
  121668. int nParam1 = nNear + pPhrase->nToken;
  121669. int nParam2 = nNear + *pnToken;
  121670. int nNew;
  121671. char *p2;
  121672. char *pOut;
  121673. int res;
  121674. assert( pPhrase->doclist.pList );
  121675. p2 = pOut = pPhrase->doclist.pList;
  121676. res = fts3PoslistNearMerge(
  121677. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  121678. );
  121679. if( res ){
  121680. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  121681. assert( pPhrase->doclist.pList[nNew]=='\0' );
  121682. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  121683. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  121684. pPhrase->doclist.nList = nNew;
  121685. *paPoslist = pPhrase->doclist.pList;
  121686. *pnToken = pPhrase->nToken;
  121687. }
  121688. return res;
  121689. }
  121690. /*
  121691. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  121692. ** Otherwise, it advances the expression passed as the second argument to
  121693. ** point to the next matching row in the database. Expressions iterate through
  121694. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  121695. ** or descending if it is non-zero.
  121696. **
  121697. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  121698. ** successful, the following variables in pExpr are set:
  121699. **
  121700. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  121701. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  121702. **
  121703. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  121704. ** at EOF, then the following variables are populated with the position list
  121705. ** for the phrase for the visited row:
  121706. **
  121707. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  121708. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  121709. **
  121710. ** It says above that this function advances the expression to the next
  121711. ** matching row. This is usually true, but there are the following exceptions:
  121712. **
  121713. ** 1. Deferred tokens are not taken into account. If a phrase consists
  121714. ** entirely of deferred tokens, it is assumed to match every row in
  121715. ** the db. In this case the position-list is not populated at all.
  121716. **
  121717. ** Or, if a phrase contains one or more deferred tokens and one or
  121718. ** more non-deferred tokens, then the expression is advanced to the
  121719. ** next possible match, considering only non-deferred tokens. In other
  121720. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  121721. ** is advanced to the next row that contains an instance of "A * C",
  121722. ** where "*" may match any single token. The position list in this case
  121723. ** is populated as for "A * C" before returning.
  121724. **
  121725. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  121726. ** advanced to point to the next row that matches "x AND y".
  121727. **
  121728. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  121729. ** really a match, taking into account deferred tokens and NEAR operators.
  121730. */
  121731. static void fts3EvalNextRow(
  121732. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121733. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  121734. int *pRc /* IN/OUT: Error code */
  121735. ){
  121736. if( *pRc==SQLITE_OK ){
  121737. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  121738. assert( pExpr->bEof==0 );
  121739. pExpr->bStart = 1;
  121740. switch( pExpr->eType ){
  121741. case FTSQUERY_NEAR:
  121742. case FTSQUERY_AND: {
  121743. Fts3Expr *pLeft = pExpr->pLeft;
  121744. Fts3Expr *pRight = pExpr->pRight;
  121745. assert( !pLeft->bDeferred || !pRight->bDeferred );
  121746. if( pLeft->bDeferred ){
  121747. /* LHS is entirely deferred. So we assume it matches every row.
  121748. ** Advance the RHS iterator to find the next row visited. */
  121749. fts3EvalNextRow(pCsr, pRight, pRc);
  121750. pExpr->iDocid = pRight->iDocid;
  121751. pExpr->bEof = pRight->bEof;
  121752. }else if( pRight->bDeferred ){
  121753. /* RHS is entirely deferred. So we assume it matches every row.
  121754. ** Advance the LHS iterator to find the next row visited. */
  121755. fts3EvalNextRow(pCsr, pLeft, pRc);
  121756. pExpr->iDocid = pLeft->iDocid;
  121757. pExpr->bEof = pLeft->bEof;
  121758. }else{
  121759. /* Neither the RHS or LHS are deferred. */
  121760. fts3EvalNextRow(pCsr, pLeft, pRc);
  121761. fts3EvalNextRow(pCsr, pRight, pRc);
  121762. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  121763. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121764. if( iDiff==0 ) break;
  121765. if( iDiff<0 ){
  121766. fts3EvalNextRow(pCsr, pLeft, pRc);
  121767. }else{
  121768. fts3EvalNextRow(pCsr, pRight, pRc);
  121769. }
  121770. }
  121771. pExpr->iDocid = pLeft->iDocid;
  121772. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  121773. }
  121774. break;
  121775. }
  121776. case FTSQUERY_OR: {
  121777. Fts3Expr *pLeft = pExpr->pLeft;
  121778. Fts3Expr *pRight = pExpr->pRight;
  121779. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121780. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  121781. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  121782. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  121783. fts3EvalNextRow(pCsr, pLeft, pRc);
  121784. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  121785. fts3EvalNextRow(pCsr, pRight, pRc);
  121786. }else{
  121787. fts3EvalNextRow(pCsr, pLeft, pRc);
  121788. fts3EvalNextRow(pCsr, pRight, pRc);
  121789. }
  121790. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  121791. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121792. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  121793. pExpr->iDocid = pLeft->iDocid;
  121794. }else{
  121795. pExpr->iDocid = pRight->iDocid;
  121796. }
  121797. break;
  121798. }
  121799. case FTSQUERY_NOT: {
  121800. Fts3Expr *pLeft = pExpr->pLeft;
  121801. Fts3Expr *pRight = pExpr->pRight;
  121802. if( pRight->bStart==0 ){
  121803. fts3EvalNextRow(pCsr, pRight, pRc);
  121804. assert( *pRc!=SQLITE_OK || pRight->bStart );
  121805. }
  121806. fts3EvalNextRow(pCsr, pLeft, pRc);
  121807. if( pLeft->bEof==0 ){
  121808. while( !*pRc
  121809. && !pRight->bEof
  121810. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  121811. ){
  121812. fts3EvalNextRow(pCsr, pRight, pRc);
  121813. }
  121814. }
  121815. pExpr->iDocid = pLeft->iDocid;
  121816. pExpr->bEof = pLeft->bEof;
  121817. break;
  121818. }
  121819. default: {
  121820. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121821. fts3EvalInvalidatePoslist(pPhrase);
  121822. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  121823. pExpr->iDocid = pPhrase->doclist.iDocid;
  121824. break;
  121825. }
  121826. }
  121827. }
  121828. }
  121829. /*
  121830. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  121831. ** cluster, then this function returns 1 immediately.
  121832. **
  121833. ** Otherwise, it checks if the current row really does match the NEAR
  121834. ** expression, using the data currently stored in the position lists
  121835. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  121836. **
  121837. ** If the current row is a match, the position list associated with each
  121838. ** phrase in the NEAR expression is edited in place to contain only those
  121839. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  121840. ** constraints. In this case it returns 1. If the NEAR expression does not
  121841. ** match the current row, 0 is returned. The position lists may or may not
  121842. ** be edited if 0 is returned.
  121843. */
  121844. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  121845. int res = 1;
  121846. /* The following block runs if pExpr is the root of a NEAR query.
  121847. ** For example, the query:
  121848. **
  121849. ** "w" NEAR "x" NEAR "y" NEAR "z"
  121850. **
  121851. ** which is represented in tree form as:
  121852. **
  121853. ** |
  121854. ** +--NEAR--+ <-- root of NEAR query
  121855. ** | |
  121856. ** +--NEAR--+ "z"
  121857. ** | |
  121858. ** +--NEAR--+ "y"
  121859. ** | |
  121860. ** "w" "x"
  121861. **
  121862. ** The right-hand child of a NEAR node is always a phrase. The
  121863. ** left-hand child may be either a phrase or a NEAR node. There are
  121864. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  121865. */
  121866. if( *pRc==SQLITE_OK
  121867. && pExpr->eType==FTSQUERY_NEAR
  121868. && pExpr->bEof==0
  121869. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  121870. ){
  121871. Fts3Expr *p;
  121872. int nTmp = 0; /* Bytes of temp space */
  121873. char *aTmp; /* Temp space for PoslistNearMerge() */
  121874. /* Allocate temporary working space. */
  121875. for(p=pExpr; p->pLeft; p=p->pLeft){
  121876. nTmp += p->pRight->pPhrase->doclist.nList;
  121877. }
  121878. nTmp += p->pPhrase->doclist.nList;
  121879. if( nTmp==0 ){
  121880. res = 0;
  121881. }else{
  121882. aTmp = sqlite3_malloc(nTmp*2);
  121883. if( !aTmp ){
  121884. *pRc = SQLITE_NOMEM;
  121885. res = 0;
  121886. }else{
  121887. char *aPoslist = p->pPhrase->doclist.pList;
  121888. int nToken = p->pPhrase->nToken;
  121889. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  121890. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  121891. int nNear = p->nNear;
  121892. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  121893. }
  121894. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  121895. nToken = pExpr->pRight->pPhrase->nToken;
  121896. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  121897. int nNear;
  121898. Fts3Phrase *pPhrase;
  121899. assert( p->pParent && p->pParent->pLeft==p );
  121900. nNear = p->pParent->nNear;
  121901. pPhrase = (
  121902. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  121903. );
  121904. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  121905. }
  121906. }
  121907. sqlite3_free(aTmp);
  121908. }
  121909. }
  121910. return res;
  121911. }
  121912. /*
  121913. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  121914. ** Assuming no error occurs or has occurred, It returns non-zero if the
  121915. ** expression passed as the second argument matches the row that pCsr
  121916. ** currently points to, or zero if it does not.
  121917. **
  121918. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121919. ** If an error occurs during execution of this function, *pRc is set to
  121920. ** the appropriate SQLite error code. In this case the returned value is
  121921. ** undefined.
  121922. */
  121923. static int fts3EvalTestExpr(
  121924. Fts3Cursor *pCsr, /* FTS cursor handle */
  121925. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  121926. int *pRc /* IN/OUT: Error code */
  121927. ){
  121928. int bHit = 1; /* Return value */
  121929. if( *pRc==SQLITE_OK ){
  121930. switch( pExpr->eType ){
  121931. case FTSQUERY_NEAR:
  121932. case FTSQUERY_AND:
  121933. bHit = (
  121934. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  121935. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  121936. && fts3EvalNearTest(pExpr, pRc)
  121937. );
  121938. /* If the NEAR expression does not match any rows, zero the doclist for
  121939. ** all phrases involved in the NEAR. This is because the snippet(),
  121940. ** offsets() and matchinfo() functions are not supposed to recognize
  121941. ** any instances of phrases that are part of unmatched NEAR queries.
  121942. ** For example if this expression:
  121943. **
  121944. ** ... MATCH 'a OR (b NEAR c)'
  121945. **
  121946. ** is matched against a row containing:
  121947. **
  121948. ** 'a b d e'
  121949. **
  121950. ** then any snippet() should ony highlight the "a" term, not the "b"
  121951. ** (as "b" is part of a non-matching NEAR clause).
  121952. */
  121953. if( bHit==0
  121954. && pExpr->eType==FTSQUERY_NEAR
  121955. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  121956. ){
  121957. Fts3Expr *p;
  121958. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  121959. if( p->pRight->iDocid==pCsr->iPrevId ){
  121960. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  121961. }
  121962. }
  121963. if( p->iDocid==pCsr->iPrevId ){
  121964. fts3EvalInvalidatePoslist(p->pPhrase);
  121965. }
  121966. }
  121967. break;
  121968. case FTSQUERY_OR: {
  121969. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  121970. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  121971. bHit = bHit1 || bHit2;
  121972. break;
  121973. }
  121974. case FTSQUERY_NOT:
  121975. bHit = (
  121976. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  121977. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  121978. );
  121979. break;
  121980. default: {
  121981. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121982. if( pCsr->pDeferred
  121983. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  121984. ){
  121985. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121986. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  121987. if( pExpr->bDeferred ){
  121988. fts3EvalInvalidatePoslist(pPhrase);
  121989. }
  121990. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  121991. bHit = (pPhrase->doclist.pList!=0);
  121992. pExpr->iDocid = pCsr->iPrevId;
  121993. }else
  121994. #endif
  121995. {
  121996. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  121997. }
  121998. break;
  121999. }
  122000. }
  122001. }
  122002. return bHit;
  122003. }
  122004. /*
  122005. ** This function is called as the second part of each xNext operation when
  122006. ** iterating through the results of a full-text query. At this point the
  122007. ** cursor points to a row that matches the query expression, with the
  122008. ** following caveats:
  122009. **
  122010. ** * Up until this point, "NEAR" operators in the expression have been
  122011. ** treated as "AND".
  122012. **
  122013. ** * Deferred tokens have not yet been considered.
  122014. **
  122015. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  122016. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  122017. ** operators and deferred tokens the current row is still a match for the
  122018. ** expression. It returns 1 if both of the following are true:
  122019. **
  122020. ** 1. *pRc is SQLITE_OK when this function returns, and
  122021. **
  122022. ** 2. After scanning the current FTS table row for the deferred tokens,
  122023. ** it is determined that the row does *not* match the query.
  122024. **
  122025. ** Or, if no error occurs and it seems the current row does match the FTS
  122026. ** query, return 0.
  122027. */
  122028. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  122029. int rc = *pRc;
  122030. int bMiss = 0;
  122031. if( rc==SQLITE_OK ){
  122032. /* If there are one or more deferred tokens, load the current row into
  122033. ** memory and scan it to determine the position list for each deferred
  122034. ** token. Then, see if this row is really a match, considering deferred
  122035. ** tokens and NEAR operators (neither of which were taken into account
  122036. ** earlier, by fts3EvalNextRow()).
  122037. */
  122038. if( pCsr->pDeferred ){
  122039. rc = fts3CursorSeek(0, pCsr);
  122040. if( rc==SQLITE_OK ){
  122041. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  122042. }
  122043. }
  122044. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  122045. /* Free the position-lists accumulated for each deferred token above. */
  122046. sqlite3Fts3FreeDeferredDoclists(pCsr);
  122047. *pRc = rc;
  122048. }
  122049. return (rc==SQLITE_OK && bMiss);
  122050. }
  122051. /*
  122052. ** Advance to the next document that matches the FTS expression in
  122053. ** Fts3Cursor.pExpr.
  122054. */
  122055. static int fts3EvalNext(Fts3Cursor *pCsr){
  122056. int rc = SQLITE_OK; /* Return Code */
  122057. Fts3Expr *pExpr = pCsr->pExpr;
  122058. assert( pCsr->isEof==0 );
  122059. if( pExpr==0 ){
  122060. pCsr->isEof = 1;
  122061. }else{
  122062. do {
  122063. if( pCsr->isRequireSeek==0 ){
  122064. sqlite3_reset(pCsr->pStmt);
  122065. }
  122066. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  122067. fts3EvalNextRow(pCsr, pExpr, &rc);
  122068. pCsr->isEof = pExpr->bEof;
  122069. pCsr->isRequireSeek = 1;
  122070. pCsr->isMatchinfoNeeded = 1;
  122071. pCsr->iPrevId = pExpr->iDocid;
  122072. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  122073. }
  122074. /* Check if the cursor is past the end of the docid range specified
  122075. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  122076. if( rc==SQLITE_OK && (
  122077. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  122078. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  122079. )){
  122080. pCsr->isEof = 1;
  122081. }
  122082. return rc;
  122083. }
  122084. /*
  122085. ** Restart interation for expression pExpr so that the next call to
  122086. ** fts3EvalNext() visits the first row. Do not allow incremental
  122087. ** loading or merging of phrase doclists for this iteration.
  122088. **
  122089. ** If *pRc is other than SQLITE_OK when this function is called, it is
  122090. ** a no-op. If an error occurs within this function, *pRc is set to an
  122091. ** SQLite error code before returning.
  122092. */
  122093. static void fts3EvalRestart(
  122094. Fts3Cursor *pCsr,
  122095. Fts3Expr *pExpr,
  122096. int *pRc
  122097. ){
  122098. if( pExpr && *pRc==SQLITE_OK ){
  122099. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122100. if( pPhrase ){
  122101. fts3EvalInvalidatePoslist(pPhrase);
  122102. if( pPhrase->bIncr ){
  122103. int i;
  122104. for(i=0; i<pPhrase->nToken; i++){
  122105. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  122106. assert( pToken->pDeferred==0 );
  122107. if( pToken->pSegcsr ){
  122108. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  122109. }
  122110. }
  122111. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  122112. }
  122113. pPhrase->doclist.pNextDocid = 0;
  122114. pPhrase->doclist.iDocid = 0;
  122115. }
  122116. pExpr->iDocid = 0;
  122117. pExpr->bEof = 0;
  122118. pExpr->bStart = 0;
  122119. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  122120. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  122121. }
  122122. }
  122123. /*
  122124. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  122125. ** expression rooted at pExpr, the cursor iterates through all rows matched
  122126. ** by pExpr, calling this function for each row. This function increments
  122127. ** the values in Fts3Expr.aMI[] according to the position-list currently
  122128. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  122129. ** expression nodes.
  122130. */
  122131. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  122132. if( pExpr ){
  122133. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122134. if( pPhrase && pPhrase->doclist.pList ){
  122135. int iCol = 0;
  122136. char *p = pPhrase->doclist.pList;
  122137. assert( *p );
  122138. while( 1 ){
  122139. u8 c = 0;
  122140. int iCnt = 0;
  122141. while( 0xFE & (*p | c) ){
  122142. if( (c&0x80)==0 ) iCnt++;
  122143. c = *p++ & 0x80;
  122144. }
  122145. /* aMI[iCol*3 + 1] = Number of occurrences
  122146. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  122147. */
  122148. pExpr->aMI[iCol*3 + 1] += iCnt;
  122149. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  122150. if( *p==0x00 ) break;
  122151. p++;
  122152. p += sqlite3Fts3GetVarint32(p, &iCol);
  122153. }
  122154. }
  122155. fts3EvalUpdateCounts(pExpr->pLeft);
  122156. fts3EvalUpdateCounts(pExpr->pRight);
  122157. }
  122158. }
  122159. /*
  122160. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  122161. **
  122162. ** If it is not already allocated and populated, this function allocates and
  122163. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  122164. ** of a NEAR expression, then it also allocates and populates the same array
  122165. ** for all other phrases that are part of the NEAR expression.
  122166. **
  122167. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  122168. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  122169. */
  122170. static int fts3EvalGatherStats(
  122171. Fts3Cursor *pCsr, /* Cursor object */
  122172. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  122173. ){
  122174. int rc = SQLITE_OK; /* Return code */
  122175. assert( pExpr->eType==FTSQUERY_PHRASE );
  122176. if( pExpr->aMI==0 ){
  122177. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122178. Fts3Expr *pRoot; /* Root of NEAR expression */
  122179. Fts3Expr *p; /* Iterator used for several purposes */
  122180. sqlite3_int64 iPrevId = pCsr->iPrevId;
  122181. sqlite3_int64 iDocid;
  122182. u8 bEof;
  122183. /* Find the root of the NEAR expression */
  122184. pRoot = pExpr;
  122185. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  122186. pRoot = pRoot->pParent;
  122187. }
  122188. iDocid = pRoot->iDocid;
  122189. bEof = pRoot->bEof;
  122190. assert( pRoot->bStart );
  122191. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  122192. for(p=pRoot; p; p=p->pLeft){
  122193. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  122194. assert( pE->aMI==0 );
  122195. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  122196. if( !pE->aMI ) return SQLITE_NOMEM;
  122197. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  122198. }
  122199. fts3EvalRestart(pCsr, pRoot, &rc);
  122200. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  122201. do {
  122202. /* Ensure the %_content statement is reset. */
  122203. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  122204. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  122205. /* Advance to the next document */
  122206. fts3EvalNextRow(pCsr, pRoot, &rc);
  122207. pCsr->isEof = pRoot->bEof;
  122208. pCsr->isRequireSeek = 1;
  122209. pCsr->isMatchinfoNeeded = 1;
  122210. pCsr->iPrevId = pRoot->iDocid;
  122211. }while( pCsr->isEof==0
  122212. && pRoot->eType==FTSQUERY_NEAR
  122213. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  122214. );
  122215. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  122216. fts3EvalUpdateCounts(pRoot);
  122217. }
  122218. }
  122219. pCsr->isEof = 0;
  122220. pCsr->iPrevId = iPrevId;
  122221. if( bEof ){
  122222. pRoot->bEof = bEof;
  122223. }else{
  122224. /* Caution: pRoot may iterate through docids in ascending or descending
  122225. ** order. For this reason, even though it seems more defensive, the
  122226. ** do loop can not be written:
  122227. **
  122228. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  122229. */
  122230. fts3EvalRestart(pCsr, pRoot, &rc);
  122231. do {
  122232. fts3EvalNextRow(pCsr, pRoot, &rc);
  122233. assert( pRoot->bEof==0 );
  122234. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  122235. fts3EvalTestDeferredAndNear(pCsr, &rc);
  122236. }
  122237. }
  122238. return rc;
  122239. }
  122240. /*
  122241. ** This function is used by the matchinfo() module to query a phrase
  122242. ** expression node for the following information:
  122243. **
  122244. ** 1. The total number of occurrences of the phrase in each column of
  122245. ** the FTS table (considering all rows), and
  122246. **
  122247. ** 2. For each column, the number of rows in the table for which the
  122248. ** column contains at least one instance of the phrase.
  122249. **
  122250. ** If no error occurs, SQLITE_OK is returned and the values for each column
  122251. ** written into the array aiOut as follows:
  122252. **
  122253. ** aiOut[iCol*3 + 1] = Number of occurrences
  122254. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  122255. **
  122256. ** Caveats:
  122257. **
  122258. ** * If a phrase consists entirely of deferred tokens, then all output
  122259. ** values are set to the number of documents in the table. In other
  122260. ** words we assume that very common tokens occur exactly once in each
  122261. ** column of each row of the table.
  122262. **
  122263. ** * If a phrase contains some deferred tokens (and some non-deferred
  122264. ** tokens), count the potential occurrence identified by considering
  122265. ** the non-deferred tokens instead of actual phrase occurrences.
  122266. **
  122267. ** * If the phrase is part of a NEAR expression, then only phrase instances
  122268. ** that meet the NEAR constraint are included in the counts.
  122269. */
  122270. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  122271. Fts3Cursor *pCsr, /* FTS cursor handle */
  122272. Fts3Expr *pExpr, /* Phrase expression */
  122273. u32 *aiOut /* Array to write results into (see above) */
  122274. ){
  122275. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122276. int rc = SQLITE_OK;
  122277. int iCol;
  122278. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  122279. assert( pCsr->nDoc>0 );
  122280. for(iCol=0; iCol<pTab->nColumn; iCol++){
  122281. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  122282. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  122283. }
  122284. }else{
  122285. rc = fts3EvalGatherStats(pCsr, pExpr);
  122286. if( rc==SQLITE_OK ){
  122287. assert( pExpr->aMI );
  122288. for(iCol=0; iCol<pTab->nColumn; iCol++){
  122289. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  122290. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  122291. }
  122292. }
  122293. }
  122294. return rc;
  122295. }
  122296. /*
  122297. ** The expression pExpr passed as the second argument to this function
  122298. ** must be of type FTSQUERY_PHRASE.
  122299. **
  122300. ** The returned value is either NULL or a pointer to a buffer containing
  122301. ** a position-list indicating the occurrences of the phrase in column iCol
  122302. ** of the current row.
  122303. **
  122304. ** More specifically, the returned buffer contains 1 varint for each
  122305. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  122306. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  122307. ** if the requested column contains "a b X c d X X" and the position-list
  122308. ** for 'X' is requested, the buffer returned may contain:
  122309. **
  122310. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  122311. **
  122312. ** This function works regardless of whether or not the phrase is deferred,
  122313. ** incremental, or neither.
  122314. */
  122315. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  122316. Fts3Cursor *pCsr, /* FTS3 cursor object */
  122317. Fts3Expr *pExpr, /* Phrase to return doclist for */
  122318. int iCol, /* Column to return position list for */
  122319. char **ppOut /* OUT: Pointer to position list */
  122320. ){
  122321. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122322. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122323. char *pIter;
  122324. int iThis;
  122325. sqlite3_int64 iDocid;
  122326. /* If this phrase is applies specifically to some column other than
  122327. ** column iCol, return a NULL pointer. */
  122328. *ppOut = 0;
  122329. assert( iCol>=0 && iCol<pTab->nColumn );
  122330. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  122331. return SQLITE_OK;
  122332. }
  122333. iDocid = pExpr->iDocid;
  122334. pIter = pPhrase->doclist.pList;
  122335. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  122336. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  122337. int iMul; /* +1 if csr dir matches index dir, else -1 */
  122338. int bOr = 0;
  122339. u8 bEof = 0;
  122340. u8 bTreeEof = 0;
  122341. Fts3Expr *p; /* Used to iterate from pExpr to root */
  122342. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  122343. /* Check if this phrase descends from an OR expression node. If not,
  122344. ** return NULL. Otherwise, the entry that corresponds to docid
  122345. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  122346. ** tree that the node is part of has been marked as EOF, but the node
  122347. ** itself is not EOF, then it may point to an earlier entry. */
  122348. pNear = pExpr;
  122349. for(p=pExpr->pParent; p; p=p->pParent){
  122350. if( p->eType==FTSQUERY_OR ) bOr = 1;
  122351. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  122352. if( p->bEof ) bTreeEof = 1;
  122353. }
  122354. if( bOr==0 ) return SQLITE_OK;
  122355. /* This is the descendent of an OR node. In this case we cannot use
  122356. ** an incremental phrase. Load the entire doclist for the phrase
  122357. ** into memory in this case. */
  122358. if( pPhrase->bIncr ){
  122359. int rc = SQLITE_OK;
  122360. int bEofSave = pExpr->bEof;
  122361. fts3EvalRestart(pCsr, pExpr, &rc);
  122362. while( rc==SQLITE_OK && !pExpr->bEof ){
  122363. fts3EvalNextRow(pCsr, pExpr, &rc);
  122364. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  122365. }
  122366. pIter = pPhrase->doclist.pList;
  122367. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  122368. if( rc!=SQLITE_OK ) return rc;
  122369. }
  122370. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  122371. while( bTreeEof==1
  122372. && pNear->bEof==0
  122373. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  122374. ){
  122375. int rc = SQLITE_OK;
  122376. fts3EvalNextRow(pCsr, pExpr, &rc);
  122377. if( rc!=SQLITE_OK ) return rc;
  122378. iDocid = pExpr->iDocid;
  122379. pIter = pPhrase->doclist.pList;
  122380. }
  122381. bEof = (pPhrase->doclist.nAll==0);
  122382. assert( bDescDoclist==0 || bDescDoclist==1 );
  122383. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  122384. if( bEof==0 ){
  122385. if( pCsr->bDesc==bDescDoclist ){
  122386. int dummy;
  122387. if( pNear->bEof ){
  122388. /* This expression is already at EOF. So position it to point to the
  122389. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  122390. ** iDocid is already set for this entry, so all that is required is
  122391. ** to set pIter to point to the first byte of the last position-list
  122392. ** in the doclist.
  122393. **
  122394. ** It would also be correct to set pIter and iDocid to zero. In
  122395. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  122396. ** would also move the iterator to point to the last entry in the
  122397. ** doclist. However, this is expensive, as to do so it has to
  122398. ** iterate through the entire doclist from start to finish (since
  122399. ** it does not know the docid for the last entry). */
  122400. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  122401. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  122402. }
  122403. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  122404. sqlite3Fts3DoclistPrev(
  122405. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  122406. &pIter, &iDocid, &dummy, &bEof
  122407. );
  122408. }
  122409. }else{
  122410. if( pNear->bEof ){
  122411. pIter = 0;
  122412. iDocid = 0;
  122413. }
  122414. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  122415. sqlite3Fts3DoclistNext(
  122416. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  122417. &pIter, &iDocid, &bEof
  122418. );
  122419. }
  122420. }
  122421. }
  122422. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  122423. }
  122424. if( pIter==0 ) return SQLITE_OK;
  122425. if( *pIter==0x01 ){
  122426. pIter++;
  122427. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  122428. }else{
  122429. iThis = 0;
  122430. }
  122431. while( iThis<iCol ){
  122432. fts3ColumnlistCopy(0, &pIter);
  122433. if( *pIter==0x00 ) return 0;
  122434. pIter++;
  122435. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  122436. }
  122437. *ppOut = ((iCol==iThis)?pIter:0);
  122438. return SQLITE_OK;
  122439. }
  122440. /*
  122441. ** Free all components of the Fts3Phrase structure that were allocated by
  122442. ** the eval module. Specifically, this means to free:
  122443. **
  122444. ** * the contents of pPhrase->doclist, and
  122445. ** * any Fts3MultiSegReader objects held by phrase tokens.
  122446. */
  122447. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  122448. if( pPhrase ){
  122449. int i;
  122450. sqlite3_free(pPhrase->doclist.aAll);
  122451. fts3EvalInvalidatePoslist(pPhrase);
  122452. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  122453. for(i=0; i<pPhrase->nToken; i++){
  122454. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  122455. pPhrase->aToken[i].pSegcsr = 0;
  122456. }
  122457. }
  122458. }
  122459. /*
  122460. ** Return SQLITE_CORRUPT_VTAB.
  122461. */
  122462. #ifdef SQLITE_DEBUG
  122463. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  122464. return SQLITE_CORRUPT_VTAB;
  122465. }
  122466. #endif
  122467. #if !SQLITE_CORE
  122468. /*
  122469. ** Initialize API pointer table, if required.
  122470. */
  122471. #ifdef _WIN32
  122472. __declspec(dllexport)
  122473. #endif
  122474. SQLITE_API int sqlite3_fts3_init(
  122475. sqlite3 *db,
  122476. char **pzErrMsg,
  122477. const sqlite3_api_routines *pApi
  122478. ){
  122479. SQLITE_EXTENSION_INIT2(pApi)
  122480. return sqlite3Fts3Init(db);
  122481. }
  122482. #endif
  122483. #endif
  122484. /************** End of fts3.c ************************************************/
  122485. /************** Begin file fts3_aux.c ****************************************/
  122486. /*
  122487. ** 2011 Jan 27
  122488. **
  122489. ** The author disclaims copyright to this source code. In place of
  122490. ** a legal notice, here is a blessing:
  122491. **
  122492. ** May you do good and not evil.
  122493. ** May you find forgiveness for yourself and forgive others.
  122494. ** May you share freely, never taking more than you give.
  122495. **
  122496. ******************************************************************************
  122497. **
  122498. */
  122499. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122500. /* #include <string.h> */
  122501. /* #include <assert.h> */
  122502. typedef struct Fts3auxTable Fts3auxTable;
  122503. typedef struct Fts3auxCursor Fts3auxCursor;
  122504. struct Fts3auxTable {
  122505. sqlite3_vtab base; /* Base class used by SQLite core */
  122506. Fts3Table *pFts3Tab;
  122507. };
  122508. struct Fts3auxCursor {
  122509. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  122510. Fts3MultiSegReader csr; /* Must be right after "base" */
  122511. Fts3SegFilter filter;
  122512. char *zStop;
  122513. int nStop; /* Byte-length of string zStop */
  122514. int iLangid; /* Language id to query */
  122515. int isEof; /* True if cursor is at EOF */
  122516. sqlite3_int64 iRowid; /* Current rowid */
  122517. int iCol; /* Current value of 'col' column */
  122518. int nStat; /* Size of aStat[] array */
  122519. struct Fts3auxColstats {
  122520. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  122521. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  122522. } *aStat;
  122523. };
  122524. /*
  122525. ** Schema of the terms table.
  122526. */
  122527. #define FTS3_AUX_SCHEMA \
  122528. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  122529. /*
  122530. ** This function does all the work for both the xConnect and xCreate methods.
  122531. ** These tables have no persistent representation of their own, so xConnect
  122532. ** and xCreate are identical operations.
  122533. */
  122534. static int fts3auxConnectMethod(
  122535. sqlite3 *db, /* Database connection */
  122536. void *pUnused, /* Unused */
  122537. int argc, /* Number of elements in argv array */
  122538. const char * const *argv, /* xCreate/xConnect argument array */
  122539. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  122540. char **pzErr /* OUT: sqlite3_malloc'd error message */
  122541. ){
  122542. char const *zDb; /* Name of database (e.g. "main") */
  122543. char const *zFts3; /* Name of fts3 table */
  122544. int nDb; /* Result of strlen(zDb) */
  122545. int nFts3; /* Result of strlen(zFts3) */
  122546. int nByte; /* Bytes of space to allocate here */
  122547. int rc; /* value returned by declare_vtab() */
  122548. Fts3auxTable *p; /* Virtual table object to return */
  122549. UNUSED_PARAMETER(pUnused);
  122550. /* The user should invoke this in one of two forms:
  122551. **
  122552. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  122553. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  122554. */
  122555. if( argc!=4 && argc!=5 ) goto bad_args;
  122556. zDb = argv[1];
  122557. nDb = (int)strlen(zDb);
  122558. if( argc==5 ){
  122559. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  122560. zDb = argv[3];
  122561. nDb = (int)strlen(zDb);
  122562. zFts3 = argv[4];
  122563. }else{
  122564. goto bad_args;
  122565. }
  122566. }else{
  122567. zFts3 = argv[3];
  122568. }
  122569. nFts3 = (int)strlen(zFts3);
  122570. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  122571. if( rc!=SQLITE_OK ) return rc;
  122572. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  122573. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  122574. if( !p ) return SQLITE_NOMEM;
  122575. memset(p, 0, nByte);
  122576. p->pFts3Tab = (Fts3Table *)&p[1];
  122577. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  122578. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  122579. p->pFts3Tab->db = db;
  122580. p->pFts3Tab->nIndex = 1;
  122581. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  122582. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  122583. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  122584. *ppVtab = (sqlite3_vtab *)p;
  122585. return SQLITE_OK;
  122586. bad_args:
  122587. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  122588. return SQLITE_ERROR;
  122589. }
  122590. /*
  122591. ** This function does the work for both the xDisconnect and xDestroy methods.
  122592. ** These tables have no persistent representation of their own, so xDisconnect
  122593. ** and xDestroy are identical operations.
  122594. */
  122595. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  122596. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  122597. Fts3Table *pFts3 = p->pFts3Tab;
  122598. int i;
  122599. /* Free any prepared statements held */
  122600. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  122601. sqlite3_finalize(pFts3->aStmt[i]);
  122602. }
  122603. sqlite3_free(pFts3->zSegmentsTbl);
  122604. sqlite3_free(p);
  122605. return SQLITE_OK;
  122606. }
  122607. #define FTS4AUX_EQ_CONSTRAINT 1
  122608. #define FTS4AUX_GE_CONSTRAINT 2
  122609. #define FTS4AUX_LE_CONSTRAINT 4
  122610. /*
  122611. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  122612. */
  122613. static int fts3auxBestIndexMethod(
  122614. sqlite3_vtab *pVTab,
  122615. sqlite3_index_info *pInfo
  122616. ){
  122617. int i;
  122618. int iEq = -1;
  122619. int iGe = -1;
  122620. int iLe = -1;
  122621. int iLangid = -1;
  122622. int iNext = 1; /* Next free argvIndex value */
  122623. UNUSED_PARAMETER(pVTab);
  122624. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  122625. if( pInfo->nOrderBy==1
  122626. && pInfo->aOrderBy[0].iColumn==0
  122627. && pInfo->aOrderBy[0].desc==0
  122628. ){
  122629. pInfo->orderByConsumed = 1;
  122630. }
  122631. /* Search for equality and range constraints on the "term" column.
  122632. ** And equality constraints on the hidden "languageid" column. */
  122633. for(i=0; i<pInfo->nConstraint; i++){
  122634. if( pInfo->aConstraint[i].usable ){
  122635. int op = pInfo->aConstraint[i].op;
  122636. int iCol = pInfo->aConstraint[i].iColumn;
  122637. if( iCol==0 ){
  122638. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  122639. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  122640. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  122641. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  122642. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  122643. }
  122644. if( iCol==4 ){
  122645. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  122646. }
  122647. }
  122648. }
  122649. if( iEq>=0 ){
  122650. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  122651. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  122652. pInfo->estimatedCost = 5;
  122653. }else{
  122654. pInfo->idxNum = 0;
  122655. pInfo->estimatedCost = 20000;
  122656. if( iGe>=0 ){
  122657. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  122658. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  122659. pInfo->estimatedCost /= 2;
  122660. }
  122661. if( iLe>=0 ){
  122662. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  122663. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  122664. pInfo->estimatedCost /= 2;
  122665. }
  122666. }
  122667. if( iLangid>=0 ){
  122668. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  122669. pInfo->estimatedCost--;
  122670. }
  122671. return SQLITE_OK;
  122672. }
  122673. /*
  122674. ** xOpen - Open a cursor.
  122675. */
  122676. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  122677. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  122678. UNUSED_PARAMETER(pVTab);
  122679. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  122680. if( !pCsr ) return SQLITE_NOMEM;
  122681. memset(pCsr, 0, sizeof(Fts3auxCursor));
  122682. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  122683. return SQLITE_OK;
  122684. }
  122685. /*
  122686. ** xClose - Close a cursor.
  122687. */
  122688. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  122689. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122690. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122691. sqlite3Fts3SegmentsClose(pFts3);
  122692. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  122693. sqlite3_free((void *)pCsr->filter.zTerm);
  122694. sqlite3_free(pCsr->zStop);
  122695. sqlite3_free(pCsr->aStat);
  122696. sqlite3_free(pCsr);
  122697. return SQLITE_OK;
  122698. }
  122699. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  122700. if( nSize>pCsr->nStat ){
  122701. struct Fts3auxColstats *aNew;
  122702. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  122703. sizeof(struct Fts3auxColstats) * nSize
  122704. );
  122705. if( aNew==0 ) return SQLITE_NOMEM;
  122706. memset(&aNew[pCsr->nStat], 0,
  122707. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  122708. );
  122709. pCsr->aStat = aNew;
  122710. pCsr->nStat = nSize;
  122711. }
  122712. return SQLITE_OK;
  122713. }
  122714. /*
  122715. ** xNext - Advance the cursor to the next row, if any.
  122716. */
  122717. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  122718. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122719. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122720. int rc;
  122721. /* Increment our pretend rowid value. */
  122722. pCsr->iRowid++;
  122723. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  122724. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  122725. }
  122726. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  122727. if( rc==SQLITE_ROW ){
  122728. int i = 0;
  122729. int nDoclist = pCsr->csr.nDoclist;
  122730. char *aDoclist = pCsr->csr.aDoclist;
  122731. int iCol;
  122732. int eState = 0;
  122733. if( pCsr->zStop ){
  122734. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  122735. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  122736. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  122737. pCsr->isEof = 1;
  122738. return SQLITE_OK;
  122739. }
  122740. }
  122741. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  122742. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  122743. iCol = 0;
  122744. while( i<nDoclist ){
  122745. sqlite3_int64 v = 0;
  122746. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  122747. switch( eState ){
  122748. /* State 0. In this state the integer just read was a docid. */
  122749. case 0:
  122750. pCsr->aStat[0].nDoc++;
  122751. eState = 1;
  122752. iCol = 0;
  122753. break;
  122754. /* State 1. In this state we are expecting either a 1, indicating
  122755. ** that the following integer will be a column number, or the
  122756. ** start of a position list for column 0.
  122757. **
  122758. ** The only difference between state 1 and state 2 is that if the
  122759. ** integer encountered in state 1 is not 0 or 1, then we need to
  122760. ** increment the column 0 "nDoc" count for this term.
  122761. */
  122762. case 1:
  122763. assert( iCol==0 );
  122764. if( v>1 ){
  122765. pCsr->aStat[1].nDoc++;
  122766. }
  122767. eState = 2;
  122768. /* fall through */
  122769. case 2:
  122770. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  122771. eState = 0;
  122772. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  122773. eState = 3;
  122774. }else{ /* 2 or greater. A position. */
  122775. pCsr->aStat[iCol+1].nOcc++;
  122776. pCsr->aStat[0].nOcc++;
  122777. }
  122778. break;
  122779. /* State 3. The integer just read is a column number. */
  122780. default: assert( eState==3 );
  122781. iCol = (int)v;
  122782. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  122783. pCsr->aStat[iCol+1].nDoc++;
  122784. eState = 2;
  122785. break;
  122786. }
  122787. }
  122788. pCsr->iCol = 0;
  122789. rc = SQLITE_OK;
  122790. }else{
  122791. pCsr->isEof = 1;
  122792. }
  122793. return rc;
  122794. }
  122795. /*
  122796. ** xFilter - Initialize a cursor to point at the start of its data.
  122797. */
  122798. static int fts3auxFilterMethod(
  122799. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  122800. int idxNum, /* Strategy index */
  122801. const char *idxStr, /* Unused */
  122802. int nVal, /* Number of elements in apVal */
  122803. sqlite3_value **apVal /* Arguments for the indexing scheme */
  122804. ){
  122805. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122806. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122807. int rc;
  122808. int isScan = 0;
  122809. int iLangVal = 0; /* Language id to query */
  122810. int iEq = -1; /* Index of term=? value in apVal */
  122811. int iGe = -1; /* Index of term>=? value in apVal */
  122812. int iLe = -1; /* Index of term<=? value in apVal */
  122813. int iLangid = -1; /* Index of languageid=? value in apVal */
  122814. int iNext = 0;
  122815. UNUSED_PARAMETER(nVal);
  122816. UNUSED_PARAMETER(idxStr);
  122817. assert( idxStr==0 );
  122818. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  122819. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  122820. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  122821. );
  122822. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  122823. iEq = iNext++;
  122824. }else{
  122825. isScan = 1;
  122826. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  122827. iGe = iNext++;
  122828. }
  122829. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  122830. iLe = iNext++;
  122831. }
  122832. }
  122833. if( iNext<nVal ){
  122834. iLangid = iNext++;
  122835. }
  122836. /* In case this cursor is being reused, close and zero it. */
  122837. testcase(pCsr->filter.zTerm);
  122838. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  122839. sqlite3_free((void *)pCsr->filter.zTerm);
  122840. sqlite3_free(pCsr->aStat);
  122841. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  122842. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  122843. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  122844. if( iEq>=0 || iGe>=0 ){
  122845. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  122846. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  122847. if( zStr ){
  122848. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  122849. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  122850. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  122851. }
  122852. }
  122853. if( iLe>=0 ){
  122854. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  122855. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  122856. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  122857. }
  122858. if( iLangid>=0 ){
  122859. iLangVal = sqlite3_value_int(apVal[iLangid]);
  122860. /* If the user specified a negative value for the languageid, use zero
  122861. ** instead. This works, as the "languageid=?" constraint will also
  122862. ** be tested by the VDBE layer. The test will always be false (since
  122863. ** this module will not return a row with a negative languageid), and
  122864. ** so the overall query will return zero rows. */
  122865. if( iLangVal<0 ) iLangVal = 0;
  122866. }
  122867. pCsr->iLangid = iLangVal;
  122868. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  122869. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  122870. );
  122871. if( rc==SQLITE_OK ){
  122872. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  122873. }
  122874. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  122875. return rc;
  122876. }
  122877. /*
  122878. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  122879. */
  122880. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  122881. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122882. return pCsr->isEof;
  122883. }
  122884. /*
  122885. ** xColumn - Return a column value.
  122886. */
  122887. static int fts3auxColumnMethod(
  122888. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  122889. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  122890. int iCol /* Index of column to read value from */
  122891. ){
  122892. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  122893. assert( p->isEof==0 );
  122894. switch( iCol ){
  122895. case 0: /* term */
  122896. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  122897. break;
  122898. case 1: /* col */
  122899. if( p->iCol ){
  122900. sqlite3_result_int(pCtx, p->iCol-1);
  122901. }else{
  122902. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  122903. }
  122904. break;
  122905. case 2: /* documents */
  122906. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  122907. break;
  122908. case 3: /* occurrences */
  122909. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  122910. break;
  122911. default: /* languageid */
  122912. assert( iCol==4 );
  122913. sqlite3_result_int(pCtx, p->iLangid);
  122914. break;
  122915. }
  122916. return SQLITE_OK;
  122917. }
  122918. /*
  122919. ** xRowid - Return the current rowid for the cursor.
  122920. */
  122921. static int fts3auxRowidMethod(
  122922. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  122923. sqlite_int64 *pRowid /* OUT: Rowid value */
  122924. ){
  122925. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122926. *pRowid = pCsr->iRowid;
  122927. return SQLITE_OK;
  122928. }
  122929. /*
  122930. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  122931. ** if successful or an error code if sqlite3_create_module() fails.
  122932. */
  122933. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  122934. static const sqlite3_module fts3aux_module = {
  122935. 0, /* iVersion */
  122936. fts3auxConnectMethod, /* xCreate */
  122937. fts3auxConnectMethod, /* xConnect */
  122938. fts3auxBestIndexMethod, /* xBestIndex */
  122939. fts3auxDisconnectMethod, /* xDisconnect */
  122940. fts3auxDisconnectMethod, /* xDestroy */
  122941. fts3auxOpenMethod, /* xOpen */
  122942. fts3auxCloseMethod, /* xClose */
  122943. fts3auxFilterMethod, /* xFilter */
  122944. fts3auxNextMethod, /* xNext */
  122945. fts3auxEofMethod, /* xEof */
  122946. fts3auxColumnMethod, /* xColumn */
  122947. fts3auxRowidMethod, /* xRowid */
  122948. 0, /* xUpdate */
  122949. 0, /* xBegin */
  122950. 0, /* xSync */
  122951. 0, /* xCommit */
  122952. 0, /* xRollback */
  122953. 0, /* xFindFunction */
  122954. 0, /* xRename */
  122955. 0, /* xSavepoint */
  122956. 0, /* xRelease */
  122957. 0 /* xRollbackTo */
  122958. };
  122959. int rc; /* Return code */
  122960. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  122961. return rc;
  122962. }
  122963. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  122964. /************** End of fts3_aux.c ********************************************/
  122965. /************** Begin file fts3_expr.c ***************************************/
  122966. /*
  122967. ** 2008 Nov 28
  122968. **
  122969. ** The author disclaims copyright to this source code. In place of
  122970. ** a legal notice, here is a blessing:
  122971. **
  122972. ** May you do good and not evil.
  122973. ** May you find forgiveness for yourself and forgive others.
  122974. ** May you share freely, never taking more than you give.
  122975. **
  122976. ******************************************************************************
  122977. **
  122978. ** This module contains code that implements a parser for fts3 query strings
  122979. ** (the right-hand argument to the MATCH operator). Because the supported
  122980. ** syntax is relatively simple, the whole tokenizer/parser system is
  122981. ** hand-coded.
  122982. */
  122983. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122984. /*
  122985. ** By default, this module parses the legacy syntax that has been
  122986. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  122987. ** is defined, then it uses the new syntax. The differences between
  122988. ** the new and the old syntaxes are:
  122989. **
  122990. ** a) The new syntax supports parenthesis. The old does not.
  122991. **
  122992. ** b) The new syntax supports the AND and NOT operators. The old does not.
  122993. **
  122994. ** c) The old syntax supports the "-" token qualifier. This is not
  122995. ** supported by the new syntax (it is replaced by the NOT operator).
  122996. **
  122997. ** d) When using the old syntax, the OR operator has a greater precedence
  122998. ** than an implicit AND. When using the new, both implicity and explicit
  122999. ** AND operators have a higher precedence than OR.
  123000. **
  123001. ** If compiled with SQLITE_TEST defined, then this module exports the
  123002. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  123003. ** to zero causes the module to use the old syntax. If it is set to
  123004. ** non-zero the new syntax is activated. This is so both syntaxes can
  123005. ** be tested using a single build of testfixture.
  123006. **
  123007. ** The following describes the syntax supported by the fts3 MATCH
  123008. ** operator in a similar format to that used by the lemon parser
  123009. ** generator. This module does not use actually lemon, it uses a
  123010. ** custom parser.
  123011. **
  123012. ** query ::= andexpr (OR andexpr)*.
  123013. **
  123014. ** andexpr ::= notexpr (AND? notexpr)*.
  123015. **
  123016. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  123017. ** notexpr ::= LP query RP.
  123018. **
  123019. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  123020. **
  123021. ** distance_opt ::= .
  123022. ** distance_opt ::= / INTEGER.
  123023. **
  123024. ** phrase ::= TOKEN.
  123025. ** phrase ::= COLUMN:TOKEN.
  123026. ** phrase ::= "TOKEN TOKEN TOKEN...".
  123027. */
  123028. #ifdef SQLITE_TEST
  123029. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  123030. #else
  123031. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  123032. # define sqlite3_fts3_enable_parentheses 1
  123033. # else
  123034. # define sqlite3_fts3_enable_parentheses 0
  123035. # endif
  123036. #endif
  123037. /*
  123038. ** Default span for NEAR operators.
  123039. */
  123040. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  123041. /* #include <string.h> */
  123042. /* #include <assert.h> */
  123043. /*
  123044. ** isNot:
  123045. ** This variable is used by function getNextNode(). When getNextNode() is
  123046. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  123047. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  123048. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  123049. ** zero.
  123050. */
  123051. typedef struct ParseContext ParseContext;
  123052. struct ParseContext {
  123053. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  123054. int iLangid; /* Language id used with tokenizer */
  123055. const char **azCol; /* Array of column names for fts3 table */
  123056. int bFts4; /* True to allow FTS4-only syntax */
  123057. int nCol; /* Number of entries in azCol[] */
  123058. int iDefaultCol; /* Default column to query */
  123059. int isNot; /* True if getNextNode() sees a unary - */
  123060. sqlite3_context *pCtx; /* Write error message here */
  123061. int nNest; /* Number of nested brackets */
  123062. };
  123063. /*
  123064. ** This function is equivalent to the standard isspace() function.
  123065. **
  123066. ** The standard isspace() can be awkward to use safely, because although it
  123067. ** is defined to accept an argument of type int, its behavior when passed
  123068. ** an integer that falls outside of the range of the unsigned char type
  123069. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  123070. ** is defined to accept an argument of type char, and always returns 0 for
  123071. ** any values that fall outside of the range of the unsigned char type (i.e.
  123072. ** negative values).
  123073. */
  123074. static int fts3isspace(char c){
  123075. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  123076. }
  123077. /*
  123078. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  123079. ** zero the memory before returning a pointer to it. If unsuccessful,
  123080. ** return NULL.
  123081. */
  123082. static void *fts3MallocZero(int nByte){
  123083. void *pRet = sqlite3_malloc(nByte);
  123084. if( pRet ) memset(pRet, 0, nByte);
  123085. return pRet;
  123086. }
  123087. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  123088. sqlite3_tokenizer *pTokenizer,
  123089. int iLangid,
  123090. const char *z,
  123091. int n,
  123092. sqlite3_tokenizer_cursor **ppCsr
  123093. ){
  123094. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123095. sqlite3_tokenizer_cursor *pCsr = 0;
  123096. int rc;
  123097. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  123098. assert( rc==SQLITE_OK || pCsr==0 );
  123099. if( rc==SQLITE_OK ){
  123100. pCsr->pTokenizer = pTokenizer;
  123101. if( pModule->iVersion>=1 ){
  123102. rc = pModule->xLanguageid(pCsr, iLangid);
  123103. if( rc!=SQLITE_OK ){
  123104. pModule->xClose(pCsr);
  123105. pCsr = 0;
  123106. }
  123107. }
  123108. }
  123109. *ppCsr = pCsr;
  123110. return rc;
  123111. }
  123112. /*
  123113. ** Extract the next token from buffer z (length n) using the tokenizer
  123114. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  123115. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  123116. ** single token and set *ppExpr to point to it. If the end of the buffer is
  123117. ** reached before a token is found, set *ppExpr to zero. It is the
  123118. ** responsibility of the caller to eventually deallocate the allocated
  123119. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  123120. **
  123121. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  123122. ** fails.
  123123. */
  123124. static int getNextToken(
  123125. ParseContext *pParse, /* fts3 query parse context */
  123126. int iCol, /* Value for Fts3Phrase.iColumn */
  123127. const char *z, int n, /* Input string */
  123128. Fts3Expr **ppExpr, /* OUT: expression */
  123129. int *pnConsumed /* OUT: Number of bytes consumed */
  123130. ){
  123131. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  123132. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123133. int rc;
  123134. sqlite3_tokenizer_cursor *pCursor;
  123135. Fts3Expr *pRet = 0;
  123136. int nConsumed = 0;
  123137. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  123138. if( rc==SQLITE_OK ){
  123139. const char *zToken;
  123140. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  123141. int nByte; /* total space to allocate */
  123142. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  123143. if( rc==SQLITE_OK ){
  123144. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  123145. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  123146. if( !pRet ){
  123147. rc = SQLITE_NOMEM;
  123148. }else{
  123149. pRet->eType = FTSQUERY_PHRASE;
  123150. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  123151. pRet->pPhrase->nToken = 1;
  123152. pRet->pPhrase->iColumn = iCol;
  123153. pRet->pPhrase->aToken[0].n = nToken;
  123154. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  123155. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  123156. if( iEnd<n && z[iEnd]=='*' ){
  123157. pRet->pPhrase->aToken[0].isPrefix = 1;
  123158. iEnd++;
  123159. }
  123160. while( 1 ){
  123161. if( !sqlite3_fts3_enable_parentheses
  123162. && iStart>0 && z[iStart-1]=='-'
  123163. ){
  123164. pParse->isNot = 1;
  123165. iStart--;
  123166. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  123167. pRet->pPhrase->aToken[0].bFirst = 1;
  123168. iStart--;
  123169. }else{
  123170. break;
  123171. }
  123172. }
  123173. }
  123174. nConsumed = iEnd;
  123175. }
  123176. pModule->xClose(pCursor);
  123177. }
  123178. *pnConsumed = nConsumed;
  123179. *ppExpr = pRet;
  123180. return rc;
  123181. }
  123182. /*
  123183. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  123184. ** then free the old allocation.
  123185. */
  123186. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  123187. void *pRet = sqlite3_realloc(pOrig, nNew);
  123188. if( !pRet ){
  123189. sqlite3_free(pOrig);
  123190. }
  123191. return pRet;
  123192. }
  123193. /*
  123194. ** Buffer zInput, length nInput, contains the contents of a quoted string
  123195. ** that appeared as part of an fts3 query expression. Neither quote character
  123196. ** is included in the buffer. This function attempts to tokenize the entire
  123197. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  123198. ** containing the results.
  123199. **
  123200. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  123201. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  123202. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  123203. ** to 0.
  123204. */
  123205. static int getNextString(
  123206. ParseContext *pParse, /* fts3 query parse context */
  123207. const char *zInput, int nInput, /* Input string */
  123208. Fts3Expr **ppExpr /* OUT: expression */
  123209. ){
  123210. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  123211. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123212. int rc;
  123213. Fts3Expr *p = 0;
  123214. sqlite3_tokenizer_cursor *pCursor = 0;
  123215. char *zTemp = 0;
  123216. int nTemp = 0;
  123217. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  123218. int nToken = 0;
  123219. /* The final Fts3Expr data structure, including the Fts3Phrase,
  123220. ** Fts3PhraseToken structures token buffers are all stored as a single
  123221. ** allocation so that the expression can be freed with a single call to
  123222. ** sqlite3_free(). Setting this up requires a two pass approach.
  123223. **
  123224. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  123225. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  123226. ** to assemble data in two dynamic buffers:
  123227. **
  123228. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  123229. ** structure, followed by the array of Fts3PhraseToken
  123230. ** structures. This pass only populates the Fts3PhraseToken array.
  123231. **
  123232. ** Buffer zTemp: Contains copies of all tokens.
  123233. **
  123234. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  123235. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  123236. ** structures.
  123237. */
  123238. rc = sqlite3Fts3OpenTokenizer(
  123239. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  123240. if( rc==SQLITE_OK ){
  123241. int ii;
  123242. for(ii=0; rc==SQLITE_OK; ii++){
  123243. const char *zByte;
  123244. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  123245. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  123246. if( rc==SQLITE_OK ){
  123247. Fts3PhraseToken *pToken;
  123248. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  123249. if( !p ) goto no_mem;
  123250. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  123251. if( !zTemp ) goto no_mem;
  123252. assert( nToken==ii );
  123253. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  123254. memset(pToken, 0, sizeof(Fts3PhraseToken));
  123255. memcpy(&zTemp[nTemp], zByte, nByte);
  123256. nTemp += nByte;
  123257. pToken->n = nByte;
  123258. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  123259. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  123260. nToken = ii+1;
  123261. }
  123262. }
  123263. pModule->xClose(pCursor);
  123264. pCursor = 0;
  123265. }
  123266. if( rc==SQLITE_DONE ){
  123267. int jj;
  123268. char *zBuf = 0;
  123269. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  123270. if( !p ) goto no_mem;
  123271. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  123272. p->eType = FTSQUERY_PHRASE;
  123273. p->pPhrase = (Fts3Phrase *)&p[1];
  123274. p->pPhrase->iColumn = pParse->iDefaultCol;
  123275. p->pPhrase->nToken = nToken;
  123276. zBuf = (char *)&p->pPhrase->aToken[nToken];
  123277. if( zTemp ){
  123278. memcpy(zBuf, zTemp, nTemp);
  123279. sqlite3_free(zTemp);
  123280. }else{
  123281. assert( nTemp==0 );
  123282. }
  123283. for(jj=0; jj<p->pPhrase->nToken; jj++){
  123284. p->pPhrase->aToken[jj].z = zBuf;
  123285. zBuf += p->pPhrase->aToken[jj].n;
  123286. }
  123287. rc = SQLITE_OK;
  123288. }
  123289. *ppExpr = p;
  123290. return rc;
  123291. no_mem:
  123292. if( pCursor ){
  123293. pModule->xClose(pCursor);
  123294. }
  123295. sqlite3_free(zTemp);
  123296. sqlite3_free(p);
  123297. *ppExpr = 0;
  123298. return SQLITE_NOMEM;
  123299. }
  123300. /*
  123301. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  123302. ** call fts3ExprParse(). So this forward declaration is required.
  123303. */
  123304. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  123305. /*
  123306. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  123307. ** structure, or set to 0 if the end of the input buffer is reached.
  123308. **
  123309. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  123310. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  123311. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  123312. */
  123313. static int getNextNode(
  123314. ParseContext *pParse, /* fts3 query parse context */
  123315. const char *z, int n, /* Input string */
  123316. Fts3Expr **ppExpr, /* OUT: expression */
  123317. int *pnConsumed /* OUT: Number of bytes consumed */
  123318. ){
  123319. static const struct Fts3Keyword {
  123320. char *z; /* Keyword text */
  123321. unsigned char n; /* Length of the keyword */
  123322. unsigned char parenOnly; /* Only valid in paren mode */
  123323. unsigned char eType; /* Keyword code */
  123324. } aKeyword[] = {
  123325. { "OR" , 2, 0, FTSQUERY_OR },
  123326. { "AND", 3, 1, FTSQUERY_AND },
  123327. { "NOT", 3, 1, FTSQUERY_NOT },
  123328. { "NEAR", 4, 0, FTSQUERY_NEAR }
  123329. };
  123330. int ii;
  123331. int iCol;
  123332. int iColLen;
  123333. int rc;
  123334. Fts3Expr *pRet = 0;
  123335. const char *zInput = z;
  123336. int nInput = n;
  123337. pParse->isNot = 0;
  123338. /* Skip over any whitespace before checking for a keyword, an open or
  123339. ** close bracket, or a quoted string.
  123340. */
  123341. while( nInput>0 && fts3isspace(*zInput) ){
  123342. nInput--;
  123343. zInput++;
  123344. }
  123345. if( nInput==0 ){
  123346. return SQLITE_DONE;
  123347. }
  123348. /* See if we are dealing with a keyword. */
  123349. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  123350. const struct Fts3Keyword *pKey = &aKeyword[ii];
  123351. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  123352. continue;
  123353. }
  123354. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  123355. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  123356. int nKey = pKey->n;
  123357. char cNext;
  123358. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  123359. if( pKey->eType==FTSQUERY_NEAR ){
  123360. assert( nKey==4 );
  123361. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  123362. nNear = 0;
  123363. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  123364. nNear = nNear * 10 + (zInput[nKey] - '0');
  123365. }
  123366. }
  123367. }
  123368. /* At this point this is probably a keyword. But for that to be true,
  123369. ** the next byte must contain either whitespace, an open or close
  123370. ** parenthesis, a quote character, or EOF.
  123371. */
  123372. cNext = zInput[nKey];
  123373. if( fts3isspace(cNext)
  123374. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  123375. ){
  123376. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  123377. if( !pRet ){
  123378. return SQLITE_NOMEM;
  123379. }
  123380. pRet->eType = pKey->eType;
  123381. pRet->nNear = nNear;
  123382. *ppExpr = pRet;
  123383. *pnConsumed = (int)((zInput - z) + nKey);
  123384. return SQLITE_OK;
  123385. }
  123386. /* Turns out that wasn't a keyword after all. This happens if the
  123387. ** user has supplied a token such as "ORacle". Continue.
  123388. */
  123389. }
  123390. }
  123391. /* Check for an open bracket. */
  123392. if( sqlite3_fts3_enable_parentheses ){
  123393. if( *zInput=='(' ){
  123394. int nConsumed;
  123395. pParse->nNest++;
  123396. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  123397. if( rc==SQLITE_OK && !*ppExpr ){
  123398. rc = SQLITE_DONE;
  123399. }
  123400. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  123401. return rc;
  123402. }
  123403. /* Check for a close bracket. */
  123404. if( *zInput==')' ){
  123405. pParse->nNest--;
  123406. *pnConsumed = (int)((zInput - z) + 1);
  123407. return SQLITE_DONE;
  123408. }
  123409. }
  123410. /* See if we are dealing with a quoted phrase. If this is the case, then
  123411. ** search for the closing quote and pass the whole string to getNextString()
  123412. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  123413. ** a quote character embedded in a string.
  123414. */
  123415. if( *zInput=='"' ){
  123416. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  123417. *pnConsumed = (int)((zInput - z) + ii + 1);
  123418. if( ii==nInput ){
  123419. return SQLITE_ERROR;
  123420. }
  123421. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  123422. }
  123423. /* If control flows to this point, this must be a regular token, or
  123424. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  123425. ** interface. Before doing so, figure out if there is an explicit
  123426. ** column specifier for the token.
  123427. **
  123428. ** TODO: Strangely, it is not possible to associate a column specifier
  123429. ** with a quoted phrase, only with a single token. Not sure if this was
  123430. ** an implementation artifact or an intentional decision when fts3 was
  123431. ** first implemented. Whichever it was, this module duplicates the
  123432. ** limitation.
  123433. */
  123434. iCol = pParse->iDefaultCol;
  123435. iColLen = 0;
  123436. for(ii=0; ii<pParse->nCol; ii++){
  123437. const char *zStr = pParse->azCol[ii];
  123438. int nStr = (int)strlen(zStr);
  123439. if( nInput>nStr && zInput[nStr]==':'
  123440. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  123441. ){
  123442. iCol = ii;
  123443. iColLen = (int)((zInput - z) + nStr + 1);
  123444. break;
  123445. }
  123446. }
  123447. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  123448. *pnConsumed += iColLen;
  123449. return rc;
  123450. }
  123451. /*
  123452. ** The argument is an Fts3Expr structure for a binary operator (any type
  123453. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  123454. ** precedence of the operator. Lower values have a higher precedence (i.e.
  123455. ** group more tightly). For example, in the C language, the == operator
  123456. ** groups more tightly than ||, and would therefore have a higher precedence.
  123457. **
  123458. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  123459. ** is defined), the order of the operators in precedence from highest to
  123460. ** lowest is:
  123461. **
  123462. ** NEAR
  123463. ** NOT
  123464. ** AND (including implicit ANDs)
  123465. ** OR
  123466. **
  123467. ** Note that when using the old query syntax, the OR operator has a higher
  123468. ** precedence than the AND operator.
  123469. */
  123470. static int opPrecedence(Fts3Expr *p){
  123471. assert( p->eType!=FTSQUERY_PHRASE );
  123472. if( sqlite3_fts3_enable_parentheses ){
  123473. return p->eType;
  123474. }else if( p->eType==FTSQUERY_NEAR ){
  123475. return 1;
  123476. }else if( p->eType==FTSQUERY_OR ){
  123477. return 2;
  123478. }
  123479. assert( p->eType==FTSQUERY_AND );
  123480. return 3;
  123481. }
  123482. /*
  123483. ** Argument ppHead contains a pointer to the current head of a query
  123484. ** expression tree being parsed. pPrev is the expression node most recently
  123485. ** inserted into the tree. This function adds pNew, which is always a binary
  123486. ** operator node, into the expression tree based on the relative precedence
  123487. ** of pNew and the existing nodes of the tree. This may result in the head
  123488. ** of the tree changing, in which case *ppHead is set to the new root node.
  123489. */
  123490. static void insertBinaryOperator(
  123491. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  123492. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  123493. Fts3Expr *pNew /* New binary node to insert into expression tree */
  123494. ){
  123495. Fts3Expr *pSplit = pPrev;
  123496. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  123497. pSplit = pSplit->pParent;
  123498. }
  123499. if( pSplit->pParent ){
  123500. assert( pSplit->pParent->pRight==pSplit );
  123501. pSplit->pParent->pRight = pNew;
  123502. pNew->pParent = pSplit->pParent;
  123503. }else{
  123504. *ppHead = pNew;
  123505. }
  123506. pNew->pLeft = pSplit;
  123507. pSplit->pParent = pNew;
  123508. }
  123509. /*
  123510. ** Parse the fts3 query expression found in buffer z, length n. This function
  123511. ** returns either when the end of the buffer is reached or an unmatched
  123512. ** closing bracket - ')' - is encountered.
  123513. **
  123514. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  123515. ** parsed form of the expression and *pnConsumed is set to the number of
  123516. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  123517. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  123518. */
  123519. static int fts3ExprParse(
  123520. ParseContext *pParse, /* fts3 query parse context */
  123521. const char *z, int n, /* Text of MATCH query */
  123522. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  123523. int *pnConsumed /* OUT: Number of bytes consumed */
  123524. ){
  123525. Fts3Expr *pRet = 0;
  123526. Fts3Expr *pPrev = 0;
  123527. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  123528. int nIn = n;
  123529. const char *zIn = z;
  123530. int rc = SQLITE_OK;
  123531. int isRequirePhrase = 1;
  123532. while( rc==SQLITE_OK ){
  123533. Fts3Expr *p = 0;
  123534. int nByte = 0;
  123535. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  123536. if( rc==SQLITE_OK ){
  123537. int isPhrase;
  123538. if( !sqlite3_fts3_enable_parentheses
  123539. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  123540. ){
  123541. /* Create an implicit NOT operator. */
  123542. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  123543. if( !pNot ){
  123544. sqlite3Fts3ExprFree(p);
  123545. rc = SQLITE_NOMEM;
  123546. goto exprparse_out;
  123547. }
  123548. pNot->eType = FTSQUERY_NOT;
  123549. pNot->pRight = p;
  123550. p->pParent = pNot;
  123551. if( pNotBranch ){
  123552. pNot->pLeft = pNotBranch;
  123553. pNotBranch->pParent = pNot;
  123554. }
  123555. pNotBranch = pNot;
  123556. p = pPrev;
  123557. }else{
  123558. int eType = p->eType;
  123559. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  123560. /* The isRequirePhrase variable is set to true if a phrase or
  123561. ** an expression contained in parenthesis is required. If a
  123562. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  123563. ** isRequirePhrase is set, this is a syntax error.
  123564. */
  123565. if( !isPhrase && isRequirePhrase ){
  123566. sqlite3Fts3ExprFree(p);
  123567. rc = SQLITE_ERROR;
  123568. goto exprparse_out;
  123569. }
  123570. if( isPhrase && !isRequirePhrase ){
  123571. /* Insert an implicit AND operator. */
  123572. Fts3Expr *pAnd;
  123573. assert( pRet && pPrev );
  123574. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  123575. if( !pAnd ){
  123576. sqlite3Fts3ExprFree(p);
  123577. rc = SQLITE_NOMEM;
  123578. goto exprparse_out;
  123579. }
  123580. pAnd->eType = FTSQUERY_AND;
  123581. insertBinaryOperator(&pRet, pPrev, pAnd);
  123582. pPrev = pAnd;
  123583. }
  123584. /* This test catches attempts to make either operand of a NEAR
  123585. ** operator something other than a phrase. For example, either of
  123586. ** the following:
  123587. **
  123588. ** (bracketed expression) NEAR phrase
  123589. ** phrase NEAR (bracketed expression)
  123590. **
  123591. ** Return an error in either case.
  123592. */
  123593. if( pPrev && (
  123594. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  123595. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  123596. )){
  123597. sqlite3Fts3ExprFree(p);
  123598. rc = SQLITE_ERROR;
  123599. goto exprparse_out;
  123600. }
  123601. if( isPhrase ){
  123602. if( pRet ){
  123603. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  123604. pPrev->pRight = p;
  123605. p->pParent = pPrev;
  123606. }else{
  123607. pRet = p;
  123608. }
  123609. }else{
  123610. insertBinaryOperator(&pRet, pPrev, p);
  123611. }
  123612. isRequirePhrase = !isPhrase;
  123613. }
  123614. assert( nByte>0 );
  123615. }
  123616. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  123617. nIn -= nByte;
  123618. zIn += nByte;
  123619. pPrev = p;
  123620. }
  123621. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  123622. rc = SQLITE_ERROR;
  123623. }
  123624. if( rc==SQLITE_DONE ){
  123625. rc = SQLITE_OK;
  123626. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  123627. if( !pRet ){
  123628. rc = SQLITE_ERROR;
  123629. }else{
  123630. Fts3Expr *pIter = pNotBranch;
  123631. while( pIter->pLeft ){
  123632. pIter = pIter->pLeft;
  123633. }
  123634. pIter->pLeft = pRet;
  123635. pRet->pParent = pIter;
  123636. pRet = pNotBranch;
  123637. }
  123638. }
  123639. }
  123640. *pnConsumed = n - nIn;
  123641. exprparse_out:
  123642. if( rc!=SQLITE_OK ){
  123643. sqlite3Fts3ExprFree(pRet);
  123644. sqlite3Fts3ExprFree(pNotBranch);
  123645. pRet = 0;
  123646. }
  123647. *ppExpr = pRet;
  123648. return rc;
  123649. }
  123650. /*
  123651. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  123652. ** as the only argument is more than nMaxDepth.
  123653. */
  123654. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  123655. int rc = SQLITE_OK;
  123656. if( p ){
  123657. if( nMaxDepth<0 ){
  123658. rc = SQLITE_TOOBIG;
  123659. }else{
  123660. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  123661. if( rc==SQLITE_OK ){
  123662. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  123663. }
  123664. }
  123665. }
  123666. return rc;
  123667. }
  123668. /*
  123669. ** This function attempts to transform the expression tree at (*pp) to
  123670. ** an equivalent but more balanced form. The tree is modified in place.
  123671. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  123672. ** new root expression node.
  123673. **
  123674. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  123675. **
  123676. ** Otherwise, if an error occurs, an SQLite error code is returned and
  123677. ** expression (*pp) freed.
  123678. */
  123679. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  123680. int rc = SQLITE_OK; /* Return code */
  123681. Fts3Expr *pRoot = *pp; /* Initial root node */
  123682. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  123683. int eType = pRoot->eType; /* Type of node in this tree */
  123684. if( nMaxDepth==0 ){
  123685. rc = SQLITE_ERROR;
  123686. }
  123687. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  123688. Fts3Expr **apLeaf;
  123689. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  123690. if( 0==apLeaf ){
  123691. rc = SQLITE_NOMEM;
  123692. }else{
  123693. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  123694. }
  123695. if( rc==SQLITE_OK ){
  123696. int i;
  123697. Fts3Expr *p;
  123698. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  123699. for(p=pRoot; p->eType==eType; p=p->pLeft){
  123700. assert( p->pParent==0 || p->pParent->pLeft==p );
  123701. assert( p->pLeft && p->pRight );
  123702. }
  123703. /* This loop runs once for each leaf in the tree of eType nodes. */
  123704. while( 1 ){
  123705. int iLvl;
  123706. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  123707. assert( pParent==0 || pParent->pLeft==p );
  123708. p->pParent = 0;
  123709. if( pParent ){
  123710. pParent->pLeft = 0;
  123711. }else{
  123712. pRoot = 0;
  123713. }
  123714. rc = fts3ExprBalance(&p, nMaxDepth-1);
  123715. if( rc!=SQLITE_OK ) break;
  123716. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  123717. if( apLeaf[iLvl]==0 ){
  123718. apLeaf[iLvl] = p;
  123719. p = 0;
  123720. }else{
  123721. assert( pFree );
  123722. pFree->pLeft = apLeaf[iLvl];
  123723. pFree->pRight = p;
  123724. pFree->pLeft->pParent = pFree;
  123725. pFree->pRight->pParent = pFree;
  123726. p = pFree;
  123727. pFree = pFree->pParent;
  123728. p->pParent = 0;
  123729. apLeaf[iLvl] = 0;
  123730. }
  123731. }
  123732. if( p ){
  123733. sqlite3Fts3ExprFree(p);
  123734. rc = SQLITE_TOOBIG;
  123735. break;
  123736. }
  123737. /* If that was the last leaf node, break out of the loop */
  123738. if( pParent==0 ) break;
  123739. /* Set $p to point to the next leaf in the tree of eType nodes */
  123740. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  123741. /* Remove pParent from the original tree. */
  123742. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  123743. pParent->pRight->pParent = pParent->pParent;
  123744. if( pParent->pParent ){
  123745. pParent->pParent->pLeft = pParent->pRight;
  123746. }else{
  123747. assert( pParent==pRoot );
  123748. pRoot = pParent->pRight;
  123749. }
  123750. /* Link pParent into the free node list. It will be used as an
  123751. ** internal node of the new tree. */
  123752. pParent->pParent = pFree;
  123753. pFree = pParent;
  123754. }
  123755. if( rc==SQLITE_OK ){
  123756. p = 0;
  123757. for(i=0; i<nMaxDepth; i++){
  123758. if( apLeaf[i] ){
  123759. if( p==0 ){
  123760. p = apLeaf[i];
  123761. p->pParent = 0;
  123762. }else{
  123763. assert( pFree!=0 );
  123764. pFree->pRight = p;
  123765. pFree->pLeft = apLeaf[i];
  123766. pFree->pLeft->pParent = pFree;
  123767. pFree->pRight->pParent = pFree;
  123768. p = pFree;
  123769. pFree = pFree->pParent;
  123770. p->pParent = 0;
  123771. }
  123772. }
  123773. }
  123774. pRoot = p;
  123775. }else{
  123776. /* An error occurred. Delete the contents of the apLeaf[] array
  123777. ** and pFree list. Everything else is cleaned up by the call to
  123778. ** sqlite3Fts3ExprFree(pRoot) below. */
  123779. Fts3Expr *pDel;
  123780. for(i=0; i<nMaxDepth; i++){
  123781. sqlite3Fts3ExprFree(apLeaf[i]);
  123782. }
  123783. while( (pDel=pFree)!=0 ){
  123784. pFree = pDel->pParent;
  123785. sqlite3_free(pDel);
  123786. }
  123787. }
  123788. assert( pFree==0 );
  123789. sqlite3_free( apLeaf );
  123790. }
  123791. }
  123792. if( rc!=SQLITE_OK ){
  123793. sqlite3Fts3ExprFree(pRoot);
  123794. pRoot = 0;
  123795. }
  123796. *pp = pRoot;
  123797. return rc;
  123798. }
  123799. /*
  123800. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  123801. ** differences:
  123802. **
  123803. ** 1. It does not do expression rebalancing.
  123804. ** 2. It does not check that the expression does not exceed the
  123805. ** maximum allowable depth.
  123806. ** 3. Even if it fails, *ppExpr may still be set to point to an
  123807. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  123808. ** in this case.
  123809. */
  123810. static int fts3ExprParseUnbalanced(
  123811. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  123812. int iLangid, /* Language id for tokenizer */
  123813. char **azCol, /* Array of column names for fts3 table */
  123814. int bFts4, /* True to allow FTS4-only syntax */
  123815. int nCol, /* Number of entries in azCol[] */
  123816. int iDefaultCol, /* Default column to query */
  123817. const char *z, int n, /* Text of MATCH query */
  123818. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  123819. ){
  123820. int nParsed;
  123821. int rc;
  123822. ParseContext sParse;
  123823. memset(&sParse, 0, sizeof(ParseContext));
  123824. sParse.pTokenizer = pTokenizer;
  123825. sParse.iLangid = iLangid;
  123826. sParse.azCol = (const char **)azCol;
  123827. sParse.nCol = nCol;
  123828. sParse.iDefaultCol = iDefaultCol;
  123829. sParse.bFts4 = bFts4;
  123830. if( z==0 ){
  123831. *ppExpr = 0;
  123832. return SQLITE_OK;
  123833. }
  123834. if( n<0 ){
  123835. n = (int)strlen(z);
  123836. }
  123837. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  123838. assert( rc==SQLITE_OK || *ppExpr==0 );
  123839. /* Check for mismatched parenthesis */
  123840. if( rc==SQLITE_OK && sParse.nNest ){
  123841. rc = SQLITE_ERROR;
  123842. }
  123843. return rc;
  123844. }
  123845. /*
  123846. ** Parameters z and n contain a pointer to and length of a buffer containing
  123847. ** an fts3 query expression, respectively. This function attempts to parse the
  123848. ** query expression and create a tree of Fts3Expr structures representing the
  123849. ** parsed expression. If successful, *ppExpr is set to point to the head
  123850. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  123851. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  123852. ** error) is returned and *ppExpr is set to 0.
  123853. **
  123854. ** If parameter n is a negative number, then z is assumed to point to a
  123855. ** nul-terminated string and the length is determined using strlen().
  123856. **
  123857. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  123858. ** use to normalize query tokens while parsing the expression. The azCol[]
  123859. ** array, which is assumed to contain nCol entries, should contain the names
  123860. ** of each column in the target fts3 table, in order from left to right.
  123861. ** Column names must be nul-terminated strings.
  123862. **
  123863. ** The iDefaultCol parameter should be passed the index of the table column
  123864. ** that appears on the left-hand-side of the MATCH operator (the default
  123865. ** column to match against for tokens for which a column name is not explicitly
  123866. ** specified as part of the query string), or -1 if tokens may by default
  123867. ** match any table column.
  123868. */
  123869. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  123870. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  123871. int iLangid, /* Language id for tokenizer */
  123872. char **azCol, /* Array of column names for fts3 table */
  123873. int bFts4, /* True to allow FTS4-only syntax */
  123874. int nCol, /* Number of entries in azCol[] */
  123875. int iDefaultCol, /* Default column to query */
  123876. const char *z, int n, /* Text of MATCH query */
  123877. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  123878. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  123879. ){
  123880. int rc = fts3ExprParseUnbalanced(
  123881. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  123882. );
  123883. /* Rebalance the expression. And check that its depth does not exceed
  123884. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  123885. if( rc==SQLITE_OK && *ppExpr ){
  123886. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  123887. if( rc==SQLITE_OK ){
  123888. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  123889. }
  123890. }
  123891. if( rc!=SQLITE_OK ){
  123892. sqlite3Fts3ExprFree(*ppExpr);
  123893. *ppExpr = 0;
  123894. if( rc==SQLITE_TOOBIG ){
  123895. *pzErr = sqlite3_mprintf(
  123896. "FTS expression tree is too large (maximum depth %d)",
  123897. SQLITE_FTS3_MAX_EXPR_DEPTH
  123898. );
  123899. rc = SQLITE_ERROR;
  123900. }else if( rc==SQLITE_ERROR ){
  123901. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  123902. }
  123903. }
  123904. return rc;
  123905. }
  123906. /*
  123907. ** Free a single node of an expression tree.
  123908. */
  123909. static void fts3FreeExprNode(Fts3Expr *p){
  123910. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  123911. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  123912. sqlite3_free(p->aMI);
  123913. sqlite3_free(p);
  123914. }
  123915. /*
  123916. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  123917. **
  123918. ** This function would be simpler if it recursively called itself. But
  123919. ** that would mean passing a sufficiently large expression to ExprParse()
  123920. ** could cause a stack overflow.
  123921. */
  123922. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  123923. Fts3Expr *p;
  123924. assert( pDel==0 || pDel->pParent==0 );
  123925. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  123926. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  123927. }
  123928. while( p ){
  123929. Fts3Expr *pParent = p->pParent;
  123930. fts3FreeExprNode(p);
  123931. if( pParent && p==pParent->pLeft && pParent->pRight ){
  123932. p = pParent->pRight;
  123933. while( p && (p->pLeft || p->pRight) ){
  123934. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  123935. p = (p->pLeft ? p->pLeft : p->pRight);
  123936. }
  123937. }else{
  123938. p = pParent;
  123939. }
  123940. }
  123941. }
  123942. /****************************************************************************
  123943. *****************************************************************************
  123944. ** Everything after this point is just test code.
  123945. */
  123946. #ifdef SQLITE_TEST
  123947. /* #include <stdio.h> */
  123948. /*
  123949. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  123950. */
  123951. static int queryTestTokenizer(
  123952. sqlite3 *db,
  123953. const char *zName,
  123954. const sqlite3_tokenizer_module **pp
  123955. ){
  123956. int rc;
  123957. sqlite3_stmt *pStmt;
  123958. const char zSql[] = "SELECT fts3_tokenizer(?)";
  123959. *pp = 0;
  123960. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  123961. if( rc!=SQLITE_OK ){
  123962. return rc;
  123963. }
  123964. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  123965. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  123966. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  123967. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  123968. }
  123969. }
  123970. return sqlite3_finalize(pStmt);
  123971. }
  123972. /*
  123973. ** Return a pointer to a buffer containing a text representation of the
  123974. ** expression passed as the first argument. The buffer is obtained from
  123975. ** sqlite3_malloc(). It is the responsibility of the caller to use
  123976. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  123977. ** NULL is returned.
  123978. **
  123979. ** If the second argument is not NULL, then its contents are prepended to
  123980. ** the returned expression text and then freed using sqlite3_free().
  123981. */
  123982. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  123983. if( pExpr==0 ){
  123984. return sqlite3_mprintf("");
  123985. }
  123986. switch( pExpr->eType ){
  123987. case FTSQUERY_PHRASE: {
  123988. Fts3Phrase *pPhrase = pExpr->pPhrase;
  123989. int i;
  123990. zBuf = sqlite3_mprintf(
  123991. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  123992. for(i=0; zBuf && i<pPhrase->nToken; i++){
  123993. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  123994. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  123995. (pPhrase->aToken[i].isPrefix?"+":"")
  123996. );
  123997. }
  123998. return zBuf;
  123999. }
  124000. case FTSQUERY_NEAR:
  124001. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  124002. break;
  124003. case FTSQUERY_NOT:
  124004. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  124005. break;
  124006. case FTSQUERY_AND:
  124007. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  124008. break;
  124009. case FTSQUERY_OR:
  124010. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  124011. break;
  124012. }
  124013. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  124014. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  124015. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  124016. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  124017. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  124018. return zBuf;
  124019. }
  124020. /*
  124021. ** This is the implementation of a scalar SQL function used to test the
  124022. ** expression parser. It should be called as follows:
  124023. **
  124024. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  124025. **
  124026. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  124027. ** to parse the query expression (see README.tokenizers). The second argument
  124028. ** is the query expression to parse. Each subsequent argument is the name
  124029. ** of a column of the fts3 table that the query expression may refer to.
  124030. ** For example:
  124031. **
  124032. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  124033. */
  124034. static void fts3ExprTest(
  124035. sqlite3_context *context,
  124036. int argc,
  124037. sqlite3_value **argv
  124038. ){
  124039. sqlite3_tokenizer_module const *pModule = 0;
  124040. sqlite3_tokenizer *pTokenizer = 0;
  124041. int rc;
  124042. char **azCol = 0;
  124043. const char *zExpr;
  124044. int nExpr;
  124045. int nCol;
  124046. int ii;
  124047. Fts3Expr *pExpr;
  124048. char *zBuf = 0;
  124049. sqlite3 *db = sqlite3_context_db_handle(context);
  124050. if( argc<3 ){
  124051. sqlite3_result_error(context,
  124052. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  124053. );
  124054. return;
  124055. }
  124056. rc = queryTestTokenizer(db,
  124057. (const char *)sqlite3_value_text(argv[0]), &pModule);
  124058. if( rc==SQLITE_NOMEM ){
  124059. sqlite3_result_error_nomem(context);
  124060. goto exprtest_out;
  124061. }else if( !pModule ){
  124062. sqlite3_result_error(context, "No such tokenizer module", -1);
  124063. goto exprtest_out;
  124064. }
  124065. rc = pModule->xCreate(0, 0, &pTokenizer);
  124066. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  124067. if( rc==SQLITE_NOMEM ){
  124068. sqlite3_result_error_nomem(context);
  124069. goto exprtest_out;
  124070. }
  124071. pTokenizer->pModule = pModule;
  124072. zExpr = (const char *)sqlite3_value_text(argv[1]);
  124073. nExpr = sqlite3_value_bytes(argv[1]);
  124074. nCol = argc-2;
  124075. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  124076. if( !azCol ){
  124077. sqlite3_result_error_nomem(context);
  124078. goto exprtest_out;
  124079. }
  124080. for(ii=0; ii<nCol; ii++){
  124081. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  124082. }
  124083. if( sqlite3_user_data(context) ){
  124084. char *zDummy = 0;
  124085. rc = sqlite3Fts3ExprParse(
  124086. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  124087. );
  124088. assert( rc==SQLITE_OK || pExpr==0 );
  124089. sqlite3_free(zDummy);
  124090. }else{
  124091. rc = fts3ExprParseUnbalanced(
  124092. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  124093. );
  124094. }
  124095. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  124096. sqlite3Fts3ExprFree(pExpr);
  124097. sqlite3_result_error(context, "Error parsing expression", -1);
  124098. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  124099. sqlite3_result_error_nomem(context);
  124100. }else{
  124101. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  124102. sqlite3_free(zBuf);
  124103. }
  124104. sqlite3Fts3ExprFree(pExpr);
  124105. exprtest_out:
  124106. if( pModule && pTokenizer ){
  124107. rc = pModule->xDestroy(pTokenizer);
  124108. }
  124109. sqlite3_free(azCol);
  124110. }
  124111. /*
  124112. ** Register the query expression parser test function fts3_exprtest()
  124113. ** with database connection db.
  124114. */
  124115. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  124116. int rc = sqlite3_create_function(
  124117. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  124118. );
  124119. if( rc==SQLITE_OK ){
  124120. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  124121. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  124122. );
  124123. }
  124124. return rc;
  124125. }
  124126. #endif
  124127. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124128. /************** End of fts3_expr.c *******************************************/
  124129. /************** Begin file fts3_hash.c ***************************************/
  124130. /*
  124131. ** 2001 September 22
  124132. **
  124133. ** The author disclaims copyright to this source code. In place of
  124134. ** a legal notice, here is a blessing:
  124135. **
  124136. ** May you do good and not evil.
  124137. ** May you find forgiveness for yourself and forgive others.
  124138. ** May you share freely, never taking more than you give.
  124139. **
  124140. *************************************************************************
  124141. ** This is the implementation of generic hash-tables used in SQLite.
  124142. ** We've modified it slightly to serve as a standalone hash table
  124143. ** implementation for the full-text indexing module.
  124144. */
  124145. /*
  124146. ** The code in this file is only compiled if:
  124147. **
  124148. ** * The FTS3 module is being built as an extension
  124149. ** (in which case SQLITE_CORE is not defined), or
  124150. **
  124151. ** * The FTS3 module is being built into the core of
  124152. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  124153. */
  124154. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124155. /* #include <assert.h> */
  124156. /* #include <stdlib.h> */
  124157. /* #include <string.h> */
  124158. /*
  124159. ** Malloc and Free functions
  124160. */
  124161. static void *fts3HashMalloc(int n){
  124162. void *p = sqlite3_malloc(n);
  124163. if( p ){
  124164. memset(p, 0, n);
  124165. }
  124166. return p;
  124167. }
  124168. static void fts3HashFree(void *p){
  124169. sqlite3_free(p);
  124170. }
  124171. /* Turn bulk memory into a hash table object by initializing the
  124172. ** fields of the Hash structure.
  124173. **
  124174. ** "pNew" is a pointer to the hash table that is to be initialized.
  124175. ** keyClass is one of the constants
  124176. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  124177. ** determines what kind of key the hash table will use. "copyKey" is
  124178. ** true if the hash table should make its own private copy of keys and
  124179. ** false if it should just use the supplied pointer.
  124180. */
  124181. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  124182. assert( pNew!=0 );
  124183. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  124184. pNew->keyClass = keyClass;
  124185. pNew->copyKey = copyKey;
  124186. pNew->first = 0;
  124187. pNew->count = 0;
  124188. pNew->htsize = 0;
  124189. pNew->ht = 0;
  124190. }
  124191. /* Remove all entries from a hash table. Reclaim all memory.
  124192. ** Call this routine to delete a hash table or to reset a hash table
  124193. ** to the empty state.
  124194. */
  124195. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  124196. Fts3HashElem *elem; /* For looping over all elements of the table */
  124197. assert( pH!=0 );
  124198. elem = pH->first;
  124199. pH->first = 0;
  124200. fts3HashFree(pH->ht);
  124201. pH->ht = 0;
  124202. pH->htsize = 0;
  124203. while( elem ){
  124204. Fts3HashElem *next_elem = elem->next;
  124205. if( pH->copyKey && elem->pKey ){
  124206. fts3HashFree(elem->pKey);
  124207. }
  124208. fts3HashFree(elem);
  124209. elem = next_elem;
  124210. }
  124211. pH->count = 0;
  124212. }
  124213. /*
  124214. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  124215. */
  124216. static int fts3StrHash(const void *pKey, int nKey){
  124217. const char *z = (const char *)pKey;
  124218. int h = 0;
  124219. if( nKey<=0 ) nKey = (int) strlen(z);
  124220. while( nKey > 0 ){
  124221. h = (h<<3) ^ h ^ *z++;
  124222. nKey--;
  124223. }
  124224. return h & 0x7fffffff;
  124225. }
  124226. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  124227. if( n1!=n2 ) return 1;
  124228. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  124229. }
  124230. /*
  124231. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  124232. */
  124233. static int fts3BinHash(const void *pKey, int nKey){
  124234. int h = 0;
  124235. const char *z = (const char *)pKey;
  124236. while( nKey-- > 0 ){
  124237. h = (h<<3) ^ h ^ *(z++);
  124238. }
  124239. return h & 0x7fffffff;
  124240. }
  124241. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  124242. if( n1!=n2 ) return 1;
  124243. return memcmp(pKey1,pKey2,n1);
  124244. }
  124245. /*
  124246. ** Return a pointer to the appropriate hash function given the key class.
  124247. **
  124248. ** The C syntax in this function definition may be unfamilar to some
  124249. ** programmers, so we provide the following additional explanation:
  124250. **
  124251. ** The name of the function is "ftsHashFunction". The function takes a
  124252. ** single parameter "keyClass". The return value of ftsHashFunction()
  124253. ** is a pointer to another function. Specifically, the return value
  124254. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  124255. ** with types "const void*" and "int" and returns an "int".
  124256. */
  124257. static int (*ftsHashFunction(int keyClass))(const void*,int){
  124258. if( keyClass==FTS3_HASH_STRING ){
  124259. return &fts3StrHash;
  124260. }else{
  124261. assert( keyClass==FTS3_HASH_BINARY );
  124262. return &fts3BinHash;
  124263. }
  124264. }
  124265. /*
  124266. ** Return a pointer to the appropriate hash function given the key class.
  124267. **
  124268. ** For help in interpreted the obscure C code in the function definition,
  124269. ** see the header comment on the previous function.
  124270. */
  124271. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  124272. if( keyClass==FTS3_HASH_STRING ){
  124273. return &fts3StrCompare;
  124274. }else{
  124275. assert( keyClass==FTS3_HASH_BINARY );
  124276. return &fts3BinCompare;
  124277. }
  124278. }
  124279. /* Link an element into the hash table
  124280. */
  124281. static void fts3HashInsertElement(
  124282. Fts3Hash *pH, /* The complete hash table */
  124283. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  124284. Fts3HashElem *pNew /* The element to be inserted */
  124285. ){
  124286. Fts3HashElem *pHead; /* First element already in pEntry */
  124287. pHead = pEntry->chain;
  124288. if( pHead ){
  124289. pNew->next = pHead;
  124290. pNew->prev = pHead->prev;
  124291. if( pHead->prev ){ pHead->prev->next = pNew; }
  124292. else { pH->first = pNew; }
  124293. pHead->prev = pNew;
  124294. }else{
  124295. pNew->next = pH->first;
  124296. if( pH->first ){ pH->first->prev = pNew; }
  124297. pNew->prev = 0;
  124298. pH->first = pNew;
  124299. }
  124300. pEntry->count++;
  124301. pEntry->chain = pNew;
  124302. }
  124303. /* Resize the hash table so that it cantains "new_size" buckets.
  124304. ** "new_size" must be a power of 2. The hash table might fail
  124305. ** to resize if sqliteMalloc() fails.
  124306. **
  124307. ** Return non-zero if a memory allocation error occurs.
  124308. */
  124309. static int fts3Rehash(Fts3Hash *pH, int new_size){
  124310. struct _fts3ht *new_ht; /* The new hash table */
  124311. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  124312. int (*xHash)(const void*,int); /* The hash function */
  124313. assert( (new_size & (new_size-1))==0 );
  124314. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  124315. if( new_ht==0 ) return 1;
  124316. fts3HashFree(pH->ht);
  124317. pH->ht = new_ht;
  124318. pH->htsize = new_size;
  124319. xHash = ftsHashFunction(pH->keyClass);
  124320. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  124321. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  124322. next_elem = elem->next;
  124323. fts3HashInsertElement(pH, &new_ht[h], elem);
  124324. }
  124325. return 0;
  124326. }
  124327. /* This function (for internal use only) locates an element in an
  124328. ** hash table that matches the given key. The hash for this key has
  124329. ** already been computed and is passed as the 4th parameter.
  124330. */
  124331. static Fts3HashElem *fts3FindElementByHash(
  124332. const Fts3Hash *pH, /* The pH to be searched */
  124333. const void *pKey, /* The key we are searching for */
  124334. int nKey,
  124335. int h /* The hash for this key. */
  124336. ){
  124337. Fts3HashElem *elem; /* Used to loop thru the element list */
  124338. int count; /* Number of elements left to test */
  124339. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  124340. if( pH->ht ){
  124341. struct _fts3ht *pEntry = &pH->ht[h];
  124342. elem = pEntry->chain;
  124343. count = pEntry->count;
  124344. xCompare = ftsCompareFunction(pH->keyClass);
  124345. while( count-- && elem ){
  124346. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  124347. return elem;
  124348. }
  124349. elem = elem->next;
  124350. }
  124351. }
  124352. return 0;
  124353. }
  124354. /* Remove a single entry from the hash table given a pointer to that
  124355. ** element and a hash on the element's key.
  124356. */
  124357. static void fts3RemoveElementByHash(
  124358. Fts3Hash *pH, /* The pH containing "elem" */
  124359. Fts3HashElem* elem, /* The element to be removed from the pH */
  124360. int h /* Hash value for the element */
  124361. ){
  124362. struct _fts3ht *pEntry;
  124363. if( elem->prev ){
  124364. elem->prev->next = elem->next;
  124365. }else{
  124366. pH->first = elem->next;
  124367. }
  124368. if( elem->next ){
  124369. elem->next->prev = elem->prev;
  124370. }
  124371. pEntry = &pH->ht[h];
  124372. if( pEntry->chain==elem ){
  124373. pEntry->chain = elem->next;
  124374. }
  124375. pEntry->count--;
  124376. if( pEntry->count<=0 ){
  124377. pEntry->chain = 0;
  124378. }
  124379. if( pH->copyKey && elem->pKey ){
  124380. fts3HashFree(elem->pKey);
  124381. }
  124382. fts3HashFree( elem );
  124383. pH->count--;
  124384. if( pH->count<=0 ){
  124385. assert( pH->first==0 );
  124386. assert( pH->count==0 );
  124387. fts3HashClear(pH);
  124388. }
  124389. }
  124390. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  124391. const Fts3Hash *pH,
  124392. const void *pKey,
  124393. int nKey
  124394. ){
  124395. int h; /* A hash on key */
  124396. int (*xHash)(const void*,int); /* The hash function */
  124397. if( pH==0 || pH->ht==0 ) return 0;
  124398. xHash = ftsHashFunction(pH->keyClass);
  124399. assert( xHash!=0 );
  124400. h = (*xHash)(pKey,nKey);
  124401. assert( (pH->htsize & (pH->htsize-1))==0 );
  124402. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  124403. }
  124404. /*
  124405. ** Attempt to locate an element of the hash table pH with a key
  124406. ** that matches pKey,nKey. Return the data for this element if it is
  124407. ** found, or NULL if there is no match.
  124408. */
  124409. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  124410. Fts3HashElem *pElem; /* The element that matches key (if any) */
  124411. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  124412. return pElem ? pElem->data : 0;
  124413. }
  124414. /* Insert an element into the hash table pH. The key is pKey,nKey
  124415. ** and the data is "data".
  124416. **
  124417. ** If no element exists with a matching key, then a new
  124418. ** element is created. A copy of the key is made if the copyKey
  124419. ** flag is set. NULL is returned.
  124420. **
  124421. ** If another element already exists with the same key, then the
  124422. ** new data replaces the old data and the old data is returned.
  124423. ** The key is not copied in this instance. If a malloc fails, then
  124424. ** the new data is returned and the hash table is unchanged.
  124425. **
  124426. ** If the "data" parameter to this function is NULL, then the
  124427. ** element corresponding to "key" is removed from the hash table.
  124428. */
  124429. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  124430. Fts3Hash *pH, /* The hash table to insert into */
  124431. const void *pKey, /* The key */
  124432. int nKey, /* Number of bytes in the key */
  124433. void *data /* The data */
  124434. ){
  124435. int hraw; /* Raw hash value of the key */
  124436. int h; /* the hash of the key modulo hash table size */
  124437. Fts3HashElem *elem; /* Used to loop thru the element list */
  124438. Fts3HashElem *new_elem; /* New element added to the pH */
  124439. int (*xHash)(const void*,int); /* The hash function */
  124440. assert( pH!=0 );
  124441. xHash = ftsHashFunction(pH->keyClass);
  124442. assert( xHash!=0 );
  124443. hraw = (*xHash)(pKey, nKey);
  124444. assert( (pH->htsize & (pH->htsize-1))==0 );
  124445. h = hraw & (pH->htsize-1);
  124446. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  124447. if( elem ){
  124448. void *old_data = elem->data;
  124449. if( data==0 ){
  124450. fts3RemoveElementByHash(pH,elem,h);
  124451. }else{
  124452. elem->data = data;
  124453. }
  124454. return old_data;
  124455. }
  124456. if( data==0 ) return 0;
  124457. if( (pH->htsize==0 && fts3Rehash(pH,8))
  124458. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  124459. ){
  124460. pH->count = 0;
  124461. return data;
  124462. }
  124463. assert( pH->htsize>0 );
  124464. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  124465. if( new_elem==0 ) return data;
  124466. if( pH->copyKey && pKey!=0 ){
  124467. new_elem->pKey = fts3HashMalloc( nKey );
  124468. if( new_elem->pKey==0 ){
  124469. fts3HashFree(new_elem);
  124470. return data;
  124471. }
  124472. memcpy((void*)new_elem->pKey, pKey, nKey);
  124473. }else{
  124474. new_elem->pKey = (void*)pKey;
  124475. }
  124476. new_elem->nKey = nKey;
  124477. pH->count++;
  124478. assert( pH->htsize>0 );
  124479. assert( (pH->htsize & (pH->htsize-1))==0 );
  124480. h = hraw & (pH->htsize-1);
  124481. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  124482. new_elem->data = data;
  124483. return 0;
  124484. }
  124485. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124486. /************** End of fts3_hash.c *******************************************/
  124487. /************** Begin file fts3_porter.c *************************************/
  124488. /*
  124489. ** 2006 September 30
  124490. **
  124491. ** The author disclaims copyright to this source code. In place of
  124492. ** a legal notice, here is a blessing:
  124493. **
  124494. ** May you do good and not evil.
  124495. ** May you find forgiveness for yourself and forgive others.
  124496. ** May you share freely, never taking more than you give.
  124497. **
  124498. *************************************************************************
  124499. ** Implementation of the full-text-search tokenizer that implements
  124500. ** a Porter stemmer.
  124501. */
  124502. /*
  124503. ** The code in this file is only compiled if:
  124504. **
  124505. ** * The FTS3 module is being built as an extension
  124506. ** (in which case SQLITE_CORE is not defined), or
  124507. **
  124508. ** * The FTS3 module is being built into the core of
  124509. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  124510. */
  124511. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124512. /* #include <assert.h> */
  124513. /* #include <stdlib.h> */
  124514. /* #include <stdio.h> */
  124515. /* #include <string.h> */
  124516. /*
  124517. ** Class derived from sqlite3_tokenizer
  124518. */
  124519. typedef struct porter_tokenizer {
  124520. sqlite3_tokenizer base; /* Base class */
  124521. } porter_tokenizer;
  124522. /*
  124523. ** Class derived from sqlite3_tokenizer_cursor
  124524. */
  124525. typedef struct porter_tokenizer_cursor {
  124526. sqlite3_tokenizer_cursor base;
  124527. const char *zInput; /* input we are tokenizing */
  124528. int nInput; /* size of the input */
  124529. int iOffset; /* current position in zInput */
  124530. int iToken; /* index of next token to be returned */
  124531. char *zToken; /* storage for current token */
  124532. int nAllocated; /* space allocated to zToken buffer */
  124533. } porter_tokenizer_cursor;
  124534. /*
  124535. ** Create a new tokenizer instance.
  124536. */
  124537. static int porterCreate(
  124538. int argc, const char * const *argv,
  124539. sqlite3_tokenizer **ppTokenizer
  124540. ){
  124541. porter_tokenizer *t;
  124542. UNUSED_PARAMETER(argc);
  124543. UNUSED_PARAMETER(argv);
  124544. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  124545. if( t==NULL ) return SQLITE_NOMEM;
  124546. memset(t, 0, sizeof(*t));
  124547. *ppTokenizer = &t->base;
  124548. return SQLITE_OK;
  124549. }
  124550. /*
  124551. ** Destroy a tokenizer
  124552. */
  124553. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  124554. sqlite3_free(pTokenizer);
  124555. return SQLITE_OK;
  124556. }
  124557. /*
  124558. ** Prepare to begin tokenizing a particular string. The input
  124559. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  124560. ** used to incrementally tokenize this string is returned in
  124561. ** *ppCursor.
  124562. */
  124563. static int porterOpen(
  124564. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  124565. const char *zInput, int nInput, /* String to be tokenized */
  124566. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  124567. ){
  124568. porter_tokenizer_cursor *c;
  124569. UNUSED_PARAMETER(pTokenizer);
  124570. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  124571. if( c==NULL ) return SQLITE_NOMEM;
  124572. c->zInput = zInput;
  124573. if( zInput==0 ){
  124574. c->nInput = 0;
  124575. }else if( nInput<0 ){
  124576. c->nInput = (int)strlen(zInput);
  124577. }else{
  124578. c->nInput = nInput;
  124579. }
  124580. c->iOffset = 0; /* start tokenizing at the beginning */
  124581. c->iToken = 0;
  124582. c->zToken = NULL; /* no space allocated, yet. */
  124583. c->nAllocated = 0;
  124584. *ppCursor = &c->base;
  124585. return SQLITE_OK;
  124586. }
  124587. /*
  124588. ** Close a tokenization cursor previously opened by a call to
  124589. ** porterOpen() above.
  124590. */
  124591. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  124592. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  124593. sqlite3_free(c->zToken);
  124594. sqlite3_free(c);
  124595. return SQLITE_OK;
  124596. }
  124597. /*
  124598. ** Vowel or consonant
  124599. */
  124600. static const char cType[] = {
  124601. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  124602. 1, 1, 1, 2, 1
  124603. };
  124604. /*
  124605. ** isConsonant() and isVowel() determine if their first character in
  124606. ** the string they point to is a consonant or a vowel, according
  124607. ** to Porter ruls.
  124608. **
  124609. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  124610. ** 'Y' is a consonant unless it follows another consonant,
  124611. ** in which case it is a vowel.
  124612. **
  124613. ** In these routine, the letters are in reverse order. So the 'y' rule
  124614. ** is that 'y' is a consonant unless it is followed by another
  124615. ** consonent.
  124616. */
  124617. static int isVowel(const char*);
  124618. static int isConsonant(const char *z){
  124619. int j;
  124620. char x = *z;
  124621. if( x==0 ) return 0;
  124622. assert( x>='a' && x<='z' );
  124623. j = cType[x-'a'];
  124624. if( j<2 ) return j;
  124625. return z[1]==0 || isVowel(z + 1);
  124626. }
  124627. static int isVowel(const char *z){
  124628. int j;
  124629. char x = *z;
  124630. if( x==0 ) return 0;
  124631. assert( x>='a' && x<='z' );
  124632. j = cType[x-'a'];
  124633. if( j<2 ) return 1-j;
  124634. return isConsonant(z + 1);
  124635. }
  124636. /*
  124637. ** Let any sequence of one or more vowels be represented by V and let
  124638. ** C be sequence of one or more consonants. Then every word can be
  124639. ** represented as:
  124640. **
  124641. ** [C] (VC){m} [V]
  124642. **
  124643. ** In prose: A word is an optional consonant followed by zero or
  124644. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  124645. ** number of vowel consonant pairs. This routine computes the value
  124646. ** of m for the first i bytes of a word.
  124647. **
  124648. ** Return true if the m-value for z is 1 or more. In other words,
  124649. ** return true if z contains at least one vowel that is followed
  124650. ** by a consonant.
  124651. **
  124652. ** In this routine z[] is in reverse order. So we are really looking
  124653. ** for an instance of of a consonant followed by a vowel.
  124654. */
  124655. static int m_gt_0(const char *z){
  124656. while( isVowel(z) ){ z++; }
  124657. if( *z==0 ) return 0;
  124658. while( isConsonant(z) ){ z++; }
  124659. return *z!=0;
  124660. }
  124661. /* Like mgt0 above except we are looking for a value of m which is
  124662. ** exactly 1
  124663. */
  124664. static int m_eq_1(const char *z){
  124665. while( isVowel(z) ){ z++; }
  124666. if( *z==0 ) return 0;
  124667. while( isConsonant(z) ){ z++; }
  124668. if( *z==0 ) return 0;
  124669. while( isVowel(z) ){ z++; }
  124670. if( *z==0 ) return 1;
  124671. while( isConsonant(z) ){ z++; }
  124672. return *z==0;
  124673. }
  124674. /* Like mgt0 above except we are looking for a value of m>1 instead
  124675. ** or m>0
  124676. */
  124677. static int m_gt_1(const char *z){
  124678. while( isVowel(z) ){ z++; }
  124679. if( *z==0 ) return 0;
  124680. while( isConsonant(z) ){ z++; }
  124681. if( *z==0 ) return 0;
  124682. while( isVowel(z) ){ z++; }
  124683. if( *z==0 ) return 0;
  124684. while( isConsonant(z) ){ z++; }
  124685. return *z!=0;
  124686. }
  124687. /*
  124688. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  124689. */
  124690. static int hasVowel(const char *z){
  124691. while( isConsonant(z) ){ z++; }
  124692. return *z!=0;
  124693. }
  124694. /*
  124695. ** Return TRUE if the word ends in a double consonant.
  124696. **
  124697. ** The text is reversed here. So we are really looking at
  124698. ** the first two characters of z[].
  124699. */
  124700. static int doubleConsonant(const char *z){
  124701. return isConsonant(z) && z[0]==z[1];
  124702. }
  124703. /*
  124704. ** Return TRUE if the word ends with three letters which
  124705. ** are consonant-vowel-consonent and where the final consonant
  124706. ** is not 'w', 'x', or 'y'.
  124707. **
  124708. ** The word is reversed here. So we are really checking the
  124709. ** first three letters and the first one cannot be in [wxy].
  124710. */
  124711. static int star_oh(const char *z){
  124712. return
  124713. isConsonant(z) &&
  124714. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  124715. isVowel(z+1) &&
  124716. isConsonant(z+2);
  124717. }
  124718. /*
  124719. ** If the word ends with zFrom and xCond() is true for the stem
  124720. ** of the word that preceeds the zFrom ending, then change the
  124721. ** ending to zTo.
  124722. **
  124723. ** The input word *pz and zFrom are both in reverse order. zTo
  124724. ** is in normal order.
  124725. **
  124726. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  124727. ** match. Not that TRUE is returned even if xCond() fails and
  124728. ** no substitution occurs.
  124729. */
  124730. static int stem(
  124731. char **pz, /* The word being stemmed (Reversed) */
  124732. const char *zFrom, /* If the ending matches this... (Reversed) */
  124733. const char *zTo, /* ... change the ending to this (not reversed) */
  124734. int (*xCond)(const char*) /* Condition that must be true */
  124735. ){
  124736. char *z = *pz;
  124737. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  124738. if( *zFrom!=0 ) return 0;
  124739. if( xCond && !xCond(z) ) return 1;
  124740. while( *zTo ){
  124741. *(--z) = *(zTo++);
  124742. }
  124743. *pz = z;
  124744. return 1;
  124745. }
  124746. /*
  124747. ** This is the fallback stemmer used when the porter stemmer is
  124748. ** inappropriate. The input word is copied into the output with
  124749. ** US-ASCII case folding. If the input word is too long (more
  124750. ** than 20 bytes if it contains no digits or more than 6 bytes if
  124751. ** it contains digits) then word is truncated to 20 or 6 bytes
  124752. ** by taking 10 or 3 bytes from the beginning and end.
  124753. */
  124754. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  124755. int i, mx, j;
  124756. int hasDigit = 0;
  124757. for(i=0; i<nIn; i++){
  124758. char c = zIn[i];
  124759. if( c>='A' && c<='Z' ){
  124760. zOut[i] = c - 'A' + 'a';
  124761. }else{
  124762. if( c>='0' && c<='9' ) hasDigit = 1;
  124763. zOut[i] = c;
  124764. }
  124765. }
  124766. mx = hasDigit ? 3 : 10;
  124767. if( nIn>mx*2 ){
  124768. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  124769. zOut[j] = zOut[i];
  124770. }
  124771. i = j;
  124772. }
  124773. zOut[i] = 0;
  124774. *pnOut = i;
  124775. }
  124776. /*
  124777. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  124778. ** zOut is at least big enough to hold nIn bytes. Write the actual
  124779. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  124780. **
  124781. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  124782. ** are converted to lower case. Upper-case UTF characters are
  124783. ** unchanged.
  124784. **
  124785. ** Words that are longer than about 20 bytes are stemmed by retaining
  124786. ** a few bytes from the beginning and the end of the word. If the
  124787. ** word contains digits, 3 bytes are taken from the beginning and
  124788. ** 3 bytes from the end. For long words without digits, 10 bytes
  124789. ** are taken from each end. US-ASCII case folding still applies.
  124790. **
  124791. ** If the input word contains not digits but does characters not
  124792. ** in [a-zA-Z] then no stemming is attempted and this routine just
  124793. ** copies the input into the input into the output with US-ASCII
  124794. ** case folding.
  124795. **
  124796. ** Stemming never increases the length of the word. So there is
  124797. ** no chance of overflowing the zOut buffer.
  124798. */
  124799. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  124800. int i, j;
  124801. char zReverse[28];
  124802. char *z, *z2;
  124803. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  124804. /* The word is too big or too small for the porter stemmer.
  124805. ** Fallback to the copy stemmer */
  124806. copy_stemmer(zIn, nIn, zOut, pnOut);
  124807. return;
  124808. }
  124809. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  124810. char c = zIn[i];
  124811. if( c>='A' && c<='Z' ){
  124812. zReverse[j] = c + 'a' - 'A';
  124813. }else if( c>='a' && c<='z' ){
  124814. zReverse[j] = c;
  124815. }else{
  124816. /* The use of a character not in [a-zA-Z] means that we fallback
  124817. ** to the copy stemmer */
  124818. copy_stemmer(zIn, nIn, zOut, pnOut);
  124819. return;
  124820. }
  124821. }
  124822. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  124823. z = &zReverse[j+1];
  124824. /* Step 1a */
  124825. if( z[0]=='s' ){
  124826. if(
  124827. !stem(&z, "sess", "ss", 0) &&
  124828. !stem(&z, "sei", "i", 0) &&
  124829. !stem(&z, "ss", "ss", 0)
  124830. ){
  124831. z++;
  124832. }
  124833. }
  124834. /* Step 1b */
  124835. z2 = z;
  124836. if( stem(&z, "dee", "ee", m_gt_0) ){
  124837. /* Do nothing. The work was all in the test */
  124838. }else if(
  124839. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  124840. && z!=z2
  124841. ){
  124842. if( stem(&z, "ta", "ate", 0) ||
  124843. stem(&z, "lb", "ble", 0) ||
  124844. stem(&z, "zi", "ize", 0) ){
  124845. /* Do nothing. The work was all in the test */
  124846. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  124847. z++;
  124848. }else if( m_eq_1(z) && star_oh(z) ){
  124849. *(--z) = 'e';
  124850. }
  124851. }
  124852. /* Step 1c */
  124853. if( z[0]=='y' && hasVowel(z+1) ){
  124854. z[0] = 'i';
  124855. }
  124856. /* Step 2 */
  124857. switch( z[1] ){
  124858. case 'a':
  124859. stem(&z, "lanoita", "ate", m_gt_0) ||
  124860. stem(&z, "lanoit", "tion", m_gt_0);
  124861. break;
  124862. case 'c':
  124863. stem(&z, "icne", "ence", m_gt_0) ||
  124864. stem(&z, "icna", "ance", m_gt_0);
  124865. break;
  124866. case 'e':
  124867. stem(&z, "rezi", "ize", m_gt_0);
  124868. break;
  124869. case 'g':
  124870. stem(&z, "igol", "log", m_gt_0);
  124871. break;
  124872. case 'l':
  124873. stem(&z, "ilb", "ble", m_gt_0) ||
  124874. stem(&z, "illa", "al", m_gt_0) ||
  124875. stem(&z, "iltne", "ent", m_gt_0) ||
  124876. stem(&z, "ile", "e", m_gt_0) ||
  124877. stem(&z, "ilsuo", "ous", m_gt_0);
  124878. break;
  124879. case 'o':
  124880. stem(&z, "noitazi", "ize", m_gt_0) ||
  124881. stem(&z, "noita", "ate", m_gt_0) ||
  124882. stem(&z, "rota", "ate", m_gt_0);
  124883. break;
  124884. case 's':
  124885. stem(&z, "msila", "al", m_gt_0) ||
  124886. stem(&z, "ssenevi", "ive", m_gt_0) ||
  124887. stem(&z, "ssenluf", "ful", m_gt_0) ||
  124888. stem(&z, "ssensuo", "ous", m_gt_0);
  124889. break;
  124890. case 't':
  124891. stem(&z, "itila", "al", m_gt_0) ||
  124892. stem(&z, "itivi", "ive", m_gt_0) ||
  124893. stem(&z, "itilib", "ble", m_gt_0);
  124894. break;
  124895. }
  124896. /* Step 3 */
  124897. switch( z[0] ){
  124898. case 'e':
  124899. stem(&z, "etaci", "ic", m_gt_0) ||
  124900. stem(&z, "evita", "", m_gt_0) ||
  124901. stem(&z, "ezila", "al", m_gt_0);
  124902. break;
  124903. case 'i':
  124904. stem(&z, "itici", "ic", m_gt_0);
  124905. break;
  124906. case 'l':
  124907. stem(&z, "laci", "ic", m_gt_0) ||
  124908. stem(&z, "luf", "", m_gt_0);
  124909. break;
  124910. case 's':
  124911. stem(&z, "ssen", "", m_gt_0);
  124912. break;
  124913. }
  124914. /* Step 4 */
  124915. switch( z[1] ){
  124916. case 'a':
  124917. if( z[0]=='l' && m_gt_1(z+2) ){
  124918. z += 2;
  124919. }
  124920. break;
  124921. case 'c':
  124922. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  124923. z += 4;
  124924. }
  124925. break;
  124926. case 'e':
  124927. if( z[0]=='r' && m_gt_1(z+2) ){
  124928. z += 2;
  124929. }
  124930. break;
  124931. case 'i':
  124932. if( z[0]=='c' && m_gt_1(z+2) ){
  124933. z += 2;
  124934. }
  124935. break;
  124936. case 'l':
  124937. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  124938. z += 4;
  124939. }
  124940. break;
  124941. case 'n':
  124942. if( z[0]=='t' ){
  124943. if( z[2]=='a' ){
  124944. if( m_gt_1(z+3) ){
  124945. z += 3;
  124946. }
  124947. }else if( z[2]=='e' ){
  124948. stem(&z, "tneme", "", m_gt_1) ||
  124949. stem(&z, "tnem", "", m_gt_1) ||
  124950. stem(&z, "tne", "", m_gt_1);
  124951. }
  124952. }
  124953. break;
  124954. case 'o':
  124955. if( z[0]=='u' ){
  124956. if( m_gt_1(z+2) ){
  124957. z += 2;
  124958. }
  124959. }else if( z[3]=='s' || z[3]=='t' ){
  124960. stem(&z, "noi", "", m_gt_1);
  124961. }
  124962. break;
  124963. case 's':
  124964. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  124965. z += 3;
  124966. }
  124967. break;
  124968. case 't':
  124969. stem(&z, "eta", "", m_gt_1) ||
  124970. stem(&z, "iti", "", m_gt_1);
  124971. break;
  124972. case 'u':
  124973. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  124974. z += 3;
  124975. }
  124976. break;
  124977. case 'v':
  124978. case 'z':
  124979. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  124980. z += 3;
  124981. }
  124982. break;
  124983. }
  124984. /* Step 5a */
  124985. if( z[0]=='e' ){
  124986. if( m_gt_1(z+1) ){
  124987. z++;
  124988. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  124989. z++;
  124990. }
  124991. }
  124992. /* Step 5b */
  124993. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  124994. z++;
  124995. }
  124996. /* z[] is now the stemmed word in reverse order. Flip it back
  124997. ** around into forward order and return.
  124998. */
  124999. *pnOut = i = (int)strlen(z);
  125000. zOut[i] = 0;
  125001. while( *z ){
  125002. zOut[--i] = *(z++);
  125003. }
  125004. }
  125005. /*
  125006. ** Characters that can be part of a token. We assume any character
  125007. ** whose value is greater than 0x80 (any UTF character) can be
  125008. ** part of a token. In other words, delimiters all must have
  125009. ** values of 0x7f or lower.
  125010. */
  125011. static const char porterIdChar[] = {
  125012. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  125013. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  125014. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  125015. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  125016. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  125017. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  125018. };
  125019. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  125020. /*
  125021. ** Extract the next token from a tokenization cursor. The cursor must
  125022. ** have been opened by a prior call to porterOpen().
  125023. */
  125024. static int porterNext(
  125025. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  125026. const char **pzToken, /* OUT: *pzToken is the token text */
  125027. int *pnBytes, /* OUT: Number of bytes in token */
  125028. int *piStartOffset, /* OUT: Starting offset of token */
  125029. int *piEndOffset, /* OUT: Ending offset of token */
  125030. int *piPosition /* OUT: Position integer of token */
  125031. ){
  125032. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  125033. const char *z = c->zInput;
  125034. while( c->iOffset<c->nInput ){
  125035. int iStartOffset, ch;
  125036. /* Scan past delimiter characters */
  125037. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  125038. c->iOffset++;
  125039. }
  125040. /* Count non-delimiter characters. */
  125041. iStartOffset = c->iOffset;
  125042. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  125043. c->iOffset++;
  125044. }
  125045. if( c->iOffset>iStartOffset ){
  125046. int n = c->iOffset-iStartOffset;
  125047. if( n>c->nAllocated ){
  125048. char *pNew;
  125049. c->nAllocated = n+20;
  125050. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  125051. if( !pNew ) return SQLITE_NOMEM;
  125052. c->zToken = pNew;
  125053. }
  125054. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  125055. *pzToken = c->zToken;
  125056. *piStartOffset = iStartOffset;
  125057. *piEndOffset = c->iOffset;
  125058. *piPosition = c->iToken++;
  125059. return SQLITE_OK;
  125060. }
  125061. }
  125062. return SQLITE_DONE;
  125063. }
  125064. /*
  125065. ** The set of routines that implement the porter-stemmer tokenizer
  125066. */
  125067. static const sqlite3_tokenizer_module porterTokenizerModule = {
  125068. 0,
  125069. porterCreate,
  125070. porterDestroy,
  125071. porterOpen,
  125072. porterClose,
  125073. porterNext,
  125074. 0
  125075. };
  125076. /*
  125077. ** Allocate a new porter tokenizer. Return a pointer to the new
  125078. ** tokenizer in *ppModule
  125079. */
  125080. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  125081. sqlite3_tokenizer_module const**ppModule
  125082. ){
  125083. *ppModule = &porterTokenizerModule;
  125084. }
  125085. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125086. /************** End of fts3_porter.c *****************************************/
  125087. /************** Begin file fts3_tokenizer.c **********************************/
  125088. /*
  125089. ** 2007 June 22
  125090. **
  125091. ** The author disclaims copyright to this source code. In place of
  125092. ** a legal notice, here is a blessing:
  125093. **
  125094. ** May you do good and not evil.
  125095. ** May you find forgiveness for yourself and forgive others.
  125096. ** May you share freely, never taking more than you give.
  125097. **
  125098. ******************************************************************************
  125099. **
  125100. ** This is part of an SQLite module implementing full-text search.
  125101. ** This particular file implements the generic tokenizer interface.
  125102. */
  125103. /*
  125104. ** The code in this file is only compiled if:
  125105. **
  125106. ** * The FTS3 module is being built as an extension
  125107. ** (in which case SQLITE_CORE is not defined), or
  125108. **
  125109. ** * The FTS3 module is being built into the core of
  125110. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  125111. */
  125112. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125113. /* #include <assert.h> */
  125114. /* #include <string.h> */
  125115. /*
  125116. ** Implementation of the SQL scalar function for accessing the underlying
  125117. ** hash table. This function may be called as follows:
  125118. **
  125119. ** SELECT <function-name>(<key-name>);
  125120. ** SELECT <function-name>(<key-name>, <pointer>);
  125121. **
  125122. ** where <function-name> is the name passed as the second argument
  125123. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  125124. **
  125125. ** If the <pointer> argument is specified, it must be a blob value
  125126. ** containing a pointer to be stored as the hash data corresponding
  125127. ** to the string <key-name>. If <pointer> is not specified, then
  125128. ** the string <key-name> must already exist in the has table. Otherwise,
  125129. ** an error is returned.
  125130. **
  125131. ** Whether or not the <pointer> argument is specified, the value returned
  125132. ** is a blob containing the pointer stored as the hash data corresponding
  125133. ** to string <key-name> (after the hash-table is updated, if applicable).
  125134. */
  125135. static void scalarFunc(
  125136. sqlite3_context *context,
  125137. int argc,
  125138. sqlite3_value **argv
  125139. ){
  125140. Fts3Hash *pHash;
  125141. void *pPtr = 0;
  125142. const unsigned char *zName;
  125143. int nName;
  125144. assert( argc==1 || argc==2 );
  125145. pHash = (Fts3Hash *)sqlite3_user_data(context);
  125146. zName = sqlite3_value_text(argv[0]);
  125147. nName = sqlite3_value_bytes(argv[0])+1;
  125148. if( argc==2 ){
  125149. void *pOld;
  125150. int n = sqlite3_value_bytes(argv[1]);
  125151. if( n!=sizeof(pPtr) ){
  125152. sqlite3_result_error(context, "argument type mismatch", -1);
  125153. return;
  125154. }
  125155. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  125156. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  125157. if( pOld==pPtr ){
  125158. sqlite3_result_error(context, "out of memory", -1);
  125159. return;
  125160. }
  125161. }else{
  125162. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  125163. if( !pPtr ){
  125164. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125165. sqlite3_result_error(context, zErr, -1);
  125166. sqlite3_free(zErr);
  125167. return;
  125168. }
  125169. }
  125170. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  125171. }
  125172. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  125173. static const char isFtsIdChar[] = {
  125174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  125175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  125176. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  125177. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  125178. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  125179. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  125180. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  125181. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  125182. };
  125183. return (c&0x80 || isFtsIdChar[(int)(c)]);
  125184. }
  125185. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  125186. const char *z1;
  125187. const char *z2 = 0;
  125188. /* Find the start of the next token. */
  125189. z1 = zStr;
  125190. while( z2==0 ){
  125191. char c = *z1;
  125192. switch( c ){
  125193. case '\0': return 0; /* No more tokens here */
  125194. case '\'':
  125195. case '"':
  125196. case '`': {
  125197. z2 = z1;
  125198. while( *++z2 && (*z2!=c || *++z2==c) );
  125199. break;
  125200. }
  125201. case '[':
  125202. z2 = &z1[1];
  125203. while( *z2 && z2[0]!=']' ) z2++;
  125204. if( *z2 ) z2++;
  125205. break;
  125206. default:
  125207. if( sqlite3Fts3IsIdChar(*z1) ){
  125208. z2 = &z1[1];
  125209. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  125210. }else{
  125211. z1++;
  125212. }
  125213. }
  125214. }
  125215. *pn = (int)(z2-z1);
  125216. return z1;
  125217. }
  125218. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  125219. Fts3Hash *pHash, /* Tokenizer hash table */
  125220. const char *zArg, /* Tokenizer name */
  125221. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  125222. char **pzErr /* OUT: Set to malloced error message */
  125223. ){
  125224. int rc;
  125225. char *z = (char *)zArg;
  125226. int n = 0;
  125227. char *zCopy;
  125228. char *zEnd; /* Pointer to nul-term of zCopy */
  125229. sqlite3_tokenizer_module *m;
  125230. zCopy = sqlite3_mprintf("%s", zArg);
  125231. if( !zCopy ) return SQLITE_NOMEM;
  125232. zEnd = &zCopy[strlen(zCopy)];
  125233. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  125234. z[n] = '\0';
  125235. sqlite3Fts3Dequote(z);
  125236. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  125237. if( !m ){
  125238. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  125239. rc = SQLITE_ERROR;
  125240. }else{
  125241. char const **aArg = 0;
  125242. int iArg = 0;
  125243. z = &z[n+1];
  125244. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  125245. int nNew = sizeof(char *)*(iArg+1);
  125246. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  125247. if( !aNew ){
  125248. sqlite3_free(zCopy);
  125249. sqlite3_free((void *)aArg);
  125250. return SQLITE_NOMEM;
  125251. }
  125252. aArg = aNew;
  125253. aArg[iArg++] = z;
  125254. z[n] = '\0';
  125255. sqlite3Fts3Dequote(z);
  125256. z = &z[n+1];
  125257. }
  125258. rc = m->xCreate(iArg, aArg, ppTok);
  125259. assert( rc!=SQLITE_OK || *ppTok );
  125260. if( rc!=SQLITE_OK ){
  125261. *pzErr = sqlite3_mprintf("unknown tokenizer");
  125262. }else{
  125263. (*ppTok)->pModule = m;
  125264. }
  125265. sqlite3_free((void *)aArg);
  125266. }
  125267. sqlite3_free(zCopy);
  125268. return rc;
  125269. }
  125270. #ifdef SQLITE_TEST
  125271. #include <tcl.h>
  125272. /* #include <string.h> */
  125273. /*
  125274. ** Implementation of a special SQL scalar function for testing tokenizers
  125275. ** designed to be used in concert with the Tcl testing framework. This
  125276. ** function must be called with two or more arguments:
  125277. **
  125278. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  125279. **
  125280. ** where <function-name> is the name passed as the second argument
  125281. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  125282. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  125283. **
  125284. ** The return value is a string that may be interpreted as a Tcl
  125285. ** list. For each token in the <input-string>, three elements are
  125286. ** added to the returned list. The first is the token position, the
  125287. ** second is the token text (folded, stemmed, etc.) and the third is the
  125288. ** substring of <input-string> associated with the token. For example,
  125289. ** using the built-in "simple" tokenizer:
  125290. **
  125291. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  125292. **
  125293. ** will return the string:
  125294. **
  125295. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  125296. **
  125297. */
  125298. static void testFunc(
  125299. sqlite3_context *context,
  125300. int argc,
  125301. sqlite3_value **argv
  125302. ){
  125303. Fts3Hash *pHash;
  125304. sqlite3_tokenizer_module *p;
  125305. sqlite3_tokenizer *pTokenizer = 0;
  125306. sqlite3_tokenizer_cursor *pCsr = 0;
  125307. const char *zErr = 0;
  125308. const char *zName;
  125309. int nName;
  125310. const char *zInput;
  125311. int nInput;
  125312. const char *azArg[64];
  125313. const char *zToken;
  125314. int nToken = 0;
  125315. int iStart = 0;
  125316. int iEnd = 0;
  125317. int iPos = 0;
  125318. int i;
  125319. Tcl_Obj *pRet;
  125320. if( argc<2 ){
  125321. sqlite3_result_error(context, "insufficient arguments", -1);
  125322. return;
  125323. }
  125324. nName = sqlite3_value_bytes(argv[0]);
  125325. zName = (const char *)sqlite3_value_text(argv[0]);
  125326. nInput = sqlite3_value_bytes(argv[argc-1]);
  125327. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  125328. pHash = (Fts3Hash *)sqlite3_user_data(context);
  125329. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  125330. if( !p ){
  125331. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125332. sqlite3_result_error(context, zErr, -1);
  125333. sqlite3_free(zErr);
  125334. return;
  125335. }
  125336. pRet = Tcl_NewObj();
  125337. Tcl_IncrRefCount(pRet);
  125338. for(i=1; i<argc-1; i++){
  125339. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  125340. }
  125341. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  125342. zErr = "error in xCreate()";
  125343. goto finish;
  125344. }
  125345. pTokenizer->pModule = p;
  125346. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  125347. zErr = "error in xOpen()";
  125348. goto finish;
  125349. }
  125350. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  125351. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  125352. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  125353. zToken = &zInput[iStart];
  125354. nToken = iEnd-iStart;
  125355. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  125356. }
  125357. if( SQLITE_OK!=p->xClose(pCsr) ){
  125358. zErr = "error in xClose()";
  125359. goto finish;
  125360. }
  125361. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  125362. zErr = "error in xDestroy()";
  125363. goto finish;
  125364. }
  125365. finish:
  125366. if( zErr ){
  125367. sqlite3_result_error(context, zErr, -1);
  125368. }else{
  125369. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  125370. }
  125371. Tcl_DecrRefCount(pRet);
  125372. }
  125373. static
  125374. int registerTokenizer(
  125375. sqlite3 *db,
  125376. char *zName,
  125377. const sqlite3_tokenizer_module *p
  125378. ){
  125379. int rc;
  125380. sqlite3_stmt *pStmt;
  125381. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  125382. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125383. if( rc!=SQLITE_OK ){
  125384. return rc;
  125385. }
  125386. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  125387. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  125388. sqlite3_step(pStmt);
  125389. return sqlite3_finalize(pStmt);
  125390. }
  125391. static
  125392. int queryTokenizer(
  125393. sqlite3 *db,
  125394. char *zName,
  125395. const sqlite3_tokenizer_module **pp
  125396. ){
  125397. int rc;
  125398. sqlite3_stmt *pStmt;
  125399. const char zSql[] = "SELECT fts3_tokenizer(?)";
  125400. *pp = 0;
  125401. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125402. if( rc!=SQLITE_OK ){
  125403. return rc;
  125404. }
  125405. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  125406. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  125407. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  125408. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  125409. }
  125410. }
  125411. return sqlite3_finalize(pStmt);
  125412. }
  125413. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125414. /*
  125415. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  125416. ** This function is used for testing only, it is not included in the
  125417. ** build unless SQLITE_TEST is defined.
  125418. **
  125419. ** The purpose of this is to test that the fts3_tokenizer() function
  125420. ** can be used as designed by the C-code in the queryTokenizer and
  125421. ** registerTokenizer() functions above. These two functions are repeated
  125422. ** in the README.tokenizer file as an example, so it is important to
  125423. ** test them.
  125424. **
  125425. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  125426. ** function with no arguments. An assert() will fail if a problem is
  125427. ** detected. i.e.:
  125428. **
  125429. ** SELECT fts3_tokenizer_internal_test();
  125430. **
  125431. */
  125432. static void intTestFunc(
  125433. sqlite3_context *context,
  125434. int argc,
  125435. sqlite3_value **argv
  125436. ){
  125437. int rc;
  125438. const sqlite3_tokenizer_module *p1;
  125439. const sqlite3_tokenizer_module *p2;
  125440. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  125441. UNUSED_PARAMETER(argc);
  125442. UNUSED_PARAMETER(argv);
  125443. /* Test the query function */
  125444. sqlite3Fts3SimpleTokenizerModule(&p1);
  125445. rc = queryTokenizer(db, "simple", &p2);
  125446. assert( rc==SQLITE_OK );
  125447. assert( p1==p2 );
  125448. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  125449. assert( rc==SQLITE_ERROR );
  125450. assert( p2==0 );
  125451. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  125452. /* Test the storage function */
  125453. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  125454. assert( rc==SQLITE_OK );
  125455. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  125456. assert( rc==SQLITE_OK );
  125457. assert( p2==p1 );
  125458. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  125459. }
  125460. #endif
  125461. /*
  125462. ** Set up SQL objects in database db used to access the contents of
  125463. ** the hash table pointed to by argument pHash. The hash table must
  125464. ** been initialized to use string keys, and to take a private copy
  125465. ** of the key when a value is inserted. i.e. by a call similar to:
  125466. **
  125467. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  125468. **
  125469. ** This function adds a scalar function (see header comment above
  125470. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  125471. ** defined at compilation time, a temporary virtual table (see header
  125472. ** comment above struct HashTableVtab) to the database schema. Both
  125473. ** provide read/write access to the contents of *pHash.
  125474. **
  125475. ** The third argument to this function, zName, is used as the name
  125476. ** of both the scalar and, if created, the virtual table.
  125477. */
  125478. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  125479. sqlite3 *db,
  125480. Fts3Hash *pHash,
  125481. const char *zName
  125482. ){
  125483. int rc = SQLITE_OK;
  125484. void *p = (void *)pHash;
  125485. const int any = SQLITE_ANY;
  125486. #ifdef SQLITE_TEST
  125487. char *zTest = 0;
  125488. char *zTest2 = 0;
  125489. void *pdb = (void *)db;
  125490. zTest = sqlite3_mprintf("%s_test", zName);
  125491. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  125492. if( !zTest || !zTest2 ){
  125493. rc = SQLITE_NOMEM;
  125494. }
  125495. #endif
  125496. if( SQLITE_OK==rc ){
  125497. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  125498. }
  125499. if( SQLITE_OK==rc ){
  125500. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  125501. }
  125502. #ifdef SQLITE_TEST
  125503. if( SQLITE_OK==rc ){
  125504. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  125505. }
  125506. if( SQLITE_OK==rc ){
  125507. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  125508. }
  125509. #endif
  125510. #ifdef SQLITE_TEST
  125511. sqlite3_free(zTest);
  125512. sqlite3_free(zTest2);
  125513. #endif
  125514. return rc;
  125515. }
  125516. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125517. /************** End of fts3_tokenizer.c **************************************/
  125518. /************** Begin file fts3_tokenizer1.c *********************************/
  125519. /*
  125520. ** 2006 Oct 10
  125521. **
  125522. ** The author disclaims copyright to this source code. In place of
  125523. ** a legal notice, here is a blessing:
  125524. **
  125525. ** May you do good and not evil.
  125526. ** May you find forgiveness for yourself and forgive others.
  125527. ** May you share freely, never taking more than you give.
  125528. **
  125529. ******************************************************************************
  125530. **
  125531. ** Implementation of the "simple" full-text-search tokenizer.
  125532. */
  125533. /*
  125534. ** The code in this file is only compiled if:
  125535. **
  125536. ** * The FTS3 module is being built as an extension
  125537. ** (in which case SQLITE_CORE is not defined), or
  125538. **
  125539. ** * The FTS3 module is being built into the core of
  125540. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  125541. */
  125542. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125543. /* #include <assert.h> */
  125544. /* #include <stdlib.h> */
  125545. /* #include <stdio.h> */
  125546. /* #include <string.h> */
  125547. typedef struct simple_tokenizer {
  125548. sqlite3_tokenizer base;
  125549. char delim[128]; /* flag ASCII delimiters */
  125550. } simple_tokenizer;
  125551. typedef struct simple_tokenizer_cursor {
  125552. sqlite3_tokenizer_cursor base;
  125553. const char *pInput; /* input we are tokenizing */
  125554. int nBytes; /* size of the input */
  125555. int iOffset; /* current position in pInput */
  125556. int iToken; /* index of next token to be returned */
  125557. char *pToken; /* storage for current token */
  125558. int nTokenAllocated; /* space allocated to zToken buffer */
  125559. } simple_tokenizer_cursor;
  125560. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  125561. return c<0x80 && t->delim[c];
  125562. }
  125563. static int fts3_isalnum(int x){
  125564. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  125565. }
  125566. /*
  125567. ** Create a new tokenizer instance.
  125568. */
  125569. static int simpleCreate(
  125570. int argc, const char * const *argv,
  125571. sqlite3_tokenizer **ppTokenizer
  125572. ){
  125573. simple_tokenizer *t;
  125574. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  125575. if( t==NULL ) return SQLITE_NOMEM;
  125576. memset(t, 0, sizeof(*t));
  125577. /* TODO(shess) Delimiters need to remain the same from run to run,
  125578. ** else we need to reindex. One solution would be a meta-table to
  125579. ** track such information in the database, then we'd only want this
  125580. ** information on the initial create.
  125581. */
  125582. if( argc>1 ){
  125583. int i, n = (int)strlen(argv[1]);
  125584. for(i=0; i<n; i++){
  125585. unsigned char ch = argv[1][i];
  125586. /* We explicitly don't support UTF-8 delimiters for now. */
  125587. if( ch>=0x80 ){
  125588. sqlite3_free(t);
  125589. return SQLITE_ERROR;
  125590. }
  125591. t->delim[ch] = 1;
  125592. }
  125593. } else {
  125594. /* Mark non-alphanumeric ASCII characters as delimiters */
  125595. int i;
  125596. for(i=1; i<0x80; i++){
  125597. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  125598. }
  125599. }
  125600. *ppTokenizer = &t->base;
  125601. return SQLITE_OK;
  125602. }
  125603. /*
  125604. ** Destroy a tokenizer
  125605. */
  125606. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  125607. sqlite3_free(pTokenizer);
  125608. return SQLITE_OK;
  125609. }
  125610. /*
  125611. ** Prepare to begin tokenizing a particular string. The input
  125612. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  125613. ** used to incrementally tokenize this string is returned in
  125614. ** *ppCursor.
  125615. */
  125616. static int simpleOpen(
  125617. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  125618. const char *pInput, int nBytes, /* String to be tokenized */
  125619. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  125620. ){
  125621. simple_tokenizer_cursor *c;
  125622. UNUSED_PARAMETER(pTokenizer);
  125623. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  125624. if( c==NULL ) return SQLITE_NOMEM;
  125625. c->pInput = pInput;
  125626. if( pInput==0 ){
  125627. c->nBytes = 0;
  125628. }else if( nBytes<0 ){
  125629. c->nBytes = (int)strlen(pInput);
  125630. }else{
  125631. c->nBytes = nBytes;
  125632. }
  125633. c->iOffset = 0; /* start tokenizing at the beginning */
  125634. c->iToken = 0;
  125635. c->pToken = NULL; /* no space allocated, yet. */
  125636. c->nTokenAllocated = 0;
  125637. *ppCursor = &c->base;
  125638. return SQLITE_OK;
  125639. }
  125640. /*
  125641. ** Close a tokenization cursor previously opened by a call to
  125642. ** simpleOpen() above.
  125643. */
  125644. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  125645. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  125646. sqlite3_free(c->pToken);
  125647. sqlite3_free(c);
  125648. return SQLITE_OK;
  125649. }
  125650. /*
  125651. ** Extract the next token from a tokenization cursor. The cursor must
  125652. ** have been opened by a prior call to simpleOpen().
  125653. */
  125654. static int simpleNext(
  125655. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  125656. const char **ppToken, /* OUT: *ppToken is the token text */
  125657. int *pnBytes, /* OUT: Number of bytes in token */
  125658. int *piStartOffset, /* OUT: Starting offset of token */
  125659. int *piEndOffset, /* OUT: Ending offset of token */
  125660. int *piPosition /* OUT: Position integer of token */
  125661. ){
  125662. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  125663. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  125664. unsigned char *p = (unsigned char *)c->pInput;
  125665. while( c->iOffset<c->nBytes ){
  125666. int iStartOffset;
  125667. /* Scan past delimiter characters */
  125668. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  125669. c->iOffset++;
  125670. }
  125671. /* Count non-delimiter characters. */
  125672. iStartOffset = c->iOffset;
  125673. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  125674. c->iOffset++;
  125675. }
  125676. if( c->iOffset>iStartOffset ){
  125677. int i, n = c->iOffset-iStartOffset;
  125678. if( n>c->nTokenAllocated ){
  125679. char *pNew;
  125680. c->nTokenAllocated = n+20;
  125681. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  125682. if( !pNew ) return SQLITE_NOMEM;
  125683. c->pToken = pNew;
  125684. }
  125685. for(i=0; i<n; i++){
  125686. /* TODO(shess) This needs expansion to handle UTF-8
  125687. ** case-insensitivity.
  125688. */
  125689. unsigned char ch = p[iStartOffset+i];
  125690. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  125691. }
  125692. *ppToken = c->pToken;
  125693. *pnBytes = n;
  125694. *piStartOffset = iStartOffset;
  125695. *piEndOffset = c->iOffset;
  125696. *piPosition = c->iToken++;
  125697. return SQLITE_OK;
  125698. }
  125699. }
  125700. return SQLITE_DONE;
  125701. }
  125702. /*
  125703. ** The set of routines that implement the simple tokenizer
  125704. */
  125705. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  125706. 0,
  125707. simpleCreate,
  125708. simpleDestroy,
  125709. simpleOpen,
  125710. simpleClose,
  125711. simpleNext,
  125712. 0,
  125713. };
  125714. /*
  125715. ** Allocate a new simple tokenizer. Return a pointer to the new
  125716. ** tokenizer in *ppModule
  125717. */
  125718. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  125719. sqlite3_tokenizer_module const**ppModule
  125720. ){
  125721. *ppModule = &simpleTokenizerModule;
  125722. }
  125723. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125724. /************** End of fts3_tokenizer1.c *************************************/
  125725. /************** Begin file fts3_tokenize_vtab.c ******************************/
  125726. /*
  125727. ** 2013 Apr 22
  125728. **
  125729. ** The author disclaims copyright to this source code. In place of
  125730. ** a legal notice, here is a blessing:
  125731. **
  125732. ** May you do good and not evil.
  125733. ** May you find forgiveness for yourself and forgive others.
  125734. ** May you share freely, never taking more than you give.
  125735. **
  125736. ******************************************************************************
  125737. **
  125738. ** This file contains code for the "fts3tokenize" virtual table module.
  125739. ** An fts3tokenize virtual table is created as follows:
  125740. **
  125741. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  125742. ** <tokenizer-name>, <arg-1>, ...
  125743. ** );
  125744. **
  125745. ** The table created has the following schema:
  125746. **
  125747. ** CREATE TABLE <tbl>(input, token, start, end, position)
  125748. **
  125749. ** When queried, the query must include a WHERE clause of type:
  125750. **
  125751. ** input = <string>
  125752. **
  125753. ** The virtual table module tokenizes this <string>, using the FTS3
  125754. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  125755. ** statement and returns one row for each token in the result. With
  125756. ** fields set as follows:
  125757. **
  125758. ** input: Always set to a copy of <string>
  125759. ** token: A token from the input.
  125760. ** start: Byte offset of the token within the input <string>.
  125761. ** end: Byte offset of the byte immediately following the end of the
  125762. ** token within the input string.
  125763. ** pos: Token offset of token within input.
  125764. **
  125765. */
  125766. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125767. /* #include <string.h> */
  125768. /* #include <assert.h> */
  125769. typedef struct Fts3tokTable Fts3tokTable;
  125770. typedef struct Fts3tokCursor Fts3tokCursor;
  125771. /*
  125772. ** Virtual table structure.
  125773. */
  125774. struct Fts3tokTable {
  125775. sqlite3_vtab base; /* Base class used by SQLite core */
  125776. const sqlite3_tokenizer_module *pMod;
  125777. sqlite3_tokenizer *pTok;
  125778. };
  125779. /*
  125780. ** Virtual table cursor structure.
  125781. */
  125782. struct Fts3tokCursor {
  125783. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  125784. char *zInput; /* Input string */
  125785. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  125786. int iRowid; /* Current 'rowid' value */
  125787. const char *zToken; /* Current 'token' value */
  125788. int nToken; /* Size of zToken in bytes */
  125789. int iStart; /* Current 'start' value */
  125790. int iEnd; /* Current 'end' value */
  125791. int iPos; /* Current 'pos' value */
  125792. };
  125793. /*
  125794. ** Query FTS for the tokenizer implementation named zName.
  125795. */
  125796. static int fts3tokQueryTokenizer(
  125797. Fts3Hash *pHash,
  125798. const char *zName,
  125799. const sqlite3_tokenizer_module **pp,
  125800. char **pzErr
  125801. ){
  125802. sqlite3_tokenizer_module *p;
  125803. int nName = (int)strlen(zName);
  125804. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  125805. if( !p ){
  125806. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125807. return SQLITE_ERROR;
  125808. }
  125809. *pp = p;
  125810. return SQLITE_OK;
  125811. }
  125812. /*
  125813. ** The second argument, argv[], is an array of pointers to nul-terminated
  125814. ** strings. This function makes a copy of the array and strings into a
  125815. ** single block of memory. It then dequotes any of the strings that appear
  125816. ** to be quoted.
  125817. **
  125818. ** If successful, output parameter *pazDequote is set to point at the
  125819. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  125820. ** responsible for eventually calling sqlite3_free() to free the array
  125821. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  125822. ** The final value of *pazDequote is undefined in this case.
  125823. */
  125824. static int fts3tokDequoteArray(
  125825. int argc, /* Number of elements in argv[] */
  125826. const char * const *argv, /* Input array */
  125827. char ***pazDequote /* Output array */
  125828. ){
  125829. int rc = SQLITE_OK; /* Return code */
  125830. if( argc==0 ){
  125831. *pazDequote = 0;
  125832. }else{
  125833. int i;
  125834. int nByte = 0;
  125835. char **azDequote;
  125836. for(i=0; i<argc; i++){
  125837. nByte += (int)(strlen(argv[i]) + 1);
  125838. }
  125839. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  125840. if( azDequote==0 ){
  125841. rc = SQLITE_NOMEM;
  125842. }else{
  125843. char *pSpace = (char *)&azDequote[argc];
  125844. for(i=0; i<argc; i++){
  125845. int n = (int)strlen(argv[i]);
  125846. azDequote[i] = pSpace;
  125847. memcpy(pSpace, argv[i], n+1);
  125848. sqlite3Fts3Dequote(pSpace);
  125849. pSpace += (n+1);
  125850. }
  125851. }
  125852. }
  125853. return rc;
  125854. }
  125855. /*
  125856. ** Schema of the tokenizer table.
  125857. */
  125858. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  125859. /*
  125860. ** This function does all the work for both the xConnect and xCreate methods.
  125861. ** These tables have no persistent representation of their own, so xConnect
  125862. ** and xCreate are identical operations.
  125863. **
  125864. ** argv[0]: module name
  125865. ** argv[1]: database name
  125866. ** argv[2]: table name
  125867. ** argv[3]: first argument (tokenizer name)
  125868. */
  125869. static int fts3tokConnectMethod(
  125870. sqlite3 *db, /* Database connection */
  125871. void *pHash, /* Hash table of tokenizers */
  125872. int argc, /* Number of elements in argv array */
  125873. const char * const *argv, /* xCreate/xConnect argument array */
  125874. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  125875. char **pzErr /* OUT: sqlite3_malloc'd error message */
  125876. ){
  125877. Fts3tokTable *pTab;
  125878. const sqlite3_tokenizer_module *pMod = 0;
  125879. sqlite3_tokenizer *pTok = 0;
  125880. int rc;
  125881. char **azDequote = 0;
  125882. int nDequote;
  125883. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  125884. if( rc!=SQLITE_OK ) return rc;
  125885. nDequote = argc-3;
  125886. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  125887. if( rc==SQLITE_OK ){
  125888. const char *zModule;
  125889. if( nDequote<1 ){
  125890. zModule = "simple";
  125891. }else{
  125892. zModule = azDequote[0];
  125893. }
  125894. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  125895. }
  125896. assert( (rc==SQLITE_OK)==(pMod!=0) );
  125897. if( rc==SQLITE_OK ){
  125898. const char * const *azArg = (const char * const *)&azDequote[1];
  125899. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  125900. }
  125901. if( rc==SQLITE_OK ){
  125902. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  125903. if( pTab==0 ){
  125904. rc = SQLITE_NOMEM;
  125905. }
  125906. }
  125907. if( rc==SQLITE_OK ){
  125908. memset(pTab, 0, sizeof(Fts3tokTable));
  125909. pTab->pMod = pMod;
  125910. pTab->pTok = pTok;
  125911. *ppVtab = &pTab->base;
  125912. }else{
  125913. if( pTok ){
  125914. pMod->xDestroy(pTok);
  125915. }
  125916. }
  125917. sqlite3_free(azDequote);
  125918. return rc;
  125919. }
  125920. /*
  125921. ** This function does the work for both the xDisconnect and xDestroy methods.
  125922. ** These tables have no persistent representation of their own, so xDisconnect
  125923. ** and xDestroy are identical operations.
  125924. */
  125925. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  125926. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  125927. pTab->pMod->xDestroy(pTab->pTok);
  125928. sqlite3_free(pTab);
  125929. return SQLITE_OK;
  125930. }
  125931. /*
  125932. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  125933. */
  125934. static int fts3tokBestIndexMethod(
  125935. sqlite3_vtab *pVTab,
  125936. sqlite3_index_info *pInfo
  125937. ){
  125938. int i;
  125939. UNUSED_PARAMETER(pVTab);
  125940. for(i=0; i<pInfo->nConstraint; i++){
  125941. if( pInfo->aConstraint[i].usable
  125942. && pInfo->aConstraint[i].iColumn==0
  125943. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  125944. ){
  125945. pInfo->idxNum = 1;
  125946. pInfo->aConstraintUsage[i].argvIndex = 1;
  125947. pInfo->aConstraintUsage[i].omit = 1;
  125948. pInfo->estimatedCost = 1;
  125949. return SQLITE_OK;
  125950. }
  125951. }
  125952. pInfo->idxNum = 0;
  125953. assert( pInfo->estimatedCost>1000000.0 );
  125954. return SQLITE_OK;
  125955. }
  125956. /*
  125957. ** xOpen - Open a cursor.
  125958. */
  125959. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  125960. Fts3tokCursor *pCsr;
  125961. UNUSED_PARAMETER(pVTab);
  125962. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  125963. if( pCsr==0 ){
  125964. return SQLITE_NOMEM;
  125965. }
  125966. memset(pCsr, 0, sizeof(Fts3tokCursor));
  125967. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  125968. return SQLITE_OK;
  125969. }
  125970. /*
  125971. ** Reset the tokenizer cursor passed as the only argument. As if it had
  125972. ** just been returned by fts3tokOpenMethod().
  125973. */
  125974. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  125975. if( pCsr->pCsr ){
  125976. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  125977. pTab->pMod->xClose(pCsr->pCsr);
  125978. pCsr->pCsr = 0;
  125979. }
  125980. sqlite3_free(pCsr->zInput);
  125981. pCsr->zInput = 0;
  125982. pCsr->zToken = 0;
  125983. pCsr->nToken = 0;
  125984. pCsr->iStart = 0;
  125985. pCsr->iEnd = 0;
  125986. pCsr->iPos = 0;
  125987. pCsr->iRowid = 0;
  125988. }
  125989. /*
  125990. ** xClose - Close a cursor.
  125991. */
  125992. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  125993. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  125994. fts3tokResetCursor(pCsr);
  125995. sqlite3_free(pCsr);
  125996. return SQLITE_OK;
  125997. }
  125998. /*
  125999. ** xNext - Advance the cursor to the next row, if any.
  126000. */
  126001. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  126002. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126003. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  126004. int rc; /* Return code */
  126005. pCsr->iRowid++;
  126006. rc = pTab->pMod->xNext(pCsr->pCsr,
  126007. &pCsr->zToken, &pCsr->nToken,
  126008. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  126009. );
  126010. if( rc!=SQLITE_OK ){
  126011. fts3tokResetCursor(pCsr);
  126012. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  126013. }
  126014. return rc;
  126015. }
  126016. /*
  126017. ** xFilter - Initialize a cursor to point at the start of its data.
  126018. */
  126019. static int fts3tokFilterMethod(
  126020. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  126021. int idxNum, /* Strategy index */
  126022. const char *idxStr, /* Unused */
  126023. int nVal, /* Number of elements in apVal */
  126024. sqlite3_value **apVal /* Arguments for the indexing scheme */
  126025. ){
  126026. int rc = SQLITE_ERROR;
  126027. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126028. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  126029. UNUSED_PARAMETER(idxStr);
  126030. UNUSED_PARAMETER(nVal);
  126031. fts3tokResetCursor(pCsr);
  126032. if( idxNum==1 ){
  126033. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  126034. int nByte = sqlite3_value_bytes(apVal[0]);
  126035. pCsr->zInput = sqlite3_malloc(nByte+1);
  126036. if( pCsr->zInput==0 ){
  126037. rc = SQLITE_NOMEM;
  126038. }else{
  126039. memcpy(pCsr->zInput, zByte, nByte);
  126040. pCsr->zInput[nByte] = 0;
  126041. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  126042. if( rc==SQLITE_OK ){
  126043. pCsr->pCsr->pTokenizer = pTab->pTok;
  126044. }
  126045. }
  126046. }
  126047. if( rc!=SQLITE_OK ) return rc;
  126048. return fts3tokNextMethod(pCursor);
  126049. }
  126050. /*
  126051. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  126052. */
  126053. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  126054. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126055. return (pCsr->zToken==0);
  126056. }
  126057. /*
  126058. ** xColumn - Return a column value.
  126059. */
  126060. static int fts3tokColumnMethod(
  126061. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  126062. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  126063. int iCol /* Index of column to read value from */
  126064. ){
  126065. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126066. /* CREATE TABLE x(input, token, start, end, position) */
  126067. switch( iCol ){
  126068. case 0:
  126069. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  126070. break;
  126071. case 1:
  126072. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  126073. break;
  126074. case 2:
  126075. sqlite3_result_int(pCtx, pCsr->iStart);
  126076. break;
  126077. case 3:
  126078. sqlite3_result_int(pCtx, pCsr->iEnd);
  126079. break;
  126080. default:
  126081. assert( iCol==4 );
  126082. sqlite3_result_int(pCtx, pCsr->iPos);
  126083. break;
  126084. }
  126085. return SQLITE_OK;
  126086. }
  126087. /*
  126088. ** xRowid - Return the current rowid for the cursor.
  126089. */
  126090. static int fts3tokRowidMethod(
  126091. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  126092. sqlite_int64 *pRowid /* OUT: Rowid value */
  126093. ){
  126094. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126095. *pRowid = (sqlite3_int64)pCsr->iRowid;
  126096. return SQLITE_OK;
  126097. }
  126098. /*
  126099. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  126100. ** if successful or an error code if sqlite3_create_module() fails.
  126101. */
  126102. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  126103. static const sqlite3_module fts3tok_module = {
  126104. 0, /* iVersion */
  126105. fts3tokConnectMethod, /* xCreate */
  126106. fts3tokConnectMethod, /* xConnect */
  126107. fts3tokBestIndexMethod, /* xBestIndex */
  126108. fts3tokDisconnectMethod, /* xDisconnect */
  126109. fts3tokDisconnectMethod, /* xDestroy */
  126110. fts3tokOpenMethod, /* xOpen */
  126111. fts3tokCloseMethod, /* xClose */
  126112. fts3tokFilterMethod, /* xFilter */
  126113. fts3tokNextMethod, /* xNext */
  126114. fts3tokEofMethod, /* xEof */
  126115. fts3tokColumnMethod, /* xColumn */
  126116. fts3tokRowidMethod, /* xRowid */
  126117. 0, /* xUpdate */
  126118. 0, /* xBegin */
  126119. 0, /* xSync */
  126120. 0, /* xCommit */
  126121. 0, /* xRollback */
  126122. 0, /* xFindFunction */
  126123. 0, /* xRename */
  126124. 0, /* xSavepoint */
  126125. 0, /* xRelease */
  126126. 0 /* xRollbackTo */
  126127. };
  126128. int rc; /* Return code */
  126129. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  126130. return rc;
  126131. }
  126132. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  126133. /************** End of fts3_tokenize_vtab.c **********************************/
  126134. /************** Begin file fts3_write.c **************************************/
  126135. /*
  126136. ** 2009 Oct 23
  126137. **
  126138. ** The author disclaims copyright to this source code. In place of
  126139. ** a legal notice, here is a blessing:
  126140. **
  126141. ** May you do good and not evil.
  126142. ** May you find forgiveness for yourself and forgive others.
  126143. ** May you share freely, never taking more than you give.
  126144. **
  126145. ******************************************************************************
  126146. **
  126147. ** This file is part of the SQLite FTS3 extension module. Specifically,
  126148. ** this file contains code to insert, update and delete rows from FTS3
  126149. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  126150. ** of the sub-routines used to merge segments are also used by the query
  126151. ** code in fts3.c.
  126152. */
  126153. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126154. /* #include <string.h> */
  126155. /* #include <assert.h> */
  126156. /* #include <stdlib.h> */
  126157. #define FTS_MAX_APPENDABLE_HEIGHT 16
  126158. /*
  126159. ** When full-text index nodes are loaded from disk, the buffer that they
  126160. ** are loaded into has the following number of bytes of padding at the end
  126161. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  126162. ** of 920 bytes is allocated for it.
  126163. **
  126164. ** This means that if we have a pointer into a buffer containing node data,
  126165. ** it is always safe to read up to two varints from it without risking an
  126166. ** overread, even if the node data is corrupted.
  126167. */
  126168. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  126169. /*
  126170. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  126171. ** memory incrementally instead of all at once. This can be a big performance
  126172. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  126173. ** method before retrieving all query results (as may happen, for example,
  126174. ** if a query has a LIMIT clause).
  126175. **
  126176. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  126177. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  126178. ** The code is written so that the hard lower-limit for each of these values
  126179. ** is 1. Clearly such small values would be inefficient, but can be useful
  126180. ** for testing purposes.
  126181. **
  126182. ** If this module is built with SQLITE_TEST defined, these constants may
  126183. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  126184. ** a Tcl interface to read and write the values.
  126185. */
  126186. #ifdef SQLITE_TEST
  126187. int test_fts3_node_chunksize = (4*1024);
  126188. int test_fts3_node_chunk_threshold = (4*1024)*4;
  126189. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  126190. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  126191. #else
  126192. # define FTS3_NODE_CHUNKSIZE (4*1024)
  126193. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  126194. #endif
  126195. /*
  126196. ** The two values that may be meaningfully bound to the :1 parameter in
  126197. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  126198. */
  126199. #define FTS_STAT_DOCTOTAL 0
  126200. #define FTS_STAT_INCRMERGEHINT 1
  126201. #define FTS_STAT_AUTOINCRMERGE 2
  126202. /*
  126203. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  126204. ** and incremental merge operation that takes place. This is used for
  126205. ** debugging FTS only, it should not usually be turned on in production
  126206. ** systems.
  126207. */
  126208. #ifdef FTS3_LOG_MERGES
  126209. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  126210. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  126211. }
  126212. #else
  126213. #define fts3LogMerge(x, y)
  126214. #endif
  126215. typedef struct PendingList PendingList;
  126216. typedef struct SegmentNode SegmentNode;
  126217. typedef struct SegmentWriter SegmentWriter;
  126218. /*
  126219. ** An instance of the following data structure is used to build doclists
  126220. ** incrementally. See function fts3PendingListAppend() for details.
  126221. */
  126222. struct PendingList {
  126223. int nData;
  126224. char *aData;
  126225. int nSpace;
  126226. sqlite3_int64 iLastDocid;
  126227. sqlite3_int64 iLastCol;
  126228. sqlite3_int64 iLastPos;
  126229. };
  126230. /*
  126231. ** Each cursor has a (possibly empty) linked list of the following objects.
  126232. */
  126233. struct Fts3DeferredToken {
  126234. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  126235. int iCol; /* Column token must occur in */
  126236. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  126237. PendingList *pList; /* Doclist is assembled here */
  126238. };
  126239. /*
  126240. ** An instance of this structure is used to iterate through the terms on
  126241. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  126242. ** this structure are only manipulated by code in this file, opaque handles
  126243. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  126244. ** terms when querying the full-text index. See functions:
  126245. **
  126246. ** sqlite3Fts3SegReaderNew()
  126247. ** sqlite3Fts3SegReaderFree()
  126248. ** sqlite3Fts3SegReaderIterate()
  126249. **
  126250. ** Methods used to manipulate Fts3SegReader structures:
  126251. **
  126252. ** fts3SegReaderNext()
  126253. ** fts3SegReaderFirstDocid()
  126254. ** fts3SegReaderNextDocid()
  126255. */
  126256. struct Fts3SegReader {
  126257. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  126258. u8 bLookup; /* True for a lookup only */
  126259. u8 rootOnly; /* True for a root-only reader */
  126260. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  126261. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  126262. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  126263. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  126264. char *aNode; /* Pointer to node data (or NULL) */
  126265. int nNode; /* Size of buffer at aNode (or 0) */
  126266. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  126267. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  126268. Fts3HashElem **ppNextElem;
  126269. /* Variables set by fts3SegReaderNext(). These may be read directly
  126270. ** by the caller. They are valid from the time SegmentReaderNew() returns
  126271. ** until SegmentReaderNext() returns something other than SQLITE_OK
  126272. ** (i.e. SQLITE_DONE).
  126273. */
  126274. int nTerm; /* Number of bytes in current term */
  126275. char *zTerm; /* Pointer to current term */
  126276. int nTermAlloc; /* Allocated size of zTerm buffer */
  126277. char *aDoclist; /* Pointer to doclist of current entry */
  126278. int nDoclist; /* Size of doclist in current entry */
  126279. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  126280. ** through the current doclist (aDoclist/nDoclist).
  126281. */
  126282. char *pOffsetList;
  126283. int nOffsetList; /* For descending pending seg-readers only */
  126284. sqlite3_int64 iDocid;
  126285. };
  126286. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  126287. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  126288. /*
  126289. ** An instance of this structure is used to create a segment b-tree in the
  126290. ** database. The internal details of this type are only accessed by the
  126291. ** following functions:
  126292. **
  126293. ** fts3SegWriterAdd()
  126294. ** fts3SegWriterFlush()
  126295. ** fts3SegWriterFree()
  126296. */
  126297. struct SegmentWriter {
  126298. SegmentNode *pTree; /* Pointer to interior tree structure */
  126299. sqlite3_int64 iFirst; /* First slot in %_segments written */
  126300. sqlite3_int64 iFree; /* Next free slot in %_segments */
  126301. char *zTerm; /* Pointer to previous term buffer */
  126302. int nTerm; /* Number of bytes in zTerm */
  126303. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  126304. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  126305. int nSize; /* Size of allocation at aData */
  126306. int nData; /* Bytes of data in aData */
  126307. char *aData; /* Pointer to block from malloc() */
  126308. };
  126309. /*
  126310. ** Type SegmentNode is used by the following three functions to create
  126311. ** the interior part of the segment b+-tree structures (everything except
  126312. ** the leaf nodes). These functions and type are only ever used by code
  126313. ** within the fts3SegWriterXXX() family of functions described above.
  126314. **
  126315. ** fts3NodeAddTerm()
  126316. ** fts3NodeWrite()
  126317. ** fts3NodeFree()
  126318. **
  126319. ** When a b+tree is written to the database (either as a result of a merge
  126320. ** or the pending-terms table being flushed), leaves are written into the
  126321. ** database file as soon as they are completely populated. The interior of
  126322. ** the tree is assembled in memory and written out only once all leaves have
  126323. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  126324. ** very large, meaning that the interior of the tree consumes relatively
  126325. ** little memory.
  126326. */
  126327. struct SegmentNode {
  126328. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  126329. SegmentNode *pRight; /* Pointer to right-sibling */
  126330. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  126331. int nEntry; /* Number of terms written to node so far */
  126332. char *zTerm; /* Pointer to previous term buffer */
  126333. int nTerm; /* Number of bytes in zTerm */
  126334. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  126335. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  126336. int nData; /* Bytes of valid data so far */
  126337. char *aData; /* Node data */
  126338. };
  126339. /*
  126340. ** Valid values for the second argument to fts3SqlStmt().
  126341. */
  126342. #define SQL_DELETE_CONTENT 0
  126343. #define SQL_IS_EMPTY 1
  126344. #define SQL_DELETE_ALL_CONTENT 2
  126345. #define SQL_DELETE_ALL_SEGMENTS 3
  126346. #define SQL_DELETE_ALL_SEGDIR 4
  126347. #define SQL_DELETE_ALL_DOCSIZE 5
  126348. #define SQL_DELETE_ALL_STAT 6
  126349. #define SQL_SELECT_CONTENT_BY_ROWID 7
  126350. #define SQL_NEXT_SEGMENT_INDEX 8
  126351. #define SQL_INSERT_SEGMENTS 9
  126352. #define SQL_NEXT_SEGMENTS_ID 10
  126353. #define SQL_INSERT_SEGDIR 11
  126354. #define SQL_SELECT_LEVEL 12
  126355. #define SQL_SELECT_LEVEL_RANGE 13
  126356. #define SQL_SELECT_LEVEL_COUNT 14
  126357. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  126358. #define SQL_DELETE_SEGDIR_LEVEL 16
  126359. #define SQL_DELETE_SEGMENTS_RANGE 17
  126360. #define SQL_CONTENT_INSERT 18
  126361. #define SQL_DELETE_DOCSIZE 19
  126362. #define SQL_REPLACE_DOCSIZE 20
  126363. #define SQL_SELECT_DOCSIZE 21
  126364. #define SQL_SELECT_STAT 22
  126365. #define SQL_REPLACE_STAT 23
  126366. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  126367. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  126368. #define SQL_DELETE_SEGDIR_RANGE 26
  126369. #define SQL_SELECT_ALL_LANGID 27
  126370. #define SQL_FIND_MERGE_LEVEL 28
  126371. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  126372. #define SQL_DELETE_SEGDIR_ENTRY 30
  126373. #define SQL_SHIFT_SEGDIR_ENTRY 31
  126374. #define SQL_SELECT_SEGDIR 32
  126375. #define SQL_CHOMP_SEGDIR 33
  126376. #define SQL_SEGMENT_IS_APPENDABLE 34
  126377. #define SQL_SELECT_INDEXES 35
  126378. #define SQL_SELECT_MXLEVEL 36
  126379. /*
  126380. ** This function is used to obtain an SQLite prepared statement handle
  126381. ** for the statement identified by the second argument. If successful,
  126382. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  126383. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  126384. **
  126385. ** If argument apVal is not NULL, then it must point to an array with
  126386. ** at least as many entries as the requested statement has bound
  126387. ** parameters. The values are bound to the statements parameters before
  126388. ** returning.
  126389. */
  126390. static int fts3SqlStmt(
  126391. Fts3Table *p, /* Virtual table handle */
  126392. int eStmt, /* One of the SQL_XXX constants above */
  126393. sqlite3_stmt **pp, /* OUT: Statement handle */
  126394. sqlite3_value **apVal /* Values to bind to statement */
  126395. ){
  126396. const char *azSql[] = {
  126397. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  126398. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  126399. /* 2 */ "DELETE FROM %Q.'%q_content'",
  126400. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  126401. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  126402. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  126403. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  126404. /* 7 */ "SELECT %s WHERE rowid=?",
  126405. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  126406. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  126407. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  126408. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  126409. /* Return segments in order from oldest to newest.*/
  126410. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126411. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  126412. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126413. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  126414. "ORDER BY level DESC, idx ASC",
  126415. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  126416. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  126417. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  126418. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  126419. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  126420. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  126421. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  126422. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  126423. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  126424. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  126425. /* 24 */ "",
  126426. /* 25 */ "",
  126427. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  126428. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  126429. /* This statement is used to determine which level to read the input from
  126430. ** when performing an incremental merge. It returns the absolute level number
  126431. ** of the oldest level in the db that contains at least ? segments. Or,
  126432. ** if no level in the FTS index contains more than ? segments, the statement
  126433. ** returns zero rows. */
  126434. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  126435. " ORDER BY (level %% 1024) ASC LIMIT 1",
  126436. /* Estimate the upper limit on the number of leaf nodes in a new segment
  126437. ** created by merging the oldest :2 segments from absolute level :1. See
  126438. ** function sqlite3Fts3Incrmerge() for details. */
  126439. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  126440. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  126441. /* SQL_DELETE_SEGDIR_ENTRY
  126442. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  126443. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  126444. /* SQL_SHIFT_SEGDIR_ENTRY
  126445. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  126446. ** to :1. */
  126447. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  126448. /* SQL_SELECT_SEGDIR
  126449. ** Read a single entry from the %_segdir table. The entry from absolute
  126450. ** level :1 with index value :2. */
  126451. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126452. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  126453. /* SQL_CHOMP_SEGDIR
  126454. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  126455. ** entry located on absolute level :3 with index :4. */
  126456. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  126457. "WHERE level = ? AND idx = ?",
  126458. /* SQL_SEGMENT_IS_APPENDABLE
  126459. ** Return a single row if the segment with end_block=? is appendable. Or
  126460. ** no rows otherwise. */
  126461. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  126462. /* SQL_SELECT_INDEXES
  126463. ** Return the list of valid segment indexes for absolute level ? */
  126464. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  126465. /* SQL_SELECT_MXLEVEL
  126466. ** Return the largest relative level in the FTS index or indexes. */
  126467. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  126468. };
  126469. int rc = SQLITE_OK;
  126470. sqlite3_stmt *pStmt;
  126471. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  126472. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  126473. pStmt = p->aStmt[eStmt];
  126474. if( !pStmt ){
  126475. char *zSql;
  126476. if( eStmt==SQL_CONTENT_INSERT ){
  126477. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  126478. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  126479. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  126480. }else{
  126481. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  126482. }
  126483. if( !zSql ){
  126484. rc = SQLITE_NOMEM;
  126485. }else{
  126486. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  126487. sqlite3_free(zSql);
  126488. assert( rc==SQLITE_OK || pStmt==0 );
  126489. p->aStmt[eStmt] = pStmt;
  126490. }
  126491. }
  126492. if( apVal ){
  126493. int i;
  126494. int nParam = sqlite3_bind_parameter_count(pStmt);
  126495. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  126496. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  126497. }
  126498. }
  126499. *pp = pStmt;
  126500. return rc;
  126501. }
  126502. static int fts3SelectDocsize(
  126503. Fts3Table *pTab, /* FTS3 table handle */
  126504. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  126505. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126506. ){
  126507. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  126508. int rc; /* Return code */
  126509. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  126510. if( rc==SQLITE_OK ){
  126511. sqlite3_bind_int64(pStmt, 1, iDocid);
  126512. rc = sqlite3_step(pStmt);
  126513. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  126514. rc = sqlite3_reset(pStmt);
  126515. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  126516. pStmt = 0;
  126517. }else{
  126518. rc = SQLITE_OK;
  126519. }
  126520. }
  126521. *ppStmt = pStmt;
  126522. return rc;
  126523. }
  126524. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  126525. Fts3Table *pTab, /* Fts3 table handle */
  126526. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126527. ){
  126528. sqlite3_stmt *pStmt = 0;
  126529. int rc;
  126530. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  126531. if( rc==SQLITE_OK ){
  126532. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  126533. if( sqlite3_step(pStmt)!=SQLITE_ROW
  126534. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  126535. ){
  126536. rc = sqlite3_reset(pStmt);
  126537. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  126538. pStmt = 0;
  126539. }
  126540. }
  126541. *ppStmt = pStmt;
  126542. return rc;
  126543. }
  126544. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  126545. Fts3Table *pTab, /* Fts3 table handle */
  126546. sqlite3_int64 iDocid, /* Docid to read size data for */
  126547. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126548. ){
  126549. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  126550. }
  126551. /*
  126552. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  126553. ** array apVal[] to the SQL statement identified by eStmt, the statement
  126554. ** is executed.
  126555. **
  126556. ** Returns SQLITE_OK if the statement is successfully executed, or an
  126557. ** SQLite error code otherwise.
  126558. */
  126559. static void fts3SqlExec(
  126560. int *pRC, /* Result code */
  126561. Fts3Table *p, /* The FTS3 table */
  126562. int eStmt, /* Index of statement to evaluate */
  126563. sqlite3_value **apVal /* Parameters to bind */
  126564. ){
  126565. sqlite3_stmt *pStmt;
  126566. int rc;
  126567. if( *pRC ) return;
  126568. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  126569. if( rc==SQLITE_OK ){
  126570. sqlite3_step(pStmt);
  126571. rc = sqlite3_reset(pStmt);
  126572. }
  126573. *pRC = rc;
  126574. }
  126575. /*
  126576. ** This function ensures that the caller has obtained an exclusive
  126577. ** shared-cache table-lock on the %_segdir table. This is required before
  126578. ** writing data to the fts3 table. If this lock is not acquired first, then
  126579. ** the caller may end up attempting to take this lock as part of committing
  126580. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  126581. ** LOCKED_SHAREDCACHEto a COMMIT command.
  126582. **
  126583. ** It is best to avoid this because if FTS3 returns any error when
  126584. ** committing a transaction, the whole transaction will be rolled back.
  126585. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  126586. ** It can still happen if the user locks the underlying tables directly
  126587. ** instead of accessing them via FTS.
  126588. */
  126589. static int fts3Writelock(Fts3Table *p){
  126590. int rc = SQLITE_OK;
  126591. if( p->nPendingData==0 ){
  126592. sqlite3_stmt *pStmt;
  126593. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  126594. if( rc==SQLITE_OK ){
  126595. sqlite3_bind_null(pStmt, 1);
  126596. sqlite3_step(pStmt);
  126597. rc = sqlite3_reset(pStmt);
  126598. }
  126599. }
  126600. return rc;
  126601. }
  126602. /*
  126603. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  126604. ** Within each language id, a separate index is maintained to store the
  126605. ** document terms, and each configured prefix size (configured the FTS
  126606. ** "prefix=" option). And each index consists of multiple levels ("relative
  126607. ** levels").
  126608. **
  126609. ** All three of these values (the language id, the specific index and the
  126610. ** level within the index) are encoded in 64-bit integer values stored
  126611. ** in the %_segdir table on disk. This function is used to convert three
  126612. ** separate component values into the single 64-bit integer value that
  126613. ** can be used to query the %_segdir table.
  126614. **
  126615. ** Specifically, each language-id/index combination is allocated 1024
  126616. ** 64-bit integer level values ("absolute levels"). The main terms index
  126617. ** for language-id 0 is allocate values 0-1023. The first prefix index
  126618. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  126619. ** Language 1 indexes are allocated immediately following language 0.
  126620. **
  126621. ** So, for a system with nPrefix prefix indexes configured, the block of
  126622. ** absolute levels that corresponds to language-id iLangid and index
  126623. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  126624. */
  126625. static sqlite3_int64 getAbsoluteLevel(
  126626. Fts3Table *p, /* FTS3 table handle */
  126627. int iLangid, /* Language id */
  126628. int iIndex, /* Index in p->aIndex[] */
  126629. int iLevel /* Level of segments */
  126630. ){
  126631. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  126632. assert( iLangid>=0 );
  126633. assert( p->nIndex>0 );
  126634. assert( iIndex>=0 && iIndex<p->nIndex );
  126635. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  126636. return iBase + iLevel;
  126637. }
  126638. /*
  126639. ** Set *ppStmt to a statement handle that may be used to iterate through
  126640. ** all rows in the %_segdir table, from oldest to newest. If successful,
  126641. ** return SQLITE_OK. If an error occurs while preparing the statement,
  126642. ** return an SQLite error code.
  126643. **
  126644. ** There is only ever one instance of this SQL statement compiled for
  126645. ** each FTS3 table.
  126646. **
  126647. ** The statement returns the following columns from the %_segdir table:
  126648. **
  126649. ** 0: idx
  126650. ** 1: start_block
  126651. ** 2: leaves_end_block
  126652. ** 3: end_block
  126653. ** 4: root
  126654. */
  126655. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  126656. Fts3Table *p, /* FTS3 table */
  126657. int iLangid, /* Language being queried */
  126658. int iIndex, /* Index for p->aIndex[] */
  126659. int iLevel, /* Level to select (relative level) */
  126660. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  126661. ){
  126662. int rc;
  126663. sqlite3_stmt *pStmt = 0;
  126664. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  126665. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  126666. assert( iIndex>=0 && iIndex<p->nIndex );
  126667. if( iLevel<0 ){
  126668. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  126669. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  126670. if( rc==SQLITE_OK ){
  126671. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  126672. sqlite3_bind_int64(pStmt, 2,
  126673. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  126674. );
  126675. }
  126676. }else{
  126677. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  126678. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  126679. if( rc==SQLITE_OK ){
  126680. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  126681. }
  126682. }
  126683. *ppStmt = pStmt;
  126684. return rc;
  126685. }
  126686. /*
  126687. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  126688. ** if successful, or an SQLite error code otherwise.
  126689. **
  126690. ** This function also serves to allocate the PendingList structure itself.
  126691. ** For example, to create a new PendingList structure containing two
  126692. ** varints:
  126693. **
  126694. ** PendingList *p = 0;
  126695. ** fts3PendingListAppendVarint(&p, 1);
  126696. ** fts3PendingListAppendVarint(&p, 2);
  126697. */
  126698. static int fts3PendingListAppendVarint(
  126699. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  126700. sqlite3_int64 i /* Value to append to data */
  126701. ){
  126702. PendingList *p = *pp;
  126703. /* Allocate or grow the PendingList as required. */
  126704. if( !p ){
  126705. p = sqlite3_malloc(sizeof(*p) + 100);
  126706. if( !p ){
  126707. return SQLITE_NOMEM;
  126708. }
  126709. p->nSpace = 100;
  126710. p->aData = (char *)&p[1];
  126711. p->nData = 0;
  126712. }
  126713. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  126714. int nNew = p->nSpace * 2;
  126715. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  126716. if( !p ){
  126717. sqlite3_free(*pp);
  126718. *pp = 0;
  126719. return SQLITE_NOMEM;
  126720. }
  126721. p->nSpace = nNew;
  126722. p->aData = (char *)&p[1];
  126723. }
  126724. /* Append the new serialized varint to the end of the list. */
  126725. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  126726. p->aData[p->nData] = '\0';
  126727. *pp = p;
  126728. return SQLITE_OK;
  126729. }
  126730. /*
  126731. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  126732. ** is returned if the structure is sqlite3_realloced as part of adding
  126733. ** the entry. Otherwise, zero.
  126734. **
  126735. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  126736. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  126737. ** it is set to SQLITE_OK.
  126738. */
  126739. static int fts3PendingListAppend(
  126740. PendingList **pp, /* IN/OUT: PendingList structure */
  126741. sqlite3_int64 iDocid, /* Docid for entry to add */
  126742. sqlite3_int64 iCol, /* Column for entry to add */
  126743. sqlite3_int64 iPos, /* Position of term for entry to add */
  126744. int *pRc /* OUT: Return code */
  126745. ){
  126746. PendingList *p = *pp;
  126747. int rc = SQLITE_OK;
  126748. assert( !p || p->iLastDocid<=iDocid );
  126749. if( !p || p->iLastDocid!=iDocid ){
  126750. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  126751. if( p ){
  126752. assert( p->nData<p->nSpace );
  126753. assert( p->aData[p->nData]==0 );
  126754. p->nData++;
  126755. }
  126756. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  126757. goto pendinglistappend_out;
  126758. }
  126759. p->iLastCol = -1;
  126760. p->iLastPos = 0;
  126761. p->iLastDocid = iDocid;
  126762. }
  126763. if( iCol>0 && p->iLastCol!=iCol ){
  126764. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  126765. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  126766. ){
  126767. goto pendinglistappend_out;
  126768. }
  126769. p->iLastCol = iCol;
  126770. p->iLastPos = 0;
  126771. }
  126772. if( iCol>=0 ){
  126773. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  126774. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  126775. if( rc==SQLITE_OK ){
  126776. p->iLastPos = iPos;
  126777. }
  126778. }
  126779. pendinglistappend_out:
  126780. *pRc = rc;
  126781. if( p!=*pp ){
  126782. *pp = p;
  126783. return 1;
  126784. }
  126785. return 0;
  126786. }
  126787. /*
  126788. ** Free a PendingList object allocated by fts3PendingListAppend().
  126789. */
  126790. static void fts3PendingListDelete(PendingList *pList){
  126791. sqlite3_free(pList);
  126792. }
  126793. /*
  126794. ** Add an entry to one of the pending-terms hash tables.
  126795. */
  126796. static int fts3PendingTermsAddOne(
  126797. Fts3Table *p,
  126798. int iCol,
  126799. int iPos,
  126800. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  126801. const char *zToken,
  126802. int nToken
  126803. ){
  126804. PendingList *pList;
  126805. int rc = SQLITE_OK;
  126806. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  126807. if( pList ){
  126808. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  126809. }
  126810. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  126811. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  126812. /* Malloc failed while inserting the new entry. This can only
  126813. ** happen if there was no previous entry for this token.
  126814. */
  126815. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  126816. sqlite3_free(pList);
  126817. rc = SQLITE_NOMEM;
  126818. }
  126819. }
  126820. if( rc==SQLITE_OK ){
  126821. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  126822. }
  126823. return rc;
  126824. }
  126825. /*
  126826. ** Tokenize the nul-terminated string zText and add all tokens to the
  126827. ** pending-terms hash-table. The docid used is that currently stored in
  126828. ** p->iPrevDocid, and the column is specified by argument iCol.
  126829. **
  126830. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  126831. */
  126832. static int fts3PendingTermsAdd(
  126833. Fts3Table *p, /* Table into which text will be inserted */
  126834. int iLangid, /* Language id to use */
  126835. const char *zText, /* Text of document to be inserted */
  126836. int iCol, /* Column into which text is being inserted */
  126837. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  126838. ){
  126839. int rc;
  126840. int iStart = 0;
  126841. int iEnd = 0;
  126842. int iPos = 0;
  126843. int nWord = 0;
  126844. char const *zToken;
  126845. int nToken = 0;
  126846. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  126847. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  126848. sqlite3_tokenizer_cursor *pCsr;
  126849. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  126850. const char**,int*,int*,int*,int*);
  126851. assert( pTokenizer && pModule );
  126852. /* If the user has inserted a NULL value, this function may be called with
  126853. ** zText==0. In this case, add zero token entries to the hash table and
  126854. ** return early. */
  126855. if( zText==0 ){
  126856. *pnWord = 0;
  126857. return SQLITE_OK;
  126858. }
  126859. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  126860. if( rc!=SQLITE_OK ){
  126861. return rc;
  126862. }
  126863. xNext = pModule->xNext;
  126864. while( SQLITE_OK==rc
  126865. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  126866. ){
  126867. int i;
  126868. if( iPos>=nWord ) nWord = iPos+1;
  126869. /* Positions cannot be negative; we use -1 as a terminator internally.
  126870. ** Tokens must have a non-zero length.
  126871. */
  126872. if( iPos<0 || !zToken || nToken<=0 ){
  126873. rc = SQLITE_ERROR;
  126874. break;
  126875. }
  126876. /* Add the term to the terms index */
  126877. rc = fts3PendingTermsAddOne(
  126878. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  126879. );
  126880. /* Add the term to each of the prefix indexes that it is not too
  126881. ** short for. */
  126882. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  126883. struct Fts3Index *pIndex = &p->aIndex[i];
  126884. if( nToken<pIndex->nPrefix ) continue;
  126885. rc = fts3PendingTermsAddOne(
  126886. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  126887. );
  126888. }
  126889. }
  126890. pModule->xClose(pCsr);
  126891. *pnWord += nWord;
  126892. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  126893. }
  126894. /*
  126895. ** Calling this function indicates that subsequent calls to
  126896. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  126897. ** contents of the document with docid iDocid.
  126898. */
  126899. static int fts3PendingTermsDocid(
  126900. Fts3Table *p, /* Full-text table handle */
  126901. int iLangid, /* Language id of row being written */
  126902. sqlite_int64 iDocid /* Docid of row being written */
  126903. ){
  126904. assert( iLangid>=0 );
  126905. /* TODO(shess) Explore whether partially flushing the buffer on
  126906. ** forced-flush would provide better performance. I suspect that if
  126907. ** we ordered the doclists by size and flushed the largest until the
  126908. ** buffer was half empty, that would let the less frequent terms
  126909. ** generate longer doclists.
  126910. */
  126911. if( iDocid<=p->iPrevDocid
  126912. || p->iPrevLangid!=iLangid
  126913. || p->nPendingData>p->nMaxPendingData
  126914. ){
  126915. int rc = sqlite3Fts3PendingTermsFlush(p);
  126916. if( rc!=SQLITE_OK ) return rc;
  126917. }
  126918. p->iPrevDocid = iDocid;
  126919. p->iPrevLangid = iLangid;
  126920. return SQLITE_OK;
  126921. }
  126922. /*
  126923. ** Discard the contents of the pending-terms hash tables.
  126924. */
  126925. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  126926. int i;
  126927. for(i=0; i<p->nIndex; i++){
  126928. Fts3HashElem *pElem;
  126929. Fts3Hash *pHash = &p->aIndex[i].hPending;
  126930. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  126931. PendingList *pList = (PendingList *)fts3HashData(pElem);
  126932. fts3PendingListDelete(pList);
  126933. }
  126934. fts3HashClear(pHash);
  126935. }
  126936. p->nPendingData = 0;
  126937. }
  126938. /*
  126939. ** This function is called by the xUpdate() method as part of an INSERT
  126940. ** operation. It adds entries for each term in the new record to the
  126941. ** pendingTerms hash table.
  126942. **
  126943. ** Argument apVal is the same as the similarly named argument passed to
  126944. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  126945. */
  126946. static int fts3InsertTerms(
  126947. Fts3Table *p,
  126948. int iLangid,
  126949. sqlite3_value **apVal,
  126950. u32 *aSz
  126951. ){
  126952. int i; /* Iterator variable */
  126953. for(i=2; i<p->nColumn+2; i++){
  126954. int iCol = i-2;
  126955. if( p->abNotindexed[iCol]==0 ){
  126956. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  126957. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  126958. if( rc!=SQLITE_OK ){
  126959. return rc;
  126960. }
  126961. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  126962. }
  126963. }
  126964. return SQLITE_OK;
  126965. }
  126966. /*
  126967. ** This function is called by the xUpdate() method for an INSERT operation.
  126968. ** The apVal parameter is passed a copy of the apVal argument passed by
  126969. ** SQLite to the xUpdate() method. i.e:
  126970. **
  126971. ** apVal[0] Not used for INSERT.
  126972. ** apVal[1] rowid
  126973. ** apVal[2] Left-most user-defined column
  126974. ** ...
  126975. ** apVal[p->nColumn+1] Right-most user-defined column
  126976. ** apVal[p->nColumn+2] Hidden column with same name as table
  126977. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  126978. ** apVal[p->nColumn+4] Hidden languageid column
  126979. */
  126980. static int fts3InsertData(
  126981. Fts3Table *p, /* Full-text table */
  126982. sqlite3_value **apVal, /* Array of values to insert */
  126983. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  126984. ){
  126985. int rc; /* Return code */
  126986. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  126987. if( p->zContentTbl ){
  126988. sqlite3_value *pRowid = apVal[p->nColumn+3];
  126989. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  126990. pRowid = apVal[1];
  126991. }
  126992. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  126993. return SQLITE_CONSTRAINT;
  126994. }
  126995. *piDocid = sqlite3_value_int64(pRowid);
  126996. return SQLITE_OK;
  126997. }
  126998. /* Locate the statement handle used to insert data into the %_content
  126999. ** table. The SQL for this statement is:
  127000. **
  127001. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  127002. **
  127003. ** The statement features N '?' variables, where N is the number of user
  127004. ** defined columns in the FTS3 table, plus one for the docid field.
  127005. */
  127006. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  127007. if( rc==SQLITE_OK && p->zLanguageid ){
  127008. rc = sqlite3_bind_int(
  127009. pContentInsert, p->nColumn+2,
  127010. sqlite3_value_int(apVal[p->nColumn+4])
  127011. );
  127012. }
  127013. if( rc!=SQLITE_OK ) return rc;
  127014. /* There is a quirk here. The users INSERT statement may have specified
  127015. ** a value for the "rowid" field, for the "docid" field, or for both.
  127016. ** Which is a problem, since "rowid" and "docid" are aliases for the
  127017. ** same value. For example:
  127018. **
  127019. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  127020. **
  127021. ** In FTS3, this is an error. It is an error to specify non-NULL values
  127022. ** for both docid and some other rowid alias.
  127023. */
  127024. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  127025. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  127026. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  127027. ){
  127028. /* A rowid/docid conflict. */
  127029. return SQLITE_ERROR;
  127030. }
  127031. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  127032. if( rc!=SQLITE_OK ) return rc;
  127033. }
  127034. /* Execute the statement to insert the record. Set *piDocid to the
  127035. ** new docid value.
  127036. */
  127037. sqlite3_step(pContentInsert);
  127038. rc = sqlite3_reset(pContentInsert);
  127039. *piDocid = sqlite3_last_insert_rowid(p->db);
  127040. return rc;
  127041. }
  127042. /*
  127043. ** Remove all data from the FTS3 table. Clear the hash table containing
  127044. ** pending terms.
  127045. */
  127046. static int fts3DeleteAll(Fts3Table *p, int bContent){
  127047. int rc = SQLITE_OK; /* Return code */
  127048. /* Discard the contents of the pending-terms hash table. */
  127049. sqlite3Fts3PendingTermsClear(p);
  127050. /* Delete everything from the shadow tables. Except, leave %_content as
  127051. ** is if bContent is false. */
  127052. assert( p->zContentTbl==0 || bContent==0 );
  127053. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  127054. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  127055. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  127056. if( p->bHasDocsize ){
  127057. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  127058. }
  127059. if( p->bHasStat ){
  127060. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  127061. }
  127062. return rc;
  127063. }
  127064. /*
  127065. **
  127066. */
  127067. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  127068. int iLangid = 0;
  127069. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  127070. return iLangid;
  127071. }
  127072. /*
  127073. ** The first element in the apVal[] array is assumed to contain the docid
  127074. ** (an integer) of a row about to be deleted. Remove all terms from the
  127075. ** full-text index.
  127076. */
  127077. static void fts3DeleteTerms(
  127078. int *pRC, /* Result code */
  127079. Fts3Table *p, /* The FTS table to delete from */
  127080. sqlite3_value *pRowid, /* The docid to be deleted */
  127081. u32 *aSz, /* Sizes of deleted document written here */
  127082. int *pbFound /* OUT: Set to true if row really does exist */
  127083. ){
  127084. int rc;
  127085. sqlite3_stmt *pSelect;
  127086. assert( *pbFound==0 );
  127087. if( *pRC ) return;
  127088. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  127089. if( rc==SQLITE_OK ){
  127090. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  127091. int i;
  127092. int iLangid = langidFromSelect(p, pSelect);
  127093. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  127094. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  127095. int iCol = i-1;
  127096. if( p->abNotindexed[iCol]==0 ){
  127097. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  127098. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  127099. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  127100. }
  127101. }
  127102. if( rc!=SQLITE_OK ){
  127103. sqlite3_reset(pSelect);
  127104. *pRC = rc;
  127105. return;
  127106. }
  127107. *pbFound = 1;
  127108. }
  127109. rc = sqlite3_reset(pSelect);
  127110. }else{
  127111. sqlite3_reset(pSelect);
  127112. }
  127113. *pRC = rc;
  127114. }
  127115. /*
  127116. ** Forward declaration to account for the circular dependency between
  127117. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  127118. */
  127119. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  127120. /*
  127121. ** This function allocates a new level iLevel index in the segdir table.
  127122. ** Usually, indexes are allocated within a level sequentially starting
  127123. ** with 0, so the allocated index is one greater than the value returned
  127124. ** by:
  127125. **
  127126. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  127127. **
  127128. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  127129. ** level, they are merged into a single level (iLevel+1) segment and the
  127130. ** allocated index is 0.
  127131. **
  127132. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  127133. ** returned. Otherwise, an SQLite error code is returned.
  127134. */
  127135. static int fts3AllocateSegdirIdx(
  127136. Fts3Table *p,
  127137. int iLangid, /* Language id */
  127138. int iIndex, /* Index for p->aIndex */
  127139. int iLevel,
  127140. int *piIdx
  127141. ){
  127142. int rc; /* Return Code */
  127143. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  127144. int iNext = 0; /* Result of query pNextIdx */
  127145. assert( iLangid>=0 );
  127146. assert( p->nIndex>=1 );
  127147. /* Set variable iNext to the next available segdir index at level iLevel. */
  127148. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  127149. if( rc==SQLITE_OK ){
  127150. sqlite3_bind_int64(
  127151. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  127152. );
  127153. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  127154. iNext = sqlite3_column_int(pNextIdx, 0);
  127155. }
  127156. rc = sqlite3_reset(pNextIdx);
  127157. }
  127158. if( rc==SQLITE_OK ){
  127159. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  127160. ** full, merge all segments in level iLevel into a single iLevel+1
  127161. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  127162. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  127163. */
  127164. if( iNext>=FTS3_MERGE_COUNT ){
  127165. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  127166. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  127167. *piIdx = 0;
  127168. }else{
  127169. *piIdx = iNext;
  127170. }
  127171. }
  127172. return rc;
  127173. }
  127174. /*
  127175. ** The %_segments table is declared as follows:
  127176. **
  127177. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  127178. **
  127179. ** This function reads data from a single row of the %_segments table. The
  127180. ** specific row is identified by the iBlockid parameter. If paBlob is not
  127181. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  127182. ** with the contents of the blob stored in the "block" column of the
  127183. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  127184. ** to the size of the blob in bytes before returning.
  127185. **
  127186. ** If an error occurs, or the table does not contain the specified row,
  127187. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  127188. ** paBlob is non-NULL, then it is the responsibility of the caller to
  127189. ** eventually free the returned buffer.
  127190. **
  127191. ** This function may leave an open sqlite3_blob* handle in the
  127192. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  127193. ** to this function. The handle may be closed by calling the
  127194. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  127195. ** performance improvement, but the blob handle should always be closed
  127196. ** before control is returned to the user (to prevent a lock being held
  127197. ** on the database file for longer than necessary). Thus, any virtual table
  127198. ** method (xFilter etc.) that may directly or indirectly call this function
  127199. ** must call sqlite3Fts3SegmentsClose() before returning.
  127200. */
  127201. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  127202. Fts3Table *p, /* FTS3 table handle */
  127203. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  127204. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  127205. int *pnBlob, /* OUT: Size of blob data */
  127206. int *pnLoad /* OUT: Bytes actually loaded */
  127207. ){
  127208. int rc; /* Return code */
  127209. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  127210. assert( pnBlob );
  127211. if( p->pSegments ){
  127212. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  127213. }else{
  127214. if( 0==p->zSegmentsTbl ){
  127215. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  127216. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  127217. }
  127218. rc = sqlite3_blob_open(
  127219. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  127220. );
  127221. }
  127222. if( rc==SQLITE_OK ){
  127223. int nByte = sqlite3_blob_bytes(p->pSegments);
  127224. *pnBlob = nByte;
  127225. if( paBlob ){
  127226. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  127227. if( !aByte ){
  127228. rc = SQLITE_NOMEM;
  127229. }else{
  127230. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  127231. nByte = FTS3_NODE_CHUNKSIZE;
  127232. *pnLoad = nByte;
  127233. }
  127234. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  127235. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  127236. if( rc!=SQLITE_OK ){
  127237. sqlite3_free(aByte);
  127238. aByte = 0;
  127239. }
  127240. }
  127241. *paBlob = aByte;
  127242. }
  127243. }
  127244. return rc;
  127245. }
  127246. /*
  127247. ** Close the blob handle at p->pSegments, if it is open. See comments above
  127248. ** the sqlite3Fts3ReadBlock() function for details.
  127249. */
  127250. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  127251. sqlite3_blob_close(p->pSegments);
  127252. p->pSegments = 0;
  127253. }
  127254. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  127255. int nRead; /* Number of bytes to read */
  127256. int rc; /* Return code */
  127257. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  127258. rc = sqlite3_blob_read(
  127259. pReader->pBlob,
  127260. &pReader->aNode[pReader->nPopulate],
  127261. nRead,
  127262. pReader->nPopulate
  127263. );
  127264. if( rc==SQLITE_OK ){
  127265. pReader->nPopulate += nRead;
  127266. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  127267. if( pReader->nPopulate==pReader->nNode ){
  127268. sqlite3_blob_close(pReader->pBlob);
  127269. pReader->pBlob = 0;
  127270. pReader->nPopulate = 0;
  127271. }
  127272. }
  127273. return rc;
  127274. }
  127275. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  127276. int rc = SQLITE_OK;
  127277. assert( !pReader->pBlob
  127278. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  127279. );
  127280. while( pReader->pBlob && rc==SQLITE_OK
  127281. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  127282. ){
  127283. rc = fts3SegReaderIncrRead(pReader);
  127284. }
  127285. return rc;
  127286. }
  127287. /*
  127288. ** Set an Fts3SegReader cursor to point at EOF.
  127289. */
  127290. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  127291. if( !fts3SegReaderIsRootOnly(pSeg) ){
  127292. sqlite3_free(pSeg->aNode);
  127293. sqlite3_blob_close(pSeg->pBlob);
  127294. pSeg->pBlob = 0;
  127295. }
  127296. pSeg->aNode = 0;
  127297. }
  127298. /*
  127299. ** Move the iterator passed as the first argument to the next term in the
  127300. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  127301. ** SQLITE_DONE. Otherwise, an SQLite error code.
  127302. */
  127303. static int fts3SegReaderNext(
  127304. Fts3Table *p,
  127305. Fts3SegReader *pReader,
  127306. int bIncr
  127307. ){
  127308. int rc; /* Return code of various sub-routines */
  127309. char *pNext; /* Cursor variable */
  127310. int nPrefix; /* Number of bytes in term prefix */
  127311. int nSuffix; /* Number of bytes in term suffix */
  127312. if( !pReader->aDoclist ){
  127313. pNext = pReader->aNode;
  127314. }else{
  127315. pNext = &pReader->aDoclist[pReader->nDoclist];
  127316. }
  127317. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  127318. if( fts3SegReaderIsPending(pReader) ){
  127319. Fts3HashElem *pElem = *(pReader->ppNextElem);
  127320. if( pElem==0 ){
  127321. pReader->aNode = 0;
  127322. }else{
  127323. PendingList *pList = (PendingList *)fts3HashData(pElem);
  127324. pReader->zTerm = (char *)fts3HashKey(pElem);
  127325. pReader->nTerm = fts3HashKeysize(pElem);
  127326. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  127327. pReader->aNode = pReader->aDoclist = pList->aData;
  127328. pReader->ppNextElem++;
  127329. assert( pReader->aNode );
  127330. }
  127331. return SQLITE_OK;
  127332. }
  127333. fts3SegReaderSetEof(pReader);
  127334. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  127335. ** blocks have already been traversed. */
  127336. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  127337. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  127338. return SQLITE_OK;
  127339. }
  127340. rc = sqlite3Fts3ReadBlock(
  127341. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  127342. (bIncr ? &pReader->nPopulate : 0)
  127343. );
  127344. if( rc!=SQLITE_OK ) return rc;
  127345. assert( pReader->pBlob==0 );
  127346. if( bIncr && pReader->nPopulate<pReader->nNode ){
  127347. pReader->pBlob = p->pSegments;
  127348. p->pSegments = 0;
  127349. }
  127350. pNext = pReader->aNode;
  127351. }
  127352. assert( !fts3SegReaderIsPending(pReader) );
  127353. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  127354. if( rc!=SQLITE_OK ) return rc;
  127355. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  127356. ** safe (no risk of overread) even if the node data is corrupted. */
  127357. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  127358. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  127359. if( nPrefix<0 || nSuffix<=0
  127360. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  127361. ){
  127362. return FTS_CORRUPT_VTAB;
  127363. }
  127364. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  127365. int nNew = (nPrefix+nSuffix)*2;
  127366. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  127367. if( !zNew ){
  127368. return SQLITE_NOMEM;
  127369. }
  127370. pReader->zTerm = zNew;
  127371. pReader->nTermAlloc = nNew;
  127372. }
  127373. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  127374. if( rc!=SQLITE_OK ) return rc;
  127375. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  127376. pReader->nTerm = nPrefix+nSuffix;
  127377. pNext += nSuffix;
  127378. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  127379. pReader->aDoclist = pNext;
  127380. pReader->pOffsetList = 0;
  127381. /* Check that the doclist does not appear to extend past the end of the
  127382. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  127383. ** of these statements is untrue, then the data structure is corrupt.
  127384. */
  127385. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  127386. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  127387. ){
  127388. return FTS_CORRUPT_VTAB;
  127389. }
  127390. return SQLITE_OK;
  127391. }
  127392. /*
  127393. ** Set the SegReader to point to the first docid in the doclist associated
  127394. ** with the current term.
  127395. */
  127396. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  127397. int rc = SQLITE_OK;
  127398. assert( pReader->aDoclist );
  127399. assert( !pReader->pOffsetList );
  127400. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  127401. u8 bEof = 0;
  127402. pReader->iDocid = 0;
  127403. pReader->nOffsetList = 0;
  127404. sqlite3Fts3DoclistPrev(0,
  127405. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  127406. &pReader->iDocid, &pReader->nOffsetList, &bEof
  127407. );
  127408. }else{
  127409. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  127410. if( rc==SQLITE_OK ){
  127411. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  127412. pReader->pOffsetList = &pReader->aDoclist[n];
  127413. }
  127414. }
  127415. return rc;
  127416. }
  127417. /*
  127418. ** Advance the SegReader to point to the next docid in the doclist
  127419. ** associated with the current term.
  127420. **
  127421. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  127422. ** *ppOffsetList is set to point to the first column-offset list
  127423. ** in the doclist entry (i.e. immediately past the docid varint).
  127424. ** *pnOffsetList is set to the length of the set of column-offset
  127425. ** lists, not including the nul-terminator byte. For example:
  127426. */
  127427. static int fts3SegReaderNextDocid(
  127428. Fts3Table *pTab,
  127429. Fts3SegReader *pReader, /* Reader to advance to next docid */
  127430. char **ppOffsetList, /* OUT: Pointer to current position-list */
  127431. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  127432. ){
  127433. int rc = SQLITE_OK;
  127434. char *p = pReader->pOffsetList;
  127435. char c = 0;
  127436. assert( p );
  127437. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  127438. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  127439. ** Pending-terms doclists are always built up in ascending order, so
  127440. ** we have to iterate through them backwards here. */
  127441. u8 bEof = 0;
  127442. if( ppOffsetList ){
  127443. *ppOffsetList = pReader->pOffsetList;
  127444. *pnOffsetList = pReader->nOffsetList - 1;
  127445. }
  127446. sqlite3Fts3DoclistPrev(0,
  127447. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  127448. &pReader->nOffsetList, &bEof
  127449. );
  127450. if( bEof ){
  127451. pReader->pOffsetList = 0;
  127452. }else{
  127453. pReader->pOffsetList = p;
  127454. }
  127455. }else{
  127456. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  127457. /* Pointer p currently points at the first byte of an offset list. The
  127458. ** following block advances it to point one byte past the end of
  127459. ** the same offset list. */
  127460. while( 1 ){
  127461. /* The following line of code (and the "p++" below the while() loop) is
  127462. ** normally all that is required to move pointer p to the desired
  127463. ** position. The exception is if this node is being loaded from disk
  127464. ** incrementally and pointer "p" now points to the first byte past
  127465. ** the populated part of pReader->aNode[].
  127466. */
  127467. while( *p | c ) c = *p++ & 0x80;
  127468. assert( *p==0 );
  127469. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  127470. rc = fts3SegReaderIncrRead(pReader);
  127471. if( rc!=SQLITE_OK ) return rc;
  127472. }
  127473. p++;
  127474. /* If required, populate the output variables with a pointer to and the
  127475. ** size of the previous offset-list.
  127476. */
  127477. if( ppOffsetList ){
  127478. *ppOffsetList = pReader->pOffsetList;
  127479. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  127480. }
  127481. /* List may have been edited in place by fts3EvalNearTrim() */
  127482. while( p<pEnd && *p==0 ) p++;
  127483. /* If there are no more entries in the doclist, set pOffsetList to
  127484. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  127485. ** Fts3SegReader.pOffsetList to point to the next offset list before
  127486. ** returning.
  127487. */
  127488. if( p>=pEnd ){
  127489. pReader->pOffsetList = 0;
  127490. }else{
  127491. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  127492. if( rc==SQLITE_OK ){
  127493. sqlite3_int64 iDelta;
  127494. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  127495. if( pTab->bDescIdx ){
  127496. pReader->iDocid -= iDelta;
  127497. }else{
  127498. pReader->iDocid += iDelta;
  127499. }
  127500. }
  127501. }
  127502. }
  127503. return SQLITE_OK;
  127504. }
  127505. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  127506. Fts3Cursor *pCsr,
  127507. Fts3MultiSegReader *pMsr,
  127508. int *pnOvfl
  127509. ){
  127510. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  127511. int nOvfl = 0;
  127512. int ii;
  127513. int rc = SQLITE_OK;
  127514. int pgsz = p->nPgsz;
  127515. assert( p->bFts4 );
  127516. assert( pgsz>0 );
  127517. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  127518. Fts3SegReader *pReader = pMsr->apSegment[ii];
  127519. if( !fts3SegReaderIsPending(pReader)
  127520. && !fts3SegReaderIsRootOnly(pReader)
  127521. ){
  127522. sqlite3_int64 jj;
  127523. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  127524. int nBlob;
  127525. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  127526. if( rc!=SQLITE_OK ) break;
  127527. if( (nBlob+35)>pgsz ){
  127528. nOvfl += (nBlob + 34)/pgsz;
  127529. }
  127530. }
  127531. }
  127532. }
  127533. *pnOvfl = nOvfl;
  127534. return rc;
  127535. }
  127536. /*
  127537. ** Free all allocations associated with the iterator passed as the
  127538. ** second argument.
  127539. */
  127540. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  127541. if( pReader && !fts3SegReaderIsPending(pReader) ){
  127542. sqlite3_free(pReader->zTerm);
  127543. if( !fts3SegReaderIsRootOnly(pReader) ){
  127544. sqlite3_free(pReader->aNode);
  127545. sqlite3_blob_close(pReader->pBlob);
  127546. }
  127547. }
  127548. sqlite3_free(pReader);
  127549. }
  127550. /*
  127551. ** Allocate a new SegReader object.
  127552. */
  127553. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  127554. int iAge, /* Segment "age". */
  127555. int bLookup, /* True for a lookup only */
  127556. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  127557. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  127558. sqlite3_int64 iEndBlock, /* Final block of segment */
  127559. const char *zRoot, /* Buffer containing root node */
  127560. int nRoot, /* Size of buffer containing root node */
  127561. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  127562. ){
  127563. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  127564. int nExtra = 0; /* Bytes to allocate segment root node */
  127565. assert( iStartLeaf<=iEndLeaf );
  127566. if( iStartLeaf==0 ){
  127567. nExtra = nRoot + FTS3_NODE_PADDING;
  127568. }
  127569. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  127570. if( !pReader ){
  127571. return SQLITE_NOMEM;
  127572. }
  127573. memset(pReader, 0, sizeof(Fts3SegReader));
  127574. pReader->iIdx = iAge;
  127575. pReader->bLookup = bLookup!=0;
  127576. pReader->iStartBlock = iStartLeaf;
  127577. pReader->iLeafEndBlock = iEndLeaf;
  127578. pReader->iEndBlock = iEndBlock;
  127579. if( nExtra ){
  127580. /* The entire segment is stored in the root node. */
  127581. pReader->aNode = (char *)&pReader[1];
  127582. pReader->rootOnly = 1;
  127583. pReader->nNode = nRoot;
  127584. memcpy(pReader->aNode, zRoot, nRoot);
  127585. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  127586. }else{
  127587. pReader->iCurrentBlock = iStartLeaf-1;
  127588. }
  127589. *ppReader = pReader;
  127590. return SQLITE_OK;
  127591. }
  127592. /*
  127593. ** This is a comparison function used as a qsort() callback when sorting
  127594. ** an array of pending terms by term. This occurs as part of flushing
  127595. ** the contents of the pending-terms hash table to the database.
  127596. */
  127597. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  127598. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  127599. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  127600. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  127601. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  127602. int n = (n1<n2 ? n1 : n2);
  127603. int c = memcmp(z1, z2, n);
  127604. if( c==0 ){
  127605. c = n1 - n2;
  127606. }
  127607. return c;
  127608. }
  127609. /*
  127610. ** This function is used to allocate an Fts3SegReader that iterates through
  127611. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  127612. **
  127613. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  127614. ** through each term in the pending-terms table. Or, if isPrefixIter is
  127615. ** non-zero, it iterates through each term and its prefixes. For example, if
  127616. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  127617. ** "firebird", then the iterator visits the following 'terms' (in the order
  127618. ** shown):
  127619. **
  127620. ** f fi fir fire fireb firebi firebir firebird
  127621. ** m my mys mysq mysql
  127622. ** s sq sql sqli sqlit sqlite
  127623. **
  127624. ** Whereas if isPrefixIter is zero, the terms visited are:
  127625. **
  127626. ** firebird mysql sqlite
  127627. */
  127628. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  127629. Fts3Table *p, /* Virtual table handle */
  127630. int iIndex, /* Index for p->aIndex */
  127631. const char *zTerm, /* Term to search for */
  127632. int nTerm, /* Size of buffer zTerm */
  127633. int bPrefix, /* True for a prefix iterator */
  127634. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  127635. ){
  127636. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  127637. Fts3HashElem *pE; /* Iterator variable */
  127638. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  127639. int nElem = 0; /* Size of array at aElem */
  127640. int rc = SQLITE_OK; /* Return Code */
  127641. Fts3Hash *pHash;
  127642. pHash = &p->aIndex[iIndex].hPending;
  127643. if( bPrefix ){
  127644. int nAlloc = 0; /* Size of allocated array at aElem */
  127645. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  127646. char *zKey = (char *)fts3HashKey(pE);
  127647. int nKey = fts3HashKeysize(pE);
  127648. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  127649. if( nElem==nAlloc ){
  127650. Fts3HashElem **aElem2;
  127651. nAlloc += 16;
  127652. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  127653. aElem, nAlloc*sizeof(Fts3HashElem *)
  127654. );
  127655. if( !aElem2 ){
  127656. rc = SQLITE_NOMEM;
  127657. nElem = 0;
  127658. break;
  127659. }
  127660. aElem = aElem2;
  127661. }
  127662. aElem[nElem++] = pE;
  127663. }
  127664. }
  127665. /* If more than one term matches the prefix, sort the Fts3HashElem
  127666. ** objects in term order using qsort(). This uses the same comparison
  127667. ** callback as is used when flushing terms to disk.
  127668. */
  127669. if( nElem>1 ){
  127670. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  127671. }
  127672. }else{
  127673. /* The query is a simple term lookup that matches at most one term in
  127674. ** the index. All that is required is a straight hash-lookup.
  127675. **
  127676. ** Because the stack address of pE may be accessed via the aElem pointer
  127677. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  127678. ** within this entire function, not just this "else{...}" block.
  127679. */
  127680. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  127681. if( pE ){
  127682. aElem = &pE;
  127683. nElem = 1;
  127684. }
  127685. }
  127686. if( nElem>0 ){
  127687. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  127688. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  127689. if( !pReader ){
  127690. rc = SQLITE_NOMEM;
  127691. }else{
  127692. memset(pReader, 0, nByte);
  127693. pReader->iIdx = 0x7FFFFFFF;
  127694. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  127695. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  127696. }
  127697. }
  127698. if( bPrefix ){
  127699. sqlite3_free(aElem);
  127700. }
  127701. *ppReader = pReader;
  127702. return rc;
  127703. }
  127704. /*
  127705. ** Compare the entries pointed to by two Fts3SegReader structures.
  127706. ** Comparison is as follows:
  127707. **
  127708. ** 1) EOF is greater than not EOF.
  127709. **
  127710. ** 2) The current terms (if any) are compared using memcmp(). If one
  127711. ** term is a prefix of another, the longer term is considered the
  127712. ** larger.
  127713. **
  127714. ** 3) By segment age. An older segment is considered larger.
  127715. */
  127716. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127717. int rc;
  127718. if( pLhs->aNode && pRhs->aNode ){
  127719. int rc2 = pLhs->nTerm - pRhs->nTerm;
  127720. if( rc2<0 ){
  127721. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  127722. }else{
  127723. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  127724. }
  127725. if( rc==0 ){
  127726. rc = rc2;
  127727. }
  127728. }else{
  127729. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  127730. }
  127731. if( rc==0 ){
  127732. rc = pRhs->iIdx - pLhs->iIdx;
  127733. }
  127734. assert( rc!=0 );
  127735. return rc;
  127736. }
  127737. /*
  127738. ** A different comparison function for SegReader structures. In this
  127739. ** version, it is assumed that each SegReader points to an entry in
  127740. ** a doclist for identical terms. Comparison is made as follows:
  127741. **
  127742. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  127743. **
  127744. ** 2) By current docid.
  127745. **
  127746. ** 3) By segment age. An older segment is considered larger.
  127747. */
  127748. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127749. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  127750. if( rc==0 ){
  127751. if( pLhs->iDocid==pRhs->iDocid ){
  127752. rc = pRhs->iIdx - pLhs->iIdx;
  127753. }else{
  127754. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  127755. }
  127756. }
  127757. assert( pLhs->aNode && pRhs->aNode );
  127758. return rc;
  127759. }
  127760. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127761. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  127762. if( rc==0 ){
  127763. if( pLhs->iDocid==pRhs->iDocid ){
  127764. rc = pRhs->iIdx - pLhs->iIdx;
  127765. }else{
  127766. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  127767. }
  127768. }
  127769. assert( pLhs->aNode && pRhs->aNode );
  127770. return rc;
  127771. }
  127772. /*
  127773. ** Compare the term that the Fts3SegReader object passed as the first argument
  127774. ** points to with the term specified by arguments zTerm and nTerm.
  127775. **
  127776. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  127777. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  127778. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  127779. */
  127780. static int fts3SegReaderTermCmp(
  127781. Fts3SegReader *pSeg, /* Segment reader object */
  127782. const char *zTerm, /* Term to compare to */
  127783. int nTerm /* Size of term zTerm in bytes */
  127784. ){
  127785. int res = 0;
  127786. if( pSeg->aNode ){
  127787. if( pSeg->nTerm>nTerm ){
  127788. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  127789. }else{
  127790. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  127791. }
  127792. if( res==0 ){
  127793. res = pSeg->nTerm-nTerm;
  127794. }
  127795. }
  127796. return res;
  127797. }
  127798. /*
  127799. ** Argument apSegment is an array of nSegment elements. It is known that
  127800. ** the final (nSegment-nSuspect) members are already in sorted order
  127801. ** (according to the comparison function provided). This function shuffles
  127802. ** the array around until all entries are in sorted order.
  127803. */
  127804. static void fts3SegReaderSort(
  127805. Fts3SegReader **apSegment, /* Array to sort entries of */
  127806. int nSegment, /* Size of apSegment array */
  127807. int nSuspect, /* Unsorted entry count */
  127808. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  127809. ){
  127810. int i; /* Iterator variable */
  127811. assert( nSuspect<=nSegment );
  127812. if( nSuspect==nSegment ) nSuspect--;
  127813. for(i=nSuspect-1; i>=0; i--){
  127814. int j;
  127815. for(j=i; j<(nSegment-1); j++){
  127816. Fts3SegReader *pTmp;
  127817. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  127818. pTmp = apSegment[j+1];
  127819. apSegment[j+1] = apSegment[j];
  127820. apSegment[j] = pTmp;
  127821. }
  127822. }
  127823. #ifndef NDEBUG
  127824. /* Check that the list really is sorted now. */
  127825. for(i=0; i<(nSuspect-1); i++){
  127826. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  127827. }
  127828. #endif
  127829. }
  127830. /*
  127831. ** Insert a record into the %_segments table.
  127832. */
  127833. static int fts3WriteSegment(
  127834. Fts3Table *p, /* Virtual table handle */
  127835. sqlite3_int64 iBlock, /* Block id for new block */
  127836. char *z, /* Pointer to buffer containing block data */
  127837. int n /* Size of buffer z in bytes */
  127838. ){
  127839. sqlite3_stmt *pStmt;
  127840. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  127841. if( rc==SQLITE_OK ){
  127842. sqlite3_bind_int64(pStmt, 1, iBlock);
  127843. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  127844. sqlite3_step(pStmt);
  127845. rc = sqlite3_reset(pStmt);
  127846. }
  127847. return rc;
  127848. }
  127849. /*
  127850. ** Find the largest relative level number in the table. If successful, set
  127851. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  127852. ** set *pnMax to zero and return an SQLite error code.
  127853. */
  127854. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  127855. int rc;
  127856. int mxLevel = 0;
  127857. sqlite3_stmt *pStmt = 0;
  127858. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  127859. if( rc==SQLITE_OK ){
  127860. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  127861. mxLevel = sqlite3_column_int(pStmt, 0);
  127862. }
  127863. rc = sqlite3_reset(pStmt);
  127864. }
  127865. *pnMax = mxLevel;
  127866. return rc;
  127867. }
  127868. /*
  127869. ** Insert a record into the %_segdir table.
  127870. */
  127871. static int fts3WriteSegdir(
  127872. Fts3Table *p, /* Virtual table handle */
  127873. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  127874. int iIdx, /* Value for "idx" field */
  127875. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  127876. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  127877. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  127878. char *zRoot, /* Blob value for "root" field */
  127879. int nRoot /* Number of bytes in buffer zRoot */
  127880. ){
  127881. sqlite3_stmt *pStmt;
  127882. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  127883. if( rc==SQLITE_OK ){
  127884. sqlite3_bind_int64(pStmt, 1, iLevel);
  127885. sqlite3_bind_int(pStmt, 2, iIdx);
  127886. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  127887. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  127888. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  127889. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  127890. sqlite3_step(pStmt);
  127891. rc = sqlite3_reset(pStmt);
  127892. }
  127893. return rc;
  127894. }
  127895. /*
  127896. ** Return the size of the common prefix (if any) shared by zPrev and
  127897. ** zNext, in bytes. For example,
  127898. **
  127899. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  127900. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  127901. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  127902. */
  127903. static int fts3PrefixCompress(
  127904. const char *zPrev, /* Buffer containing previous term */
  127905. int nPrev, /* Size of buffer zPrev in bytes */
  127906. const char *zNext, /* Buffer containing next term */
  127907. int nNext /* Size of buffer zNext in bytes */
  127908. ){
  127909. int n;
  127910. UNUSED_PARAMETER(nNext);
  127911. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  127912. return n;
  127913. }
  127914. /*
  127915. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  127916. ** (according to memcmp) than the previous term.
  127917. */
  127918. static int fts3NodeAddTerm(
  127919. Fts3Table *p, /* Virtual table handle */
  127920. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  127921. int isCopyTerm, /* True if zTerm/nTerm is transient */
  127922. const char *zTerm, /* Pointer to buffer containing term */
  127923. int nTerm /* Size of term in bytes */
  127924. ){
  127925. SegmentNode *pTree = *ppTree;
  127926. int rc;
  127927. SegmentNode *pNew;
  127928. /* First try to append the term to the current node. Return early if
  127929. ** this is possible.
  127930. */
  127931. if( pTree ){
  127932. int nData = pTree->nData; /* Current size of node in bytes */
  127933. int nReq = nData; /* Required space after adding zTerm */
  127934. int nPrefix; /* Number of bytes of prefix compression */
  127935. int nSuffix; /* Suffix length */
  127936. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  127937. nSuffix = nTerm-nPrefix;
  127938. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  127939. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  127940. if( nReq>p->nNodeSize ){
  127941. /* An unusual case: this is the first term to be added to the node
  127942. ** and the static node buffer (p->nNodeSize bytes) is not large
  127943. ** enough. Use a separately malloced buffer instead This wastes
  127944. ** p->nNodeSize bytes, but since this scenario only comes about when
  127945. ** the database contain two terms that share a prefix of almost 2KB,
  127946. ** this is not expected to be a serious problem.
  127947. */
  127948. assert( pTree->aData==(char *)&pTree[1] );
  127949. pTree->aData = (char *)sqlite3_malloc(nReq);
  127950. if( !pTree->aData ){
  127951. return SQLITE_NOMEM;
  127952. }
  127953. }
  127954. if( pTree->zTerm ){
  127955. /* There is no prefix-length field for first term in a node */
  127956. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  127957. }
  127958. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  127959. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  127960. pTree->nData = nData + nSuffix;
  127961. pTree->nEntry++;
  127962. if( isCopyTerm ){
  127963. if( pTree->nMalloc<nTerm ){
  127964. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  127965. if( !zNew ){
  127966. return SQLITE_NOMEM;
  127967. }
  127968. pTree->nMalloc = nTerm*2;
  127969. pTree->zMalloc = zNew;
  127970. }
  127971. pTree->zTerm = pTree->zMalloc;
  127972. memcpy(pTree->zTerm, zTerm, nTerm);
  127973. pTree->nTerm = nTerm;
  127974. }else{
  127975. pTree->zTerm = (char *)zTerm;
  127976. pTree->nTerm = nTerm;
  127977. }
  127978. return SQLITE_OK;
  127979. }
  127980. }
  127981. /* If control flows to here, it was not possible to append zTerm to the
  127982. ** current node. Create a new node (a right-sibling of the current node).
  127983. ** If this is the first node in the tree, the term is added to it.
  127984. **
  127985. ** Otherwise, the term is not added to the new node, it is left empty for
  127986. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  127987. ** has no parent, one is created here.
  127988. */
  127989. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  127990. if( !pNew ){
  127991. return SQLITE_NOMEM;
  127992. }
  127993. memset(pNew, 0, sizeof(SegmentNode));
  127994. pNew->nData = 1 + FTS3_VARINT_MAX;
  127995. pNew->aData = (char *)&pNew[1];
  127996. if( pTree ){
  127997. SegmentNode *pParent = pTree->pParent;
  127998. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  127999. if( pTree->pParent==0 ){
  128000. pTree->pParent = pParent;
  128001. }
  128002. pTree->pRight = pNew;
  128003. pNew->pLeftmost = pTree->pLeftmost;
  128004. pNew->pParent = pParent;
  128005. pNew->zMalloc = pTree->zMalloc;
  128006. pNew->nMalloc = pTree->nMalloc;
  128007. pTree->zMalloc = 0;
  128008. }else{
  128009. pNew->pLeftmost = pNew;
  128010. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  128011. }
  128012. *ppTree = pNew;
  128013. return rc;
  128014. }
  128015. /*
  128016. ** Helper function for fts3NodeWrite().
  128017. */
  128018. static int fts3TreeFinishNode(
  128019. SegmentNode *pTree,
  128020. int iHeight,
  128021. sqlite3_int64 iLeftChild
  128022. ){
  128023. int nStart;
  128024. assert( iHeight>=1 && iHeight<128 );
  128025. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  128026. pTree->aData[nStart] = (char)iHeight;
  128027. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  128028. return nStart;
  128029. }
  128030. /*
  128031. ** Write the buffer for the segment node pTree and all of its peers to the
  128032. ** database. Then call this function recursively to write the parent of
  128033. ** pTree and its peers to the database.
  128034. **
  128035. ** Except, if pTree is a root node, do not write it to the database. Instead,
  128036. ** set output variables *paRoot and *pnRoot to contain the root node.
  128037. **
  128038. ** If successful, SQLITE_OK is returned and output variable *piLast is
  128039. ** set to the largest blockid written to the database (or zero if no
  128040. ** blocks were written to the db). Otherwise, an SQLite error code is
  128041. ** returned.
  128042. */
  128043. static int fts3NodeWrite(
  128044. Fts3Table *p, /* Virtual table handle */
  128045. SegmentNode *pTree, /* SegmentNode handle */
  128046. int iHeight, /* Height of this node in tree */
  128047. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  128048. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  128049. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  128050. char **paRoot, /* OUT: Data for root node */
  128051. int *pnRoot /* OUT: Size of root node in bytes */
  128052. ){
  128053. int rc = SQLITE_OK;
  128054. if( !pTree->pParent ){
  128055. /* Root node of the tree. */
  128056. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  128057. *piLast = iFree-1;
  128058. *pnRoot = pTree->nData - nStart;
  128059. *paRoot = &pTree->aData[nStart];
  128060. }else{
  128061. SegmentNode *pIter;
  128062. sqlite3_int64 iNextFree = iFree;
  128063. sqlite3_int64 iNextLeaf = iLeaf;
  128064. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  128065. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  128066. int nWrite = pIter->nData - nStart;
  128067. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  128068. iNextFree++;
  128069. iNextLeaf += (pIter->nEntry+1);
  128070. }
  128071. if( rc==SQLITE_OK ){
  128072. assert( iNextLeaf==iFree );
  128073. rc = fts3NodeWrite(
  128074. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  128075. );
  128076. }
  128077. }
  128078. return rc;
  128079. }
  128080. /*
  128081. ** Free all memory allocations associated with the tree pTree.
  128082. */
  128083. static void fts3NodeFree(SegmentNode *pTree){
  128084. if( pTree ){
  128085. SegmentNode *p = pTree->pLeftmost;
  128086. fts3NodeFree(p->pParent);
  128087. while( p ){
  128088. SegmentNode *pRight = p->pRight;
  128089. if( p->aData!=(char *)&p[1] ){
  128090. sqlite3_free(p->aData);
  128091. }
  128092. assert( pRight==0 || p->zMalloc==0 );
  128093. sqlite3_free(p->zMalloc);
  128094. sqlite3_free(p);
  128095. p = pRight;
  128096. }
  128097. }
  128098. }
  128099. /*
  128100. ** Add a term to the segment being constructed by the SegmentWriter object
  128101. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  128102. ** be passed NULL. This function will allocate a new SegmentWriter object
  128103. ** and return it via the input/output variable *ppWriter in this case.
  128104. **
  128105. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  128106. */
  128107. static int fts3SegWriterAdd(
  128108. Fts3Table *p, /* Virtual table handle */
  128109. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  128110. int isCopyTerm, /* True if buffer zTerm must be copied */
  128111. const char *zTerm, /* Pointer to buffer containing term */
  128112. int nTerm, /* Size of term in bytes */
  128113. const char *aDoclist, /* Pointer to buffer containing doclist */
  128114. int nDoclist /* Size of doclist in bytes */
  128115. ){
  128116. int nPrefix; /* Size of term prefix in bytes */
  128117. int nSuffix; /* Size of term suffix in bytes */
  128118. int nReq; /* Number of bytes required on leaf page */
  128119. int nData;
  128120. SegmentWriter *pWriter = *ppWriter;
  128121. if( !pWriter ){
  128122. int rc;
  128123. sqlite3_stmt *pStmt;
  128124. /* Allocate the SegmentWriter structure */
  128125. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  128126. if( !pWriter ) return SQLITE_NOMEM;
  128127. memset(pWriter, 0, sizeof(SegmentWriter));
  128128. *ppWriter = pWriter;
  128129. /* Allocate a buffer in which to accumulate data */
  128130. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  128131. if( !pWriter->aData ) return SQLITE_NOMEM;
  128132. pWriter->nSize = p->nNodeSize;
  128133. /* Find the next free blockid in the %_segments table */
  128134. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  128135. if( rc!=SQLITE_OK ) return rc;
  128136. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128137. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  128138. pWriter->iFirst = pWriter->iFree;
  128139. }
  128140. rc = sqlite3_reset(pStmt);
  128141. if( rc!=SQLITE_OK ) return rc;
  128142. }
  128143. nData = pWriter->nData;
  128144. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  128145. nSuffix = nTerm-nPrefix;
  128146. /* Figure out how many bytes are required by this new entry */
  128147. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  128148. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  128149. nSuffix + /* Term suffix */
  128150. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  128151. nDoclist; /* Doclist data */
  128152. if( nData>0 && nData+nReq>p->nNodeSize ){
  128153. int rc;
  128154. /* The current leaf node is full. Write it out to the database. */
  128155. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  128156. if( rc!=SQLITE_OK ) return rc;
  128157. p->nLeafAdd++;
  128158. /* Add the current term to the interior node tree. The term added to
  128159. ** the interior tree must:
  128160. **
  128161. ** a) be greater than the largest term on the leaf node just written
  128162. ** to the database (still available in pWriter->zTerm), and
  128163. **
  128164. ** b) be less than or equal to the term about to be added to the new
  128165. ** leaf node (zTerm/nTerm).
  128166. **
  128167. ** In other words, it must be the prefix of zTerm 1 byte longer than
  128168. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  128169. */
  128170. assert( nPrefix<nTerm );
  128171. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  128172. if( rc!=SQLITE_OK ) return rc;
  128173. nData = 0;
  128174. pWriter->nTerm = 0;
  128175. nPrefix = 0;
  128176. nSuffix = nTerm;
  128177. nReq = 1 + /* varint containing prefix size */
  128178. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  128179. nTerm + /* Term suffix */
  128180. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  128181. nDoclist; /* Doclist data */
  128182. }
  128183. /* If the buffer currently allocated is too small for this entry, realloc
  128184. ** the buffer to make it large enough.
  128185. */
  128186. if( nReq>pWriter->nSize ){
  128187. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  128188. if( !aNew ) return SQLITE_NOMEM;
  128189. pWriter->aData = aNew;
  128190. pWriter->nSize = nReq;
  128191. }
  128192. assert( nData+nReq<=pWriter->nSize );
  128193. /* Append the prefix-compressed term and doclist to the buffer. */
  128194. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  128195. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  128196. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  128197. nData += nSuffix;
  128198. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  128199. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  128200. pWriter->nData = nData + nDoclist;
  128201. /* Save the current term so that it can be used to prefix-compress the next.
  128202. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  128203. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  128204. ** store a copy of the pointer.
  128205. */
  128206. if( isCopyTerm ){
  128207. if( nTerm>pWriter->nMalloc ){
  128208. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  128209. if( !zNew ){
  128210. return SQLITE_NOMEM;
  128211. }
  128212. pWriter->nMalloc = nTerm*2;
  128213. pWriter->zMalloc = zNew;
  128214. pWriter->zTerm = zNew;
  128215. }
  128216. assert( pWriter->zTerm==pWriter->zMalloc );
  128217. memcpy(pWriter->zTerm, zTerm, nTerm);
  128218. }else{
  128219. pWriter->zTerm = (char *)zTerm;
  128220. }
  128221. pWriter->nTerm = nTerm;
  128222. return SQLITE_OK;
  128223. }
  128224. /*
  128225. ** Flush all data associated with the SegmentWriter object pWriter to the
  128226. ** database. This function must be called after all terms have been added
  128227. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  128228. ** returned. Otherwise, an SQLite error code.
  128229. */
  128230. static int fts3SegWriterFlush(
  128231. Fts3Table *p, /* Virtual table handle */
  128232. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  128233. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  128234. int iIdx /* Value for 'idx' column of %_segdir */
  128235. ){
  128236. int rc; /* Return code */
  128237. if( pWriter->pTree ){
  128238. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  128239. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  128240. char *zRoot = NULL; /* Pointer to buffer containing root node */
  128241. int nRoot = 0; /* Size of buffer zRoot */
  128242. iLastLeaf = pWriter->iFree;
  128243. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  128244. if( rc==SQLITE_OK ){
  128245. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  128246. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  128247. }
  128248. if( rc==SQLITE_OK ){
  128249. rc = fts3WriteSegdir(
  128250. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  128251. }
  128252. }else{
  128253. /* The entire tree fits on the root node. Write it to the segdir table. */
  128254. rc = fts3WriteSegdir(
  128255. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  128256. }
  128257. p->nLeafAdd++;
  128258. return rc;
  128259. }
  128260. /*
  128261. ** Release all memory held by the SegmentWriter object passed as the
  128262. ** first argument.
  128263. */
  128264. static void fts3SegWriterFree(SegmentWriter *pWriter){
  128265. if( pWriter ){
  128266. sqlite3_free(pWriter->aData);
  128267. sqlite3_free(pWriter->zMalloc);
  128268. fts3NodeFree(pWriter->pTree);
  128269. sqlite3_free(pWriter);
  128270. }
  128271. }
  128272. /*
  128273. ** The first value in the apVal[] array is assumed to contain an integer.
  128274. ** This function tests if there exist any documents with docid values that
  128275. ** are different from that integer. i.e. if deleting the document with docid
  128276. ** pRowid would mean the FTS3 table were empty.
  128277. **
  128278. ** If successful, *pisEmpty is set to true if the table is empty except for
  128279. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  128280. ** error occurs, an SQLite error code is returned.
  128281. */
  128282. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  128283. sqlite3_stmt *pStmt;
  128284. int rc;
  128285. if( p->zContentTbl ){
  128286. /* If using the content=xxx option, assume the table is never empty */
  128287. *pisEmpty = 0;
  128288. rc = SQLITE_OK;
  128289. }else{
  128290. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  128291. if( rc==SQLITE_OK ){
  128292. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128293. *pisEmpty = sqlite3_column_int(pStmt, 0);
  128294. }
  128295. rc = sqlite3_reset(pStmt);
  128296. }
  128297. }
  128298. return rc;
  128299. }
  128300. /*
  128301. ** Set *pnMax to the largest segment level in the database for the index
  128302. ** iIndex.
  128303. **
  128304. ** Segment levels are stored in the 'level' column of the %_segdir table.
  128305. **
  128306. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  128307. */
  128308. static int fts3SegmentMaxLevel(
  128309. Fts3Table *p,
  128310. int iLangid,
  128311. int iIndex,
  128312. sqlite3_int64 *pnMax
  128313. ){
  128314. sqlite3_stmt *pStmt;
  128315. int rc;
  128316. assert( iIndex>=0 && iIndex<p->nIndex );
  128317. /* Set pStmt to the compiled version of:
  128318. **
  128319. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  128320. **
  128321. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  128322. */
  128323. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  128324. if( rc!=SQLITE_OK ) return rc;
  128325. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  128326. sqlite3_bind_int64(pStmt, 2,
  128327. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  128328. );
  128329. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128330. *pnMax = sqlite3_column_int64(pStmt, 0);
  128331. }
  128332. return sqlite3_reset(pStmt);
  128333. }
  128334. /*
  128335. ** Delete all entries in the %_segments table associated with the segment
  128336. ** opened with seg-reader pSeg. This function does not affect the contents
  128337. ** of the %_segdir table.
  128338. */
  128339. static int fts3DeleteSegment(
  128340. Fts3Table *p, /* FTS table handle */
  128341. Fts3SegReader *pSeg /* Segment to delete */
  128342. ){
  128343. int rc = SQLITE_OK; /* Return code */
  128344. if( pSeg->iStartBlock ){
  128345. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  128346. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  128347. if( rc==SQLITE_OK ){
  128348. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  128349. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  128350. sqlite3_step(pDelete);
  128351. rc = sqlite3_reset(pDelete);
  128352. }
  128353. }
  128354. return rc;
  128355. }
  128356. /*
  128357. ** This function is used after merging multiple segments into a single large
  128358. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  128359. ** it:
  128360. **
  128361. ** 1) Deletes all %_segments entries for the segments associated with
  128362. ** each of the SegReader objects in the array passed as the third
  128363. ** argument, and
  128364. **
  128365. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  128366. ** entries regardless of level if (iLevel<0).
  128367. **
  128368. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  128369. */
  128370. static int fts3DeleteSegdir(
  128371. Fts3Table *p, /* Virtual table handle */
  128372. int iLangid, /* Language id */
  128373. int iIndex, /* Index for p->aIndex */
  128374. int iLevel, /* Level of %_segdir entries to delete */
  128375. Fts3SegReader **apSegment, /* Array of SegReader objects */
  128376. int nReader /* Size of array apSegment */
  128377. ){
  128378. int rc = SQLITE_OK; /* Return Code */
  128379. int i; /* Iterator variable */
  128380. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  128381. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  128382. rc = fts3DeleteSegment(p, apSegment[i]);
  128383. }
  128384. if( rc!=SQLITE_OK ){
  128385. return rc;
  128386. }
  128387. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  128388. if( iLevel==FTS3_SEGCURSOR_ALL ){
  128389. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  128390. if( rc==SQLITE_OK ){
  128391. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  128392. sqlite3_bind_int64(pDelete, 2,
  128393. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  128394. );
  128395. }
  128396. }else{
  128397. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  128398. if( rc==SQLITE_OK ){
  128399. sqlite3_bind_int64(
  128400. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  128401. );
  128402. }
  128403. }
  128404. if( rc==SQLITE_OK ){
  128405. sqlite3_step(pDelete);
  128406. rc = sqlite3_reset(pDelete);
  128407. }
  128408. return rc;
  128409. }
  128410. /*
  128411. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  128412. ** a position list that may (or may not) feature multiple columns. This
  128413. ** function adjusts the pointer *ppList and the length *pnList so that they
  128414. ** identify the subset of the position list that corresponds to column iCol.
  128415. **
  128416. ** If there are no entries in the input position list for column iCol, then
  128417. ** *pnList is set to zero before returning.
  128418. **
  128419. ** If parameter bZero is non-zero, then any part of the input list following
  128420. ** the end of the output list is zeroed before returning.
  128421. */
  128422. static void fts3ColumnFilter(
  128423. int iCol, /* Column to filter on */
  128424. int bZero, /* Zero out anything following *ppList */
  128425. char **ppList, /* IN/OUT: Pointer to position list */
  128426. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  128427. ){
  128428. char *pList = *ppList;
  128429. int nList = *pnList;
  128430. char *pEnd = &pList[nList];
  128431. int iCurrent = 0;
  128432. char *p = pList;
  128433. assert( iCol>=0 );
  128434. while( 1 ){
  128435. char c = 0;
  128436. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  128437. if( iCol==iCurrent ){
  128438. nList = (int)(p - pList);
  128439. break;
  128440. }
  128441. nList -= (int)(p - pList);
  128442. pList = p;
  128443. if( nList==0 ){
  128444. break;
  128445. }
  128446. p = &pList[1];
  128447. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  128448. }
  128449. if( bZero && &pList[nList]!=pEnd ){
  128450. memset(&pList[nList], 0, pEnd - &pList[nList]);
  128451. }
  128452. *ppList = pList;
  128453. *pnList = nList;
  128454. }
  128455. /*
  128456. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  128457. ** existing data). Grow the buffer if required.
  128458. **
  128459. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  128460. ** trying to resize the buffer, return SQLITE_NOMEM.
  128461. */
  128462. static int fts3MsrBufferData(
  128463. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  128464. char *pList,
  128465. int nList
  128466. ){
  128467. if( nList>pMsr->nBuffer ){
  128468. char *pNew;
  128469. pMsr->nBuffer = nList*2;
  128470. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  128471. if( !pNew ) return SQLITE_NOMEM;
  128472. pMsr->aBuffer = pNew;
  128473. }
  128474. memcpy(pMsr->aBuffer, pList, nList);
  128475. return SQLITE_OK;
  128476. }
  128477. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  128478. Fts3Table *p, /* Virtual table handle */
  128479. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  128480. sqlite3_int64 *piDocid, /* OUT: Docid value */
  128481. char **paPoslist, /* OUT: Pointer to position list */
  128482. int *pnPoslist /* OUT: Size of position list in bytes */
  128483. ){
  128484. int nMerge = pMsr->nAdvance;
  128485. Fts3SegReader **apSegment = pMsr->apSegment;
  128486. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128487. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128488. );
  128489. if( nMerge==0 ){
  128490. *paPoslist = 0;
  128491. return SQLITE_OK;
  128492. }
  128493. while( 1 ){
  128494. Fts3SegReader *pSeg;
  128495. pSeg = pMsr->apSegment[0];
  128496. if( pSeg->pOffsetList==0 ){
  128497. *paPoslist = 0;
  128498. break;
  128499. }else{
  128500. int rc;
  128501. char *pList;
  128502. int nList;
  128503. int j;
  128504. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  128505. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  128506. j = 1;
  128507. while( rc==SQLITE_OK
  128508. && j<nMerge
  128509. && apSegment[j]->pOffsetList
  128510. && apSegment[j]->iDocid==iDocid
  128511. ){
  128512. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  128513. j++;
  128514. }
  128515. if( rc!=SQLITE_OK ) return rc;
  128516. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  128517. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  128518. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  128519. if( rc!=SQLITE_OK ) return rc;
  128520. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  128521. pList = pMsr->aBuffer;
  128522. }
  128523. if( pMsr->iColFilter>=0 ){
  128524. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  128525. }
  128526. if( nList>0 ){
  128527. *paPoslist = pList;
  128528. *piDocid = iDocid;
  128529. *pnPoslist = nList;
  128530. break;
  128531. }
  128532. }
  128533. }
  128534. return SQLITE_OK;
  128535. }
  128536. static int fts3SegReaderStart(
  128537. Fts3Table *p, /* Virtual table handle */
  128538. Fts3MultiSegReader *pCsr, /* Cursor object */
  128539. const char *zTerm, /* Term searched for (or NULL) */
  128540. int nTerm /* Length of zTerm in bytes */
  128541. ){
  128542. int i;
  128543. int nSeg = pCsr->nSegment;
  128544. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  128545. ** for, then advance each segment iterator until it points to a term of
  128546. ** equal or greater value than the specified term. This prevents many
  128547. ** unnecessary merge/sort operations for the case where single segment
  128548. ** b-tree leaf nodes contain more than one term.
  128549. */
  128550. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  128551. int res = 0;
  128552. Fts3SegReader *pSeg = pCsr->apSegment[i];
  128553. do {
  128554. int rc = fts3SegReaderNext(p, pSeg, 0);
  128555. if( rc!=SQLITE_OK ) return rc;
  128556. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  128557. if( pSeg->bLookup && res!=0 ){
  128558. fts3SegReaderSetEof(pSeg);
  128559. }
  128560. }
  128561. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  128562. return SQLITE_OK;
  128563. }
  128564. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  128565. Fts3Table *p, /* Virtual table handle */
  128566. Fts3MultiSegReader *pCsr, /* Cursor object */
  128567. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  128568. ){
  128569. pCsr->pFilter = pFilter;
  128570. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  128571. }
  128572. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  128573. Fts3Table *p, /* Virtual table handle */
  128574. Fts3MultiSegReader *pCsr, /* Cursor object */
  128575. int iCol, /* Column to match on. */
  128576. const char *zTerm, /* Term to iterate through a doclist for */
  128577. int nTerm /* Number of bytes in zTerm */
  128578. ){
  128579. int i;
  128580. int rc;
  128581. int nSegment = pCsr->nSegment;
  128582. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128583. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128584. );
  128585. assert( pCsr->pFilter==0 );
  128586. assert( zTerm && nTerm>0 );
  128587. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  128588. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  128589. if( rc!=SQLITE_OK ) return rc;
  128590. /* Determine how many of the segments actually point to zTerm/nTerm. */
  128591. for(i=0; i<nSegment; i++){
  128592. Fts3SegReader *pSeg = pCsr->apSegment[i];
  128593. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  128594. break;
  128595. }
  128596. }
  128597. pCsr->nAdvance = i;
  128598. /* Advance each of the segments to point to the first docid. */
  128599. for(i=0; i<pCsr->nAdvance; i++){
  128600. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  128601. if( rc!=SQLITE_OK ) return rc;
  128602. }
  128603. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  128604. assert( iCol<0 || iCol<p->nColumn );
  128605. pCsr->iColFilter = iCol;
  128606. return SQLITE_OK;
  128607. }
  128608. /*
  128609. ** This function is called on a MultiSegReader that has been started using
  128610. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  128611. ** have been made. Calling this function puts the MultiSegReader in such
  128612. ** a state that if the next two calls are:
  128613. **
  128614. ** sqlite3Fts3SegReaderStart()
  128615. ** sqlite3Fts3SegReaderStep()
  128616. **
  128617. ** then the entire doclist for the term is available in
  128618. ** MultiSegReader.aDoclist/nDoclist.
  128619. */
  128620. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  128621. int i; /* Used to iterate through segment-readers */
  128622. assert( pCsr->zTerm==0 );
  128623. assert( pCsr->nTerm==0 );
  128624. assert( pCsr->aDoclist==0 );
  128625. assert( pCsr->nDoclist==0 );
  128626. pCsr->nAdvance = 0;
  128627. pCsr->bRestart = 1;
  128628. for(i=0; i<pCsr->nSegment; i++){
  128629. pCsr->apSegment[i]->pOffsetList = 0;
  128630. pCsr->apSegment[i]->nOffsetList = 0;
  128631. pCsr->apSegment[i]->iDocid = 0;
  128632. }
  128633. return SQLITE_OK;
  128634. }
  128635. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  128636. Fts3Table *p, /* Virtual table handle */
  128637. Fts3MultiSegReader *pCsr /* Cursor object */
  128638. ){
  128639. int rc = SQLITE_OK;
  128640. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  128641. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  128642. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  128643. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  128644. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  128645. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  128646. Fts3SegReader **apSegment = pCsr->apSegment;
  128647. int nSegment = pCsr->nSegment;
  128648. Fts3SegFilter *pFilter = pCsr->pFilter;
  128649. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128650. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128651. );
  128652. if( pCsr->nSegment==0 ) return SQLITE_OK;
  128653. do {
  128654. int nMerge;
  128655. int i;
  128656. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  128657. ** forward. Then sort the list in order of current term again.
  128658. */
  128659. for(i=0; i<pCsr->nAdvance; i++){
  128660. Fts3SegReader *pSeg = apSegment[i];
  128661. if( pSeg->bLookup ){
  128662. fts3SegReaderSetEof(pSeg);
  128663. }else{
  128664. rc = fts3SegReaderNext(p, pSeg, 0);
  128665. }
  128666. if( rc!=SQLITE_OK ) return rc;
  128667. }
  128668. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  128669. pCsr->nAdvance = 0;
  128670. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  128671. assert( rc==SQLITE_OK );
  128672. if( apSegment[0]->aNode==0 ) break;
  128673. pCsr->nTerm = apSegment[0]->nTerm;
  128674. pCsr->zTerm = apSegment[0]->zTerm;
  128675. /* If this is a prefix-search, and if the term that apSegment[0] points
  128676. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  128677. ** required callbacks have been made. In this case exit early.
  128678. **
  128679. ** Similarly, if this is a search for an exact match, and the first term
  128680. ** of segment apSegment[0] is not a match, exit early.
  128681. */
  128682. if( pFilter->zTerm && !isScan ){
  128683. if( pCsr->nTerm<pFilter->nTerm
  128684. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  128685. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  128686. ){
  128687. break;
  128688. }
  128689. }
  128690. nMerge = 1;
  128691. while( nMerge<nSegment
  128692. && apSegment[nMerge]->aNode
  128693. && apSegment[nMerge]->nTerm==pCsr->nTerm
  128694. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  128695. ){
  128696. nMerge++;
  128697. }
  128698. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  128699. if( nMerge==1
  128700. && !isIgnoreEmpty
  128701. && !isFirst
  128702. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  128703. ){
  128704. pCsr->nDoclist = apSegment[0]->nDoclist;
  128705. if( fts3SegReaderIsPending(apSegment[0]) ){
  128706. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  128707. pCsr->aDoclist = pCsr->aBuffer;
  128708. }else{
  128709. pCsr->aDoclist = apSegment[0]->aDoclist;
  128710. }
  128711. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  128712. }else{
  128713. int nDoclist = 0; /* Size of doclist */
  128714. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  128715. /* The current term of the first nMerge entries in the array
  128716. ** of Fts3SegReader objects is the same. The doclists must be merged
  128717. ** and a single term returned with the merged doclist.
  128718. */
  128719. for(i=0; i<nMerge; i++){
  128720. fts3SegReaderFirstDocid(p, apSegment[i]);
  128721. }
  128722. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  128723. while( apSegment[0]->pOffsetList ){
  128724. int j; /* Number of segments that share a docid */
  128725. char *pList = 0;
  128726. int nList = 0;
  128727. int nByte;
  128728. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  128729. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  128730. j = 1;
  128731. while( j<nMerge
  128732. && apSegment[j]->pOffsetList
  128733. && apSegment[j]->iDocid==iDocid
  128734. ){
  128735. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  128736. j++;
  128737. }
  128738. if( isColFilter ){
  128739. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  128740. }
  128741. if( !isIgnoreEmpty || nList>0 ){
  128742. /* Calculate the 'docid' delta value to write into the merged
  128743. ** doclist. */
  128744. sqlite3_int64 iDelta;
  128745. if( p->bDescIdx && nDoclist>0 ){
  128746. iDelta = iPrev - iDocid;
  128747. }else{
  128748. iDelta = iDocid - iPrev;
  128749. }
  128750. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  128751. assert( nDoclist>0 || iDelta==iDocid );
  128752. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  128753. if( nDoclist+nByte>pCsr->nBuffer ){
  128754. char *aNew;
  128755. pCsr->nBuffer = (nDoclist+nByte)*2;
  128756. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  128757. if( !aNew ){
  128758. return SQLITE_NOMEM;
  128759. }
  128760. pCsr->aBuffer = aNew;
  128761. }
  128762. if( isFirst ){
  128763. char *a = &pCsr->aBuffer[nDoclist];
  128764. int nWrite;
  128765. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  128766. if( nWrite ){
  128767. iPrev = iDocid;
  128768. nDoclist += nWrite;
  128769. }
  128770. }else{
  128771. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  128772. iPrev = iDocid;
  128773. if( isRequirePos ){
  128774. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  128775. nDoclist += nList;
  128776. pCsr->aBuffer[nDoclist++] = '\0';
  128777. }
  128778. }
  128779. }
  128780. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  128781. }
  128782. if( nDoclist>0 ){
  128783. pCsr->aDoclist = pCsr->aBuffer;
  128784. pCsr->nDoclist = nDoclist;
  128785. rc = SQLITE_ROW;
  128786. }
  128787. }
  128788. pCsr->nAdvance = nMerge;
  128789. }while( rc==SQLITE_OK );
  128790. return rc;
  128791. }
  128792. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  128793. Fts3MultiSegReader *pCsr /* Cursor object */
  128794. ){
  128795. if( pCsr ){
  128796. int i;
  128797. for(i=0; i<pCsr->nSegment; i++){
  128798. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  128799. }
  128800. sqlite3_free(pCsr->apSegment);
  128801. sqlite3_free(pCsr->aBuffer);
  128802. pCsr->nSegment = 0;
  128803. pCsr->apSegment = 0;
  128804. pCsr->aBuffer = 0;
  128805. }
  128806. }
  128807. /*
  128808. ** Merge all level iLevel segments in the database into a single
  128809. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  128810. ** single segment with a level equal to the numerically largest level
  128811. ** currently present in the database.
  128812. **
  128813. ** If this function is called with iLevel<0, but there is only one
  128814. ** segment in the database, SQLITE_DONE is returned immediately.
  128815. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  128816. ** an SQLite error code is returned.
  128817. */
  128818. static int fts3SegmentMerge(
  128819. Fts3Table *p,
  128820. int iLangid, /* Language id to merge */
  128821. int iIndex, /* Index in p->aIndex[] to merge */
  128822. int iLevel /* Level to merge */
  128823. ){
  128824. int rc; /* Return code */
  128825. int iIdx = 0; /* Index of new segment */
  128826. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  128827. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  128828. Fts3SegFilter filter; /* Segment term filter condition */
  128829. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  128830. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  128831. assert( iLevel==FTS3_SEGCURSOR_ALL
  128832. || iLevel==FTS3_SEGCURSOR_PENDING
  128833. || iLevel>=0
  128834. );
  128835. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  128836. assert( iIndex>=0 && iIndex<p->nIndex );
  128837. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  128838. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  128839. if( iLevel==FTS3_SEGCURSOR_ALL ){
  128840. /* This call is to merge all segments in the database to a single
  128841. ** segment. The level of the new segment is equal to the numerically
  128842. ** greatest segment level currently present in the database for this
  128843. ** index. The idx of the new segment is always 0. */
  128844. if( csr.nSegment==1 ){
  128845. rc = SQLITE_DONE;
  128846. goto finished;
  128847. }
  128848. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  128849. bIgnoreEmpty = 1;
  128850. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  128851. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  128852. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  128853. }else{
  128854. /* This call is to merge all segments at level iLevel. find the next
  128855. ** available segment index at level iLevel+1. The call to
  128856. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  128857. ** a single iLevel+2 segment if necessary. */
  128858. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  128859. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  128860. }
  128861. if( rc!=SQLITE_OK ) goto finished;
  128862. assert( csr.nSegment>0 );
  128863. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  128864. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  128865. memset(&filter, 0, sizeof(Fts3SegFilter));
  128866. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  128867. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  128868. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  128869. while( SQLITE_OK==rc ){
  128870. rc = sqlite3Fts3SegReaderStep(p, &csr);
  128871. if( rc!=SQLITE_ROW ) break;
  128872. rc = fts3SegWriterAdd(p, &pWriter, 1,
  128873. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  128874. }
  128875. if( rc!=SQLITE_OK ) goto finished;
  128876. assert( pWriter );
  128877. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  128878. rc = fts3DeleteSegdir(
  128879. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  128880. );
  128881. if( rc!=SQLITE_OK ) goto finished;
  128882. }
  128883. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  128884. finished:
  128885. fts3SegWriterFree(pWriter);
  128886. sqlite3Fts3SegReaderFinish(&csr);
  128887. return rc;
  128888. }
  128889. /*
  128890. ** Flush the contents of pendingTerms to level 0 segments.
  128891. */
  128892. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  128893. int rc = SQLITE_OK;
  128894. int i;
  128895. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  128896. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  128897. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  128898. }
  128899. sqlite3Fts3PendingTermsClear(p);
  128900. /* Determine the auto-incr-merge setting if unknown. If enabled,
  128901. ** estimate the number of leaf blocks of content to be written
  128902. */
  128903. if( rc==SQLITE_OK && p->bHasStat
  128904. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  128905. ){
  128906. sqlite3_stmt *pStmt = 0;
  128907. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  128908. if( rc==SQLITE_OK ){
  128909. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  128910. rc = sqlite3_step(pStmt);
  128911. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  128912. rc = sqlite3_reset(pStmt);
  128913. }
  128914. }
  128915. return rc;
  128916. }
  128917. /*
  128918. ** Encode N integers as varints into a blob.
  128919. */
  128920. static void fts3EncodeIntArray(
  128921. int N, /* The number of integers to encode */
  128922. u32 *a, /* The integer values */
  128923. char *zBuf, /* Write the BLOB here */
  128924. int *pNBuf /* Write number of bytes if zBuf[] used here */
  128925. ){
  128926. int i, j;
  128927. for(i=j=0; i<N; i++){
  128928. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  128929. }
  128930. *pNBuf = j;
  128931. }
  128932. /*
  128933. ** Decode a blob of varints into N integers
  128934. */
  128935. static void fts3DecodeIntArray(
  128936. int N, /* The number of integers to decode */
  128937. u32 *a, /* Write the integer values */
  128938. const char *zBuf, /* The BLOB containing the varints */
  128939. int nBuf /* size of the BLOB */
  128940. ){
  128941. int i, j;
  128942. UNUSED_PARAMETER(nBuf);
  128943. for(i=j=0; i<N; i++){
  128944. sqlite3_int64 x;
  128945. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  128946. assert(j<=nBuf);
  128947. a[i] = (u32)(x & 0xffffffff);
  128948. }
  128949. }
  128950. /*
  128951. ** Insert the sizes (in tokens) for each column of the document
  128952. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  128953. ** a blob of varints.
  128954. */
  128955. static void fts3InsertDocsize(
  128956. int *pRC, /* Result code */
  128957. Fts3Table *p, /* Table into which to insert */
  128958. u32 *aSz /* Sizes of each column, in tokens */
  128959. ){
  128960. char *pBlob; /* The BLOB encoding of the document size */
  128961. int nBlob; /* Number of bytes in the BLOB */
  128962. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  128963. int rc; /* Result code from subfunctions */
  128964. if( *pRC ) return;
  128965. pBlob = sqlite3_malloc( 10*p->nColumn );
  128966. if( pBlob==0 ){
  128967. *pRC = SQLITE_NOMEM;
  128968. return;
  128969. }
  128970. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  128971. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  128972. if( rc ){
  128973. sqlite3_free(pBlob);
  128974. *pRC = rc;
  128975. return;
  128976. }
  128977. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  128978. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  128979. sqlite3_step(pStmt);
  128980. *pRC = sqlite3_reset(pStmt);
  128981. }
  128982. /*
  128983. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  128984. ** where N is the number of user defined columns in the fts3 table plus
  128985. ** two. If nCol is the number of user defined columns, then values of the
  128986. ** varints are set as follows:
  128987. **
  128988. ** Varint 0: Total number of rows in the table.
  128989. **
  128990. ** Varint 1..nCol: For each column, the total number of tokens stored in
  128991. ** the column for all rows of the table.
  128992. **
  128993. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  128994. ** columns of all rows of the table.
  128995. **
  128996. */
  128997. static void fts3UpdateDocTotals(
  128998. int *pRC, /* The result code */
  128999. Fts3Table *p, /* Table being updated */
  129000. u32 *aSzIns, /* Size increases */
  129001. u32 *aSzDel, /* Size decreases */
  129002. int nChng /* Change in the number of documents */
  129003. ){
  129004. char *pBlob; /* Storage for BLOB written into %_stat */
  129005. int nBlob; /* Size of BLOB written into %_stat */
  129006. u32 *a; /* Array of integers that becomes the BLOB */
  129007. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  129008. int i; /* Loop counter */
  129009. int rc; /* Result code from subfunctions */
  129010. const int nStat = p->nColumn+2;
  129011. if( *pRC ) return;
  129012. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  129013. if( a==0 ){
  129014. *pRC = SQLITE_NOMEM;
  129015. return;
  129016. }
  129017. pBlob = (char*)&a[nStat];
  129018. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  129019. if( rc ){
  129020. sqlite3_free(a);
  129021. *pRC = rc;
  129022. return;
  129023. }
  129024. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  129025. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  129026. fts3DecodeIntArray(nStat, a,
  129027. sqlite3_column_blob(pStmt, 0),
  129028. sqlite3_column_bytes(pStmt, 0));
  129029. }else{
  129030. memset(a, 0, sizeof(u32)*(nStat) );
  129031. }
  129032. rc = sqlite3_reset(pStmt);
  129033. if( rc!=SQLITE_OK ){
  129034. sqlite3_free(a);
  129035. *pRC = rc;
  129036. return;
  129037. }
  129038. if( nChng<0 && a[0]<(u32)(-nChng) ){
  129039. a[0] = 0;
  129040. }else{
  129041. a[0] += nChng;
  129042. }
  129043. for(i=0; i<p->nColumn+1; i++){
  129044. u32 x = a[i+1];
  129045. if( x+aSzIns[i] < aSzDel[i] ){
  129046. x = 0;
  129047. }else{
  129048. x = x + aSzIns[i] - aSzDel[i];
  129049. }
  129050. a[i+1] = x;
  129051. }
  129052. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  129053. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  129054. if( rc ){
  129055. sqlite3_free(a);
  129056. *pRC = rc;
  129057. return;
  129058. }
  129059. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  129060. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  129061. sqlite3_step(pStmt);
  129062. *pRC = sqlite3_reset(pStmt);
  129063. sqlite3_free(a);
  129064. }
  129065. /*
  129066. ** Merge the entire database so that there is one segment for each
  129067. ** iIndex/iLangid combination.
  129068. */
  129069. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  129070. int bSeenDone = 0;
  129071. int rc;
  129072. sqlite3_stmt *pAllLangid = 0;
  129073. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  129074. if( rc==SQLITE_OK ){
  129075. int rc2;
  129076. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  129077. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  129078. int i;
  129079. int iLangid = sqlite3_column_int(pAllLangid, 0);
  129080. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  129081. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  129082. if( rc==SQLITE_DONE ){
  129083. bSeenDone = 1;
  129084. rc = SQLITE_OK;
  129085. }
  129086. }
  129087. }
  129088. rc2 = sqlite3_reset(pAllLangid);
  129089. if( rc==SQLITE_OK ) rc = rc2;
  129090. }
  129091. sqlite3Fts3SegmentsClose(p);
  129092. sqlite3Fts3PendingTermsClear(p);
  129093. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  129094. }
  129095. /*
  129096. ** This function is called when the user executes the following statement:
  129097. **
  129098. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  129099. **
  129100. ** The entire FTS index is discarded and rebuilt. If the table is one
  129101. ** created using the content=xxx option, then the new index is based on
  129102. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  129103. ** on the contents of the %_content table.
  129104. */
  129105. static int fts3DoRebuild(Fts3Table *p){
  129106. int rc; /* Return Code */
  129107. rc = fts3DeleteAll(p, 0);
  129108. if( rc==SQLITE_OK ){
  129109. u32 *aSz = 0;
  129110. u32 *aSzIns = 0;
  129111. u32 *aSzDel = 0;
  129112. sqlite3_stmt *pStmt = 0;
  129113. int nEntry = 0;
  129114. /* Compose and prepare an SQL statement to loop through the content table */
  129115. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  129116. if( !zSql ){
  129117. rc = SQLITE_NOMEM;
  129118. }else{
  129119. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  129120. sqlite3_free(zSql);
  129121. }
  129122. if( rc==SQLITE_OK ){
  129123. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  129124. aSz = (u32 *)sqlite3_malloc(nByte);
  129125. if( aSz==0 ){
  129126. rc = SQLITE_NOMEM;
  129127. }else{
  129128. memset(aSz, 0, nByte);
  129129. aSzIns = &aSz[p->nColumn+1];
  129130. aSzDel = &aSzIns[p->nColumn+1];
  129131. }
  129132. }
  129133. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  129134. int iCol;
  129135. int iLangid = langidFromSelect(p, pStmt);
  129136. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  129137. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  129138. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  129139. if( p->abNotindexed[iCol]==0 ){
  129140. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  129141. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  129142. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  129143. }
  129144. }
  129145. if( p->bHasDocsize ){
  129146. fts3InsertDocsize(&rc, p, aSz);
  129147. }
  129148. if( rc!=SQLITE_OK ){
  129149. sqlite3_finalize(pStmt);
  129150. pStmt = 0;
  129151. }else{
  129152. nEntry++;
  129153. for(iCol=0; iCol<=p->nColumn; iCol++){
  129154. aSzIns[iCol] += aSz[iCol];
  129155. }
  129156. }
  129157. }
  129158. if( p->bFts4 ){
  129159. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  129160. }
  129161. sqlite3_free(aSz);
  129162. if( pStmt ){
  129163. int rc2 = sqlite3_finalize(pStmt);
  129164. if( rc==SQLITE_OK ){
  129165. rc = rc2;
  129166. }
  129167. }
  129168. }
  129169. return rc;
  129170. }
  129171. /*
  129172. ** This function opens a cursor used to read the input data for an
  129173. ** incremental merge operation. Specifically, it opens a cursor to scan
  129174. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  129175. ** level iAbsLevel.
  129176. */
  129177. static int fts3IncrmergeCsr(
  129178. Fts3Table *p, /* FTS3 table handle */
  129179. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  129180. int nSeg, /* Number of segments to merge */
  129181. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  129182. ){
  129183. int rc; /* Return Code */
  129184. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  129185. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  129186. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  129187. memset(pCsr, 0, sizeof(*pCsr));
  129188. nByte = sizeof(Fts3SegReader *) * nSeg;
  129189. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  129190. if( pCsr->apSegment==0 ){
  129191. rc = SQLITE_NOMEM;
  129192. }else{
  129193. memset(pCsr->apSegment, 0, nByte);
  129194. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  129195. }
  129196. if( rc==SQLITE_OK ){
  129197. int i;
  129198. int rc2;
  129199. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  129200. assert( pCsr->nSegment==0 );
  129201. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  129202. rc = sqlite3Fts3SegReaderNew(i, 0,
  129203. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  129204. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  129205. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  129206. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  129207. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  129208. &pCsr->apSegment[i]
  129209. );
  129210. pCsr->nSegment++;
  129211. }
  129212. rc2 = sqlite3_reset(pStmt);
  129213. if( rc==SQLITE_OK ) rc = rc2;
  129214. }
  129215. return rc;
  129216. }
  129217. typedef struct IncrmergeWriter IncrmergeWriter;
  129218. typedef struct NodeWriter NodeWriter;
  129219. typedef struct Blob Blob;
  129220. typedef struct NodeReader NodeReader;
  129221. /*
  129222. ** An instance of the following structure is used as a dynamic buffer
  129223. ** to build up nodes or other blobs of data in.
  129224. **
  129225. ** The function blobGrowBuffer() is used to extend the allocation.
  129226. */
  129227. struct Blob {
  129228. char *a; /* Pointer to allocation */
  129229. int n; /* Number of valid bytes of data in a[] */
  129230. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  129231. };
  129232. /*
  129233. ** This structure is used to build up buffers containing segment b-tree
  129234. ** nodes (blocks).
  129235. */
  129236. struct NodeWriter {
  129237. sqlite3_int64 iBlock; /* Current block id */
  129238. Blob key; /* Last key written to the current block */
  129239. Blob block; /* Current block image */
  129240. };
  129241. /*
  129242. ** An object of this type contains the state required to create or append
  129243. ** to an appendable b-tree segment.
  129244. */
  129245. struct IncrmergeWriter {
  129246. int nLeafEst; /* Space allocated for leaf blocks */
  129247. int nWork; /* Number of leaf pages flushed */
  129248. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  129249. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  129250. sqlite3_int64 iStart; /* Block number of first allocated block */
  129251. sqlite3_int64 iEnd; /* Block number of last allocated block */
  129252. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  129253. };
  129254. /*
  129255. ** An object of the following type is used to read data from a single
  129256. ** FTS segment node. See the following functions:
  129257. **
  129258. ** nodeReaderInit()
  129259. ** nodeReaderNext()
  129260. ** nodeReaderRelease()
  129261. */
  129262. struct NodeReader {
  129263. const char *aNode;
  129264. int nNode;
  129265. int iOff; /* Current offset within aNode[] */
  129266. /* Output variables. Containing the current node entry. */
  129267. sqlite3_int64 iChild; /* Pointer to child node */
  129268. Blob term; /* Current term */
  129269. const char *aDoclist; /* Pointer to doclist */
  129270. int nDoclist; /* Size of doclist in bytes */
  129271. };
  129272. /*
  129273. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  129274. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  129275. ** bytes in size, extend (realloc) it to be so.
  129276. **
  129277. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  129278. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  129279. ** to reflect the new size of the pBlob->a[] buffer.
  129280. */
  129281. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  129282. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  129283. int nAlloc = nMin;
  129284. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  129285. if( a ){
  129286. pBlob->nAlloc = nAlloc;
  129287. pBlob->a = a;
  129288. }else{
  129289. *pRc = SQLITE_NOMEM;
  129290. }
  129291. }
  129292. }
  129293. /*
  129294. ** Attempt to advance the node-reader object passed as the first argument to
  129295. ** the next entry on the node.
  129296. **
  129297. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  129298. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  129299. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  129300. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  129301. ** variables for the new entry.
  129302. */
  129303. static int nodeReaderNext(NodeReader *p){
  129304. int bFirst = (p->term.n==0); /* True for first term on the node */
  129305. int nPrefix = 0; /* Bytes to copy from previous term */
  129306. int nSuffix = 0; /* Bytes to append to the prefix */
  129307. int rc = SQLITE_OK; /* Return code */
  129308. assert( p->aNode );
  129309. if( p->iChild && bFirst==0 ) p->iChild++;
  129310. if( p->iOff>=p->nNode ){
  129311. /* EOF */
  129312. p->aNode = 0;
  129313. }else{
  129314. if( bFirst==0 ){
  129315. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  129316. }
  129317. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  129318. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  129319. if( rc==SQLITE_OK ){
  129320. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  129321. p->term.n = nPrefix+nSuffix;
  129322. p->iOff += nSuffix;
  129323. if( p->iChild==0 ){
  129324. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  129325. p->aDoclist = &p->aNode[p->iOff];
  129326. p->iOff += p->nDoclist;
  129327. }
  129328. }
  129329. }
  129330. assert( p->iOff<=p->nNode );
  129331. return rc;
  129332. }
  129333. /*
  129334. ** Release all dynamic resources held by node-reader object *p.
  129335. */
  129336. static void nodeReaderRelease(NodeReader *p){
  129337. sqlite3_free(p->term.a);
  129338. }
  129339. /*
  129340. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  129341. **
  129342. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  129343. ** point to the first entry on the node (if any). Otherwise, an SQLite
  129344. ** error code is returned.
  129345. */
  129346. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  129347. memset(p, 0, sizeof(NodeReader));
  129348. p->aNode = aNode;
  129349. p->nNode = nNode;
  129350. /* Figure out if this is a leaf or an internal node. */
  129351. if( p->aNode[0] ){
  129352. /* An internal node. */
  129353. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  129354. }else{
  129355. p->iOff = 1;
  129356. }
  129357. return nodeReaderNext(p);
  129358. }
  129359. /*
  129360. ** This function is called while writing an FTS segment each time a leaf o
  129361. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  129362. ** to be greater than the largest key on the node just written, but smaller
  129363. ** than or equal to the first key that will be written to the next leaf
  129364. ** node.
  129365. **
  129366. ** The block id of the leaf node just written to disk may be found in
  129367. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  129368. */
  129369. static int fts3IncrmergePush(
  129370. Fts3Table *p, /* Fts3 table handle */
  129371. IncrmergeWriter *pWriter, /* Writer object */
  129372. const char *zTerm, /* Term to write to internal node */
  129373. int nTerm /* Bytes at zTerm */
  129374. ){
  129375. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  129376. int iLayer;
  129377. assert( nTerm>0 );
  129378. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  129379. sqlite3_int64 iNextPtr = 0;
  129380. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  129381. int rc = SQLITE_OK;
  129382. int nPrefix;
  129383. int nSuffix;
  129384. int nSpace;
  129385. /* Figure out how much space the key will consume if it is written to
  129386. ** the current node of layer iLayer. Due to the prefix compression,
  129387. ** the space required changes depending on which node the key is to
  129388. ** be added to. */
  129389. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  129390. nSuffix = nTerm - nPrefix;
  129391. nSpace = sqlite3Fts3VarintLen(nPrefix);
  129392. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129393. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  129394. /* If the current node of layer iLayer contains zero keys, or if adding
  129395. ** the key to it will not cause it to grow to larger than nNodeSize
  129396. ** bytes in size, write the key here. */
  129397. Blob *pBlk = &pNode->block;
  129398. if( pBlk->n==0 ){
  129399. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  129400. if( rc==SQLITE_OK ){
  129401. pBlk->a[0] = (char)iLayer;
  129402. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  129403. }
  129404. }
  129405. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  129406. blobGrowBuffer(&pNode->key, nTerm, &rc);
  129407. if( rc==SQLITE_OK ){
  129408. if( pNode->key.n ){
  129409. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  129410. }
  129411. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  129412. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  129413. pBlk->n += nSuffix;
  129414. memcpy(pNode->key.a, zTerm, nTerm);
  129415. pNode->key.n = nTerm;
  129416. }
  129417. }else{
  129418. /* Otherwise, flush the current node of layer iLayer to disk.
  129419. ** Then allocate a new, empty sibling node. The key will be written
  129420. ** into the parent of this node. */
  129421. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  129422. assert( pNode->block.nAlloc>=p->nNodeSize );
  129423. pNode->block.a[0] = (char)iLayer;
  129424. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  129425. iNextPtr = pNode->iBlock;
  129426. pNode->iBlock++;
  129427. pNode->key.n = 0;
  129428. }
  129429. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  129430. iPtr = iNextPtr;
  129431. }
  129432. assert( 0 );
  129433. return 0;
  129434. }
  129435. /*
  129436. ** Append a term and (optionally) doclist to the FTS segment node currently
  129437. ** stored in blob *pNode. The node need not contain any terms, but the
  129438. ** header must be written before this function is called.
  129439. **
  129440. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  129441. ** followed by the left-hand-child varint for an internal node.
  129442. **
  129443. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  129444. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  129445. ** node, both aDoclist and nDoclist must be passed 0.
  129446. **
  129447. ** If the size of the value in blob pPrev is zero, then this is the first
  129448. ** term written to the node. Otherwise, pPrev contains a copy of the
  129449. ** previous term. Before this function returns, it is updated to contain a
  129450. ** copy of zTerm/nTerm.
  129451. **
  129452. ** It is assumed that the buffer associated with pNode is already large
  129453. ** enough to accommodate the new entry. The buffer associated with pPrev
  129454. ** is extended by this function if requrired.
  129455. **
  129456. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  129457. ** returned. Otherwise, SQLITE_OK.
  129458. */
  129459. static int fts3AppendToNode(
  129460. Blob *pNode, /* Current node image to append to */
  129461. Blob *pPrev, /* Buffer containing previous term written */
  129462. const char *zTerm, /* New term to write */
  129463. int nTerm, /* Size of zTerm in bytes */
  129464. const char *aDoclist, /* Doclist (or NULL) to write */
  129465. int nDoclist /* Size of aDoclist in bytes */
  129466. ){
  129467. int rc = SQLITE_OK; /* Return code */
  129468. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  129469. int nPrefix; /* Size of term prefix in bytes */
  129470. int nSuffix; /* Size of term suffix in bytes */
  129471. /* Node must have already been started. There must be a doclist for a
  129472. ** leaf node, and there must not be a doclist for an internal node. */
  129473. assert( pNode->n>0 );
  129474. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  129475. blobGrowBuffer(pPrev, nTerm, &rc);
  129476. if( rc!=SQLITE_OK ) return rc;
  129477. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  129478. nSuffix = nTerm - nPrefix;
  129479. memcpy(pPrev->a, zTerm, nTerm);
  129480. pPrev->n = nTerm;
  129481. if( bFirst==0 ){
  129482. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  129483. }
  129484. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  129485. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  129486. pNode->n += nSuffix;
  129487. if( aDoclist ){
  129488. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  129489. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  129490. pNode->n += nDoclist;
  129491. }
  129492. assert( pNode->n<=pNode->nAlloc );
  129493. return SQLITE_OK;
  129494. }
  129495. /*
  129496. ** Append the current term and doclist pointed to by cursor pCsr to the
  129497. ** appendable b-tree segment opened for writing by pWriter.
  129498. **
  129499. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  129500. */
  129501. static int fts3IncrmergeAppend(
  129502. Fts3Table *p, /* Fts3 table handle */
  129503. IncrmergeWriter *pWriter, /* Writer object */
  129504. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  129505. ){
  129506. const char *zTerm = pCsr->zTerm;
  129507. int nTerm = pCsr->nTerm;
  129508. const char *aDoclist = pCsr->aDoclist;
  129509. int nDoclist = pCsr->nDoclist;
  129510. int rc = SQLITE_OK; /* Return code */
  129511. int nSpace; /* Total space in bytes required on leaf */
  129512. int nPrefix; /* Size of prefix shared with previous term */
  129513. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  129514. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  129515. pLeaf = &pWriter->aNodeWriter[0];
  129516. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  129517. nSuffix = nTerm - nPrefix;
  129518. nSpace = sqlite3Fts3VarintLen(nPrefix);
  129519. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129520. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  129521. /* If the current block is not empty, and if adding this term/doclist
  129522. ** to the current block would make it larger than Fts3Table.nNodeSize
  129523. ** bytes, write this block out to the database. */
  129524. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  129525. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  129526. pWriter->nWork++;
  129527. /* Add the current term to the parent node. The term added to the
  129528. ** parent must:
  129529. **
  129530. ** a) be greater than the largest term on the leaf node just written
  129531. ** to the database (still available in pLeaf->key), and
  129532. **
  129533. ** b) be less than or equal to the term about to be added to the new
  129534. ** leaf node (zTerm/nTerm).
  129535. **
  129536. ** In other words, it must be the prefix of zTerm 1 byte longer than
  129537. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  129538. */
  129539. if( rc==SQLITE_OK ){
  129540. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  129541. }
  129542. /* Advance to the next output block */
  129543. pLeaf->iBlock++;
  129544. pLeaf->key.n = 0;
  129545. pLeaf->block.n = 0;
  129546. nSuffix = nTerm;
  129547. nSpace = 1;
  129548. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129549. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  129550. }
  129551. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  129552. if( rc==SQLITE_OK ){
  129553. if( pLeaf->block.n==0 ){
  129554. pLeaf->block.n = 1;
  129555. pLeaf->block.a[0] = '\0';
  129556. }
  129557. rc = fts3AppendToNode(
  129558. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  129559. );
  129560. }
  129561. return rc;
  129562. }
  129563. /*
  129564. ** This function is called to release all dynamic resources held by the
  129565. ** merge-writer object pWriter, and if no error has occurred, to flush
  129566. ** all outstanding node buffers held by pWriter to disk.
  129567. **
  129568. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  129569. ** is made to write any data to disk. Instead, this function serves only
  129570. ** to release outstanding resources.
  129571. **
  129572. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  129573. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  129574. ** returning.
  129575. */
  129576. static void fts3IncrmergeRelease(
  129577. Fts3Table *p, /* FTS3 table handle */
  129578. IncrmergeWriter *pWriter, /* Merge-writer object */
  129579. int *pRc /* IN/OUT: Error code */
  129580. ){
  129581. int i; /* Used to iterate through non-root layers */
  129582. int iRoot; /* Index of root in pWriter->aNodeWriter */
  129583. NodeWriter *pRoot; /* NodeWriter for root node */
  129584. int rc = *pRc; /* Error code */
  129585. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  129586. ** root node. If the segment fits entirely on a single leaf node, iRoot
  129587. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  129588. ** will be 1. And so on. */
  129589. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  129590. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  129591. if( pNode->block.n>0 ) break;
  129592. assert( *pRc || pNode->block.nAlloc==0 );
  129593. assert( *pRc || pNode->key.nAlloc==0 );
  129594. sqlite3_free(pNode->block.a);
  129595. sqlite3_free(pNode->key.a);
  129596. }
  129597. /* Empty output segment. This is a no-op. */
  129598. if( iRoot<0 ) return;
  129599. /* The entire output segment fits on a single node. Normally, this means
  129600. ** the node would be stored as a blob in the "root" column of the %_segdir
  129601. ** table. However, this is not permitted in this case. The problem is that
  129602. ** space has already been reserved in the %_segments table, and so the
  129603. ** start_block and end_block fields of the %_segdir table must be populated.
  129604. ** And, by design or by accident, released versions of FTS cannot handle
  129605. ** segments that fit entirely on the root node with start_block!=0.
  129606. **
  129607. ** Instead, create a synthetic root node that contains nothing but a
  129608. ** pointer to the single content node. So that the segment consists of a
  129609. ** single leaf and a single interior (root) node.
  129610. **
  129611. ** Todo: Better might be to defer allocating space in the %_segments
  129612. ** table until we are sure it is needed.
  129613. */
  129614. if( iRoot==0 ){
  129615. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  129616. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  129617. if( rc==SQLITE_OK ){
  129618. pBlock->a[0] = 0x01;
  129619. pBlock->n = 1 + sqlite3Fts3PutVarint(
  129620. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  129621. );
  129622. }
  129623. iRoot = 1;
  129624. }
  129625. pRoot = &pWriter->aNodeWriter[iRoot];
  129626. /* Flush all currently outstanding nodes to disk. */
  129627. for(i=0; i<iRoot; i++){
  129628. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  129629. if( pNode->block.n>0 && rc==SQLITE_OK ){
  129630. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  129631. }
  129632. sqlite3_free(pNode->block.a);
  129633. sqlite3_free(pNode->key.a);
  129634. }
  129635. /* Write the %_segdir record. */
  129636. if( rc==SQLITE_OK ){
  129637. rc = fts3WriteSegdir(p,
  129638. pWriter->iAbsLevel+1, /* level */
  129639. pWriter->iIdx, /* idx */
  129640. pWriter->iStart, /* start_block */
  129641. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  129642. pWriter->iEnd, /* end_block */
  129643. pRoot->block.a, pRoot->block.n /* root */
  129644. );
  129645. }
  129646. sqlite3_free(pRoot->block.a);
  129647. sqlite3_free(pRoot->key.a);
  129648. *pRc = rc;
  129649. }
  129650. /*
  129651. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  129652. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  129653. ** the other, it is considered to be smaller than the other.
  129654. **
  129655. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  129656. ** if it is greater.
  129657. */
  129658. static int fts3TermCmp(
  129659. const char *zLhs, int nLhs, /* LHS of comparison */
  129660. const char *zRhs, int nRhs /* RHS of comparison */
  129661. ){
  129662. int nCmp = MIN(nLhs, nRhs);
  129663. int res;
  129664. res = memcmp(zLhs, zRhs, nCmp);
  129665. if( res==0 ) res = nLhs - nRhs;
  129666. return res;
  129667. }
  129668. /*
  129669. ** Query to see if the entry in the %_segments table with blockid iEnd is
  129670. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  129671. ** returning. Otherwise, set *pbRes to 0.
  129672. **
  129673. ** Or, if an error occurs while querying the database, return an SQLite
  129674. ** error code. The final value of *pbRes is undefined in this case.
  129675. **
  129676. ** This is used to test if a segment is an "appendable" segment. If it
  129677. ** is, then a NULL entry has been inserted into the %_segments table
  129678. ** with blockid %_segdir.end_block.
  129679. */
  129680. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  129681. int bRes = 0; /* Result to set *pbRes to */
  129682. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  129683. int rc; /* Return code */
  129684. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  129685. if( rc==SQLITE_OK ){
  129686. sqlite3_bind_int64(pCheck, 1, iEnd);
  129687. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  129688. rc = sqlite3_reset(pCheck);
  129689. }
  129690. *pbRes = bRes;
  129691. return rc;
  129692. }
  129693. /*
  129694. ** This function is called when initializing an incremental-merge operation.
  129695. ** It checks if the existing segment with index value iIdx at absolute level
  129696. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  129697. ** merge-writer object *pWriter is initialized to write to it.
  129698. **
  129699. ** An existing segment can be appended to by an incremental merge if:
  129700. **
  129701. ** * It was initially created as an appendable segment (with all required
  129702. ** space pre-allocated), and
  129703. **
  129704. ** * The first key read from the input (arguments zKey and nKey) is
  129705. ** greater than the largest key currently stored in the potential
  129706. ** output segment.
  129707. */
  129708. static int fts3IncrmergeLoad(
  129709. Fts3Table *p, /* Fts3 table handle */
  129710. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  129711. int iIdx, /* Index of candidate output segment */
  129712. const char *zKey, /* First key to write */
  129713. int nKey, /* Number of bytes in nKey */
  129714. IncrmergeWriter *pWriter /* Populate this object */
  129715. ){
  129716. int rc; /* Return code */
  129717. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  129718. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  129719. if( rc==SQLITE_OK ){
  129720. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  129721. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  129722. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  129723. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  129724. int nRoot = 0; /* Size of aRoot[] in bytes */
  129725. int rc2; /* Return code from sqlite3_reset() */
  129726. int bAppendable = 0; /* Set to true if segment is appendable */
  129727. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  129728. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  129729. sqlite3_bind_int(pSelect, 2, iIdx);
  129730. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  129731. iStart = sqlite3_column_int64(pSelect, 1);
  129732. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  129733. iEnd = sqlite3_column_int64(pSelect, 3);
  129734. nRoot = sqlite3_column_bytes(pSelect, 4);
  129735. aRoot = sqlite3_column_blob(pSelect, 4);
  129736. }else{
  129737. return sqlite3_reset(pSelect);
  129738. }
  129739. /* Check for the zero-length marker in the %_segments table */
  129740. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  129741. /* Check that zKey/nKey is larger than the largest key the candidate */
  129742. if( rc==SQLITE_OK && bAppendable ){
  129743. char *aLeaf = 0;
  129744. int nLeaf = 0;
  129745. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  129746. if( rc==SQLITE_OK ){
  129747. NodeReader reader;
  129748. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  129749. rc==SQLITE_OK && reader.aNode;
  129750. rc = nodeReaderNext(&reader)
  129751. ){
  129752. assert( reader.aNode );
  129753. }
  129754. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  129755. bAppendable = 0;
  129756. }
  129757. nodeReaderRelease(&reader);
  129758. }
  129759. sqlite3_free(aLeaf);
  129760. }
  129761. if( rc==SQLITE_OK && bAppendable ){
  129762. /* It is possible to append to this segment. Set up the IncrmergeWriter
  129763. ** object to do so. */
  129764. int i;
  129765. int nHeight = (int)aRoot[0];
  129766. NodeWriter *pNode;
  129767. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  129768. pWriter->iStart = iStart;
  129769. pWriter->iEnd = iEnd;
  129770. pWriter->iAbsLevel = iAbsLevel;
  129771. pWriter->iIdx = iIdx;
  129772. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  129773. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  129774. }
  129775. pNode = &pWriter->aNodeWriter[nHeight];
  129776. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  129777. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  129778. if( rc==SQLITE_OK ){
  129779. memcpy(pNode->block.a, aRoot, nRoot);
  129780. pNode->block.n = nRoot;
  129781. }
  129782. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  129783. NodeReader reader;
  129784. pNode = &pWriter->aNodeWriter[i];
  129785. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  129786. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  129787. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  129788. if( rc==SQLITE_OK ){
  129789. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  129790. pNode->key.n = reader.term.n;
  129791. if( i>0 ){
  129792. char *aBlock = 0;
  129793. int nBlock = 0;
  129794. pNode = &pWriter->aNodeWriter[i-1];
  129795. pNode->iBlock = reader.iChild;
  129796. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  129797. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  129798. if( rc==SQLITE_OK ){
  129799. memcpy(pNode->block.a, aBlock, nBlock);
  129800. pNode->block.n = nBlock;
  129801. }
  129802. sqlite3_free(aBlock);
  129803. }
  129804. }
  129805. nodeReaderRelease(&reader);
  129806. }
  129807. }
  129808. rc2 = sqlite3_reset(pSelect);
  129809. if( rc==SQLITE_OK ) rc = rc2;
  129810. }
  129811. return rc;
  129812. }
  129813. /*
  129814. ** Determine the largest segment index value that exists within absolute
  129815. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  129816. ** one before returning SQLITE_OK. Or, if there are no segments at all
  129817. ** within level iAbsLevel, set *piIdx to zero.
  129818. **
  129819. ** If an error occurs, return an SQLite error code. The final value of
  129820. ** *piIdx is undefined in this case.
  129821. */
  129822. static int fts3IncrmergeOutputIdx(
  129823. Fts3Table *p, /* FTS Table handle */
  129824. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  129825. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  129826. ){
  129827. int rc;
  129828. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  129829. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  129830. if( rc==SQLITE_OK ){
  129831. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  129832. sqlite3_step(pOutputIdx);
  129833. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  129834. rc = sqlite3_reset(pOutputIdx);
  129835. }
  129836. return rc;
  129837. }
  129838. /*
  129839. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  129840. ** with idx value iIdx.
  129841. **
  129842. ** In the %_segdir table, a segment is defined by the values in three
  129843. ** columns:
  129844. **
  129845. ** start_block
  129846. ** leaves_end_block
  129847. ** end_block
  129848. **
  129849. ** When an appendable segment is allocated, it is estimated that the
  129850. ** maximum number of leaf blocks that may be required is the sum of the
  129851. ** number of leaf blocks consumed by the input segments, plus the number
  129852. ** of input segments, multiplied by two. This value is stored in stack
  129853. ** variable nLeafEst.
  129854. **
  129855. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  129856. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  129857. ** array of leaf nodes starts at the first block allocated. The array
  129858. ** of interior nodes that are parents of the leaf nodes start at block
  129859. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  129860. **
  129861. ** In the actual code below, the value "16" is replaced with the
  129862. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  129863. */
  129864. static int fts3IncrmergeWriter(
  129865. Fts3Table *p, /* Fts3 table handle */
  129866. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  129867. int iIdx, /* Index of new output segment */
  129868. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  129869. IncrmergeWriter *pWriter /* Populate this object */
  129870. ){
  129871. int rc; /* Return Code */
  129872. int i; /* Iterator variable */
  129873. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  129874. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  129875. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  129876. /* Calculate nLeafEst. */
  129877. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  129878. if( rc==SQLITE_OK ){
  129879. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  129880. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  129881. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  129882. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  129883. }
  129884. rc = sqlite3_reset(pLeafEst);
  129885. }
  129886. if( rc!=SQLITE_OK ) return rc;
  129887. /* Calculate the first block to use in the output segment */
  129888. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  129889. if( rc==SQLITE_OK ){
  129890. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  129891. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  129892. pWriter->iEnd = pWriter->iStart - 1;
  129893. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  129894. }
  129895. rc = sqlite3_reset(pFirstBlock);
  129896. }
  129897. if( rc!=SQLITE_OK ) return rc;
  129898. /* Insert the marker in the %_segments table to make sure nobody tries
  129899. ** to steal the space just allocated. This is also used to identify
  129900. ** appendable segments. */
  129901. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  129902. if( rc!=SQLITE_OK ) return rc;
  129903. pWriter->iAbsLevel = iAbsLevel;
  129904. pWriter->nLeafEst = nLeafEst;
  129905. pWriter->iIdx = iIdx;
  129906. /* Set up the array of NodeWriter objects */
  129907. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  129908. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  129909. }
  129910. return SQLITE_OK;
  129911. }
  129912. /*
  129913. ** Remove an entry from the %_segdir table. This involves running the
  129914. ** following two statements:
  129915. **
  129916. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  129917. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  129918. **
  129919. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  129920. ** statement ensures that the remaining segments have contiguously allocated
  129921. ** idx values.
  129922. */
  129923. static int fts3RemoveSegdirEntry(
  129924. Fts3Table *p, /* FTS3 table handle */
  129925. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  129926. int iIdx /* Index of %_segdir entry to delete */
  129927. ){
  129928. int rc; /* Return code */
  129929. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  129930. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  129931. if( rc==SQLITE_OK ){
  129932. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  129933. sqlite3_bind_int(pDelete, 2, iIdx);
  129934. sqlite3_step(pDelete);
  129935. rc = sqlite3_reset(pDelete);
  129936. }
  129937. return rc;
  129938. }
  129939. /*
  129940. ** One or more segments have just been removed from absolute level iAbsLevel.
  129941. ** Update the 'idx' values of the remaining segments in the level so that
  129942. ** the idx values are a contiguous sequence starting from 0.
  129943. */
  129944. static int fts3RepackSegdirLevel(
  129945. Fts3Table *p, /* FTS3 table handle */
  129946. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  129947. ){
  129948. int rc; /* Return code */
  129949. int *aIdx = 0; /* Array of remaining idx values */
  129950. int nIdx = 0; /* Valid entries in aIdx[] */
  129951. int nAlloc = 0; /* Allocated size of aIdx[] */
  129952. int i; /* Iterator variable */
  129953. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  129954. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  129955. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  129956. if( rc==SQLITE_OK ){
  129957. int rc2;
  129958. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  129959. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  129960. if( nIdx>=nAlloc ){
  129961. int *aNew;
  129962. nAlloc += 16;
  129963. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  129964. if( !aNew ){
  129965. rc = SQLITE_NOMEM;
  129966. break;
  129967. }
  129968. aIdx = aNew;
  129969. }
  129970. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  129971. }
  129972. rc2 = sqlite3_reset(pSelect);
  129973. if( rc==SQLITE_OK ) rc = rc2;
  129974. }
  129975. if( rc==SQLITE_OK ){
  129976. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  129977. }
  129978. if( rc==SQLITE_OK ){
  129979. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  129980. }
  129981. assert( p->bIgnoreSavepoint==0 );
  129982. p->bIgnoreSavepoint = 1;
  129983. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  129984. if( aIdx[i]!=i ){
  129985. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  129986. sqlite3_bind_int(pUpdate, 1, i);
  129987. sqlite3_step(pUpdate);
  129988. rc = sqlite3_reset(pUpdate);
  129989. }
  129990. }
  129991. p->bIgnoreSavepoint = 0;
  129992. sqlite3_free(aIdx);
  129993. return rc;
  129994. }
  129995. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  129996. pNode->a[0] = (char)iHeight;
  129997. if( iChild ){
  129998. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  129999. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  130000. }else{
  130001. assert( pNode->nAlloc>=1 );
  130002. pNode->n = 1;
  130003. }
  130004. }
  130005. /*
  130006. ** The first two arguments are a pointer to and the size of a segment b-tree
  130007. ** node. The node may be a leaf or an internal node.
  130008. **
  130009. ** This function creates a new node image in blob object *pNew by copying
  130010. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  130011. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  130012. */
  130013. static int fts3TruncateNode(
  130014. const char *aNode, /* Current node image */
  130015. int nNode, /* Size of aNode in bytes */
  130016. Blob *pNew, /* OUT: Write new node image here */
  130017. const char *zTerm, /* Omit all terms smaller than this */
  130018. int nTerm, /* Size of zTerm in bytes */
  130019. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  130020. ){
  130021. NodeReader reader; /* Reader object */
  130022. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  130023. int rc = SQLITE_OK; /* Return code */
  130024. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  130025. /* Allocate required output space */
  130026. blobGrowBuffer(pNew, nNode, &rc);
  130027. if( rc!=SQLITE_OK ) return rc;
  130028. pNew->n = 0;
  130029. /* Populate new node buffer */
  130030. for(rc = nodeReaderInit(&reader, aNode, nNode);
  130031. rc==SQLITE_OK && reader.aNode;
  130032. rc = nodeReaderNext(&reader)
  130033. ){
  130034. if( pNew->n==0 ){
  130035. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  130036. if( res<0 || (bLeaf==0 && res==0) ) continue;
  130037. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  130038. *piBlock = reader.iChild;
  130039. }
  130040. rc = fts3AppendToNode(
  130041. pNew, &prev, reader.term.a, reader.term.n,
  130042. reader.aDoclist, reader.nDoclist
  130043. );
  130044. if( rc!=SQLITE_OK ) break;
  130045. }
  130046. if( pNew->n==0 ){
  130047. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  130048. *piBlock = reader.iChild;
  130049. }
  130050. assert( pNew->n<=pNew->nAlloc );
  130051. nodeReaderRelease(&reader);
  130052. sqlite3_free(prev.a);
  130053. return rc;
  130054. }
  130055. /*
  130056. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  130057. ** level iAbsLevel. This may involve deleting entries from the %_segments
  130058. ** table, and modifying existing entries in both the %_segments and %_segdir
  130059. ** tables.
  130060. **
  130061. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  130062. ** SQLite error code otherwise.
  130063. */
  130064. static int fts3TruncateSegment(
  130065. Fts3Table *p, /* FTS3 table handle */
  130066. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  130067. int iIdx, /* Index within level of segment to modify */
  130068. const char *zTerm, /* Remove terms smaller than this */
  130069. int nTerm /* Number of bytes in buffer zTerm */
  130070. ){
  130071. int rc = SQLITE_OK; /* Return code */
  130072. Blob root = {0,0,0}; /* New root page image */
  130073. Blob block = {0,0,0}; /* Buffer used for any other block */
  130074. sqlite3_int64 iBlock = 0; /* Block id */
  130075. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  130076. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  130077. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  130078. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  130079. if( rc==SQLITE_OK ){
  130080. int rc2; /* sqlite3_reset() return code */
  130081. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  130082. sqlite3_bind_int(pFetch, 2, iIdx);
  130083. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  130084. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  130085. int nRoot = sqlite3_column_bytes(pFetch, 4);
  130086. iOldStart = sqlite3_column_int64(pFetch, 1);
  130087. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  130088. }
  130089. rc2 = sqlite3_reset(pFetch);
  130090. if( rc==SQLITE_OK ) rc = rc2;
  130091. }
  130092. while( rc==SQLITE_OK && iBlock ){
  130093. char *aBlock = 0;
  130094. int nBlock = 0;
  130095. iNewStart = iBlock;
  130096. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  130097. if( rc==SQLITE_OK ){
  130098. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  130099. }
  130100. if( rc==SQLITE_OK ){
  130101. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  130102. }
  130103. sqlite3_free(aBlock);
  130104. }
  130105. /* Variable iNewStart now contains the first valid leaf node. */
  130106. if( rc==SQLITE_OK && iNewStart ){
  130107. sqlite3_stmt *pDel = 0;
  130108. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  130109. if( rc==SQLITE_OK ){
  130110. sqlite3_bind_int64(pDel, 1, iOldStart);
  130111. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  130112. sqlite3_step(pDel);
  130113. rc = sqlite3_reset(pDel);
  130114. }
  130115. }
  130116. if( rc==SQLITE_OK ){
  130117. sqlite3_stmt *pChomp = 0;
  130118. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  130119. if( rc==SQLITE_OK ){
  130120. sqlite3_bind_int64(pChomp, 1, iNewStart);
  130121. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  130122. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  130123. sqlite3_bind_int(pChomp, 4, iIdx);
  130124. sqlite3_step(pChomp);
  130125. rc = sqlite3_reset(pChomp);
  130126. }
  130127. }
  130128. sqlite3_free(root.a);
  130129. sqlite3_free(block.a);
  130130. return rc;
  130131. }
  130132. /*
  130133. ** This function is called after an incrmental-merge operation has run to
  130134. ** merge (or partially merge) two or more segments from absolute level
  130135. ** iAbsLevel.
  130136. **
  130137. ** Each input segment is either removed from the db completely (if all of
  130138. ** its data was copied to the output segment by the incrmerge operation)
  130139. ** or modified in place so that it no longer contains those entries that
  130140. ** have been duplicated in the output segment.
  130141. */
  130142. static int fts3IncrmergeChomp(
  130143. Fts3Table *p, /* FTS table handle */
  130144. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  130145. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  130146. int *pnRem /* Number of segments not deleted */
  130147. ){
  130148. int i;
  130149. int nRem = 0;
  130150. int rc = SQLITE_OK;
  130151. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  130152. Fts3SegReader *pSeg = 0;
  130153. int j;
  130154. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  130155. ** somewhere in the pCsr->apSegment[] array. */
  130156. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  130157. pSeg = pCsr->apSegment[j];
  130158. if( pSeg->iIdx==i ) break;
  130159. }
  130160. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  130161. if( pSeg->aNode==0 ){
  130162. /* Seg-reader is at EOF. Remove the entire input segment. */
  130163. rc = fts3DeleteSegment(p, pSeg);
  130164. if( rc==SQLITE_OK ){
  130165. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  130166. }
  130167. *pnRem = 0;
  130168. }else{
  130169. /* The incremental merge did not copy all the data from this
  130170. ** segment to the upper level. The segment is modified in place
  130171. ** so that it contains no keys smaller than zTerm/nTerm. */
  130172. const char *zTerm = pSeg->zTerm;
  130173. int nTerm = pSeg->nTerm;
  130174. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  130175. nRem++;
  130176. }
  130177. }
  130178. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  130179. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  130180. }
  130181. *pnRem = nRem;
  130182. return rc;
  130183. }
  130184. /*
  130185. ** Store an incr-merge hint in the database.
  130186. */
  130187. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  130188. sqlite3_stmt *pReplace = 0;
  130189. int rc; /* Return code */
  130190. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  130191. if( rc==SQLITE_OK ){
  130192. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  130193. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  130194. sqlite3_step(pReplace);
  130195. rc = sqlite3_reset(pReplace);
  130196. }
  130197. return rc;
  130198. }
  130199. /*
  130200. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  130201. ** exists, is stored in the rowid==1 row of the %_stat table.
  130202. **
  130203. ** If successful, populate blob *pHint with the value read from the %_stat
  130204. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  130205. ** SQLite error code.
  130206. */
  130207. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  130208. sqlite3_stmt *pSelect = 0;
  130209. int rc;
  130210. pHint->n = 0;
  130211. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  130212. if( rc==SQLITE_OK ){
  130213. int rc2;
  130214. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  130215. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  130216. const char *aHint = sqlite3_column_blob(pSelect, 0);
  130217. int nHint = sqlite3_column_bytes(pSelect, 0);
  130218. if( aHint ){
  130219. blobGrowBuffer(pHint, nHint, &rc);
  130220. if( rc==SQLITE_OK ){
  130221. memcpy(pHint->a, aHint, nHint);
  130222. pHint->n = nHint;
  130223. }
  130224. }
  130225. }
  130226. rc2 = sqlite3_reset(pSelect);
  130227. if( rc==SQLITE_OK ) rc = rc2;
  130228. }
  130229. return rc;
  130230. }
  130231. /*
  130232. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  130233. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  130234. ** consists of two varints, the absolute level number of the input segments
  130235. ** and the number of input segments.
  130236. **
  130237. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  130238. ** set *pRc to an SQLite error code before returning.
  130239. */
  130240. static void fts3IncrmergeHintPush(
  130241. Blob *pHint, /* Hint blob to append to */
  130242. i64 iAbsLevel, /* First varint to store in hint */
  130243. int nInput, /* Second varint to store in hint */
  130244. int *pRc /* IN/OUT: Error code */
  130245. ){
  130246. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  130247. if( *pRc==SQLITE_OK ){
  130248. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  130249. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  130250. }
  130251. }
  130252. /*
  130253. ** Read the last entry (most recently pushed) from the hint blob *pHint
  130254. ** and then remove the entry. Write the two values read to *piAbsLevel and
  130255. ** *pnInput before returning.
  130256. **
  130257. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  130258. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  130259. */
  130260. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  130261. const int nHint = pHint->n;
  130262. int i;
  130263. i = pHint->n-2;
  130264. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  130265. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  130266. pHint->n = i;
  130267. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  130268. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  130269. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  130270. return SQLITE_OK;
  130271. }
  130272. /*
  130273. ** Attempt an incremental merge that writes nMerge leaf blocks.
  130274. **
  130275. ** Incremental merges happen nMin segments at a time. The two
  130276. ** segments to be merged are the nMin oldest segments (the ones with
  130277. ** the smallest indexes) in the highest level that contains at least
  130278. ** nMin segments. Multiple merges might occur in an attempt to write the
  130279. ** quota of nMerge leaf blocks.
  130280. */
  130281. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  130282. int rc; /* Return code */
  130283. int nRem = nMerge; /* Number of leaf pages yet to be written */
  130284. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  130285. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  130286. IncrmergeWriter *pWriter; /* Writer object */
  130287. int nSeg = 0; /* Number of input segments */
  130288. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  130289. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  130290. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  130291. /* Allocate space for the cursor, filter and writer objects */
  130292. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  130293. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  130294. if( !pWriter ) return SQLITE_NOMEM;
  130295. pFilter = (Fts3SegFilter *)&pWriter[1];
  130296. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  130297. rc = fts3IncrmergeHintLoad(p, &hint);
  130298. while( rc==SQLITE_OK && nRem>0 ){
  130299. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  130300. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  130301. int bUseHint = 0; /* True if attempting to append */
  130302. /* Search the %_segdir table for the absolute level with the smallest
  130303. ** relative level number that contains at least nMin segments, if any.
  130304. ** If one is found, set iAbsLevel to the absolute level number and
  130305. ** nSeg to nMin. If no level with at least nMin segments can be found,
  130306. ** set nSeg to -1.
  130307. */
  130308. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  130309. sqlite3_bind_int(pFindLevel, 1, nMin);
  130310. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  130311. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  130312. nSeg = nMin;
  130313. }else{
  130314. nSeg = -1;
  130315. }
  130316. rc = sqlite3_reset(pFindLevel);
  130317. /* If the hint read from the %_stat table is not empty, check if the
  130318. ** last entry in it specifies a relative level smaller than or equal
  130319. ** to the level identified by the block above (if any). If so, this
  130320. ** iteration of the loop will work on merging at the hinted level.
  130321. */
  130322. if( rc==SQLITE_OK && hint.n ){
  130323. int nHint = hint.n;
  130324. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  130325. int nHintSeg = 0; /* Hint number of segments */
  130326. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  130327. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  130328. iAbsLevel = iHintAbsLevel;
  130329. nSeg = nHintSeg;
  130330. bUseHint = 1;
  130331. bDirtyHint = 1;
  130332. }else{
  130333. /* This undoes the effect of the HintPop() above - so that no entry
  130334. ** is removed from the hint blob. */
  130335. hint.n = nHint;
  130336. }
  130337. }
  130338. /* If nSeg is less that zero, then there is no level with at least
  130339. ** nMin segments and no hint in the %_stat table. No work to do.
  130340. ** Exit early in this case. */
  130341. if( nSeg<0 ) break;
  130342. /* Open a cursor to iterate through the contents of the oldest nSeg
  130343. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  130344. ** the 'hint' parameters, it is possible that there are less than nSeg
  130345. ** segments available in level iAbsLevel. In this case, no work is
  130346. ** done on iAbsLevel - fall through to the next iteration of the loop
  130347. ** to start work on some other level. */
  130348. memset(pWriter, 0, nAlloc);
  130349. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  130350. if( rc==SQLITE_OK ){
  130351. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  130352. }
  130353. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  130354. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  130355. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  130356. ){
  130357. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  130358. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  130359. if( rc==SQLITE_OK ){
  130360. if( bUseHint && iIdx>0 ){
  130361. const char *zKey = pCsr->zTerm;
  130362. int nKey = pCsr->nTerm;
  130363. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  130364. }else{
  130365. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  130366. }
  130367. }
  130368. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  130369. fts3LogMerge(nSeg, iAbsLevel);
  130370. do {
  130371. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  130372. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  130373. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  130374. }while( rc==SQLITE_ROW );
  130375. /* Update or delete the input segments */
  130376. if( rc==SQLITE_OK ){
  130377. nRem -= (1 + pWriter->nWork);
  130378. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  130379. if( nSeg!=0 ){
  130380. bDirtyHint = 1;
  130381. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  130382. }
  130383. }
  130384. }
  130385. fts3IncrmergeRelease(p, pWriter, &rc);
  130386. }
  130387. sqlite3Fts3SegReaderFinish(pCsr);
  130388. }
  130389. /* Write the hint values into the %_stat table for the next incr-merger */
  130390. if( bDirtyHint && rc==SQLITE_OK ){
  130391. rc = fts3IncrmergeHintStore(p, &hint);
  130392. }
  130393. sqlite3_free(pWriter);
  130394. sqlite3_free(hint.a);
  130395. return rc;
  130396. }
  130397. /*
  130398. ** Convert the text beginning at *pz into an integer and return
  130399. ** its value. Advance *pz to point to the first character past
  130400. ** the integer.
  130401. */
  130402. static int fts3Getint(const char **pz){
  130403. const char *z = *pz;
  130404. int i = 0;
  130405. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  130406. *pz = z;
  130407. return i;
  130408. }
  130409. /*
  130410. ** Process statements of the form:
  130411. **
  130412. ** INSERT INTO table(table) VALUES('merge=A,B');
  130413. **
  130414. ** A and B are integers that decode to be the number of leaf pages
  130415. ** written for the merge, and the minimum number of segments on a level
  130416. ** before it will be selected for a merge, respectively.
  130417. */
  130418. static int fts3DoIncrmerge(
  130419. Fts3Table *p, /* FTS3 table handle */
  130420. const char *zParam /* Nul-terminated string containing "A,B" */
  130421. ){
  130422. int rc;
  130423. int nMin = (FTS3_MERGE_COUNT / 2);
  130424. int nMerge = 0;
  130425. const char *z = zParam;
  130426. /* Read the first integer value */
  130427. nMerge = fts3Getint(&z);
  130428. /* If the first integer value is followed by a ',', read the second
  130429. ** integer value. */
  130430. if( z[0]==',' && z[1]!='\0' ){
  130431. z++;
  130432. nMin = fts3Getint(&z);
  130433. }
  130434. if( z[0]!='\0' || nMin<2 ){
  130435. rc = SQLITE_ERROR;
  130436. }else{
  130437. rc = SQLITE_OK;
  130438. if( !p->bHasStat ){
  130439. assert( p->bFts4==0 );
  130440. sqlite3Fts3CreateStatTable(&rc, p);
  130441. }
  130442. if( rc==SQLITE_OK ){
  130443. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  130444. }
  130445. sqlite3Fts3SegmentsClose(p);
  130446. }
  130447. return rc;
  130448. }
  130449. /*
  130450. ** Process statements of the form:
  130451. **
  130452. ** INSERT INTO table(table) VALUES('automerge=X');
  130453. **
  130454. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  130455. ** turn it on. The setting is persistent.
  130456. */
  130457. static int fts3DoAutoincrmerge(
  130458. Fts3Table *p, /* FTS3 table handle */
  130459. const char *zParam /* Nul-terminated string containing boolean */
  130460. ){
  130461. int rc = SQLITE_OK;
  130462. sqlite3_stmt *pStmt = 0;
  130463. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  130464. if( !p->bHasStat ){
  130465. assert( p->bFts4==0 );
  130466. sqlite3Fts3CreateStatTable(&rc, p);
  130467. if( rc ) return rc;
  130468. }
  130469. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  130470. if( rc ) return rc;
  130471. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  130472. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  130473. sqlite3_step(pStmt);
  130474. rc = sqlite3_reset(pStmt);
  130475. return rc;
  130476. }
  130477. /*
  130478. ** Return a 64-bit checksum for the FTS index entry specified by the
  130479. ** arguments to this function.
  130480. */
  130481. static u64 fts3ChecksumEntry(
  130482. const char *zTerm, /* Pointer to buffer containing term */
  130483. int nTerm, /* Size of zTerm in bytes */
  130484. int iLangid, /* Language id for current row */
  130485. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  130486. i64 iDocid, /* Docid for current row. */
  130487. int iCol, /* Column number */
  130488. int iPos /* Position */
  130489. ){
  130490. int i;
  130491. u64 ret = (u64)iDocid;
  130492. ret += (ret<<3) + iLangid;
  130493. ret += (ret<<3) + iIndex;
  130494. ret += (ret<<3) + iCol;
  130495. ret += (ret<<3) + iPos;
  130496. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  130497. return ret;
  130498. }
  130499. /*
  130500. ** Return a checksum of all entries in the FTS index that correspond to
  130501. ** language id iLangid. The checksum is calculated by XORing the checksums
  130502. ** of each individual entry (see fts3ChecksumEntry()) together.
  130503. **
  130504. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  130505. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  130506. ** return value is undefined in this case.
  130507. */
  130508. static u64 fts3ChecksumIndex(
  130509. Fts3Table *p, /* FTS3 table handle */
  130510. int iLangid, /* Language id to return cksum for */
  130511. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  130512. int *pRc /* OUT: Return code */
  130513. ){
  130514. Fts3SegFilter filter;
  130515. Fts3MultiSegReader csr;
  130516. int rc;
  130517. u64 cksum = 0;
  130518. assert( *pRc==SQLITE_OK );
  130519. memset(&filter, 0, sizeof(filter));
  130520. memset(&csr, 0, sizeof(csr));
  130521. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  130522. filter.flags |= FTS3_SEGMENT_SCAN;
  130523. rc = sqlite3Fts3SegReaderCursor(
  130524. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  130525. );
  130526. if( rc==SQLITE_OK ){
  130527. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  130528. }
  130529. if( rc==SQLITE_OK ){
  130530. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  130531. char *pCsr = csr.aDoclist;
  130532. char *pEnd = &pCsr[csr.nDoclist];
  130533. i64 iDocid = 0;
  130534. i64 iCol = 0;
  130535. i64 iPos = 0;
  130536. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  130537. while( pCsr<pEnd ){
  130538. i64 iVal = 0;
  130539. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  130540. if( pCsr<pEnd ){
  130541. if( iVal==0 || iVal==1 ){
  130542. iCol = 0;
  130543. iPos = 0;
  130544. if( iVal ){
  130545. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  130546. }else{
  130547. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  130548. iDocid += iVal;
  130549. }
  130550. }else{
  130551. iPos += (iVal - 2);
  130552. cksum = cksum ^ fts3ChecksumEntry(
  130553. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  130554. (int)iCol, (int)iPos
  130555. );
  130556. }
  130557. }
  130558. }
  130559. }
  130560. }
  130561. sqlite3Fts3SegReaderFinish(&csr);
  130562. *pRc = rc;
  130563. return cksum;
  130564. }
  130565. /*
  130566. ** Check if the contents of the FTS index match the current contents of the
  130567. ** content table. If no error occurs and the contents do match, set *pbOk
  130568. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  130569. ** to false before returning.
  130570. **
  130571. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  130572. ** code. The final value of *pbOk is undefined in this case.
  130573. */
  130574. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  130575. int rc = SQLITE_OK; /* Return code */
  130576. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  130577. u64 cksum2 = 0; /* Checksum based on %_content contents */
  130578. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  130579. /* This block calculates the checksum according to the FTS index. */
  130580. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  130581. if( rc==SQLITE_OK ){
  130582. int rc2;
  130583. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  130584. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  130585. int iLangid = sqlite3_column_int(pAllLangid, 0);
  130586. int i;
  130587. for(i=0; i<p->nIndex; i++){
  130588. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  130589. }
  130590. }
  130591. rc2 = sqlite3_reset(pAllLangid);
  130592. if( rc==SQLITE_OK ) rc = rc2;
  130593. }
  130594. /* This block calculates the checksum according to the %_content table */
  130595. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  130596. if( rc==SQLITE_OK ){
  130597. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  130598. sqlite3_stmt *pStmt = 0;
  130599. char *zSql;
  130600. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  130601. if( !zSql ){
  130602. rc = SQLITE_NOMEM;
  130603. }else{
  130604. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  130605. sqlite3_free(zSql);
  130606. }
  130607. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  130608. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  130609. int iLang = langidFromSelect(p, pStmt);
  130610. int iCol;
  130611. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  130612. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  130613. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  130614. sqlite3_tokenizer_cursor *pT = 0;
  130615. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  130616. while( rc==SQLITE_OK ){
  130617. char const *zToken; /* Buffer containing token */
  130618. int nToken = 0; /* Number of bytes in token */
  130619. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  130620. int iPos = 0; /* Position of token in zText */
  130621. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  130622. if( rc==SQLITE_OK ){
  130623. int i;
  130624. cksum2 = cksum2 ^ fts3ChecksumEntry(
  130625. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  130626. );
  130627. for(i=1; i<p->nIndex; i++){
  130628. if( p->aIndex[i].nPrefix<=nToken ){
  130629. cksum2 = cksum2 ^ fts3ChecksumEntry(
  130630. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  130631. );
  130632. }
  130633. }
  130634. }
  130635. }
  130636. if( pT ) pModule->xClose(pT);
  130637. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130638. }
  130639. }
  130640. sqlite3_finalize(pStmt);
  130641. }
  130642. *pbOk = (cksum1==cksum2);
  130643. return rc;
  130644. }
  130645. /*
  130646. ** Run the integrity-check. If no error occurs and the current contents of
  130647. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  130648. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  130649. **
  130650. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  130651. ** error code.
  130652. **
  130653. ** The integrity-check works as follows. For each token and indexed token
  130654. ** prefix in the document set, a 64-bit checksum is calculated (by code
  130655. ** in fts3ChecksumEntry()) based on the following:
  130656. **
  130657. ** + The index number (0 for the main index, 1 for the first prefix
  130658. ** index etc.),
  130659. ** + The token (or token prefix) text itself,
  130660. ** + The language-id of the row it appears in,
  130661. ** + The docid of the row it appears in,
  130662. ** + The column it appears in, and
  130663. ** + The tokens position within that column.
  130664. **
  130665. ** The checksums for all entries in the index are XORed together to create
  130666. ** a single checksum for the entire index.
  130667. **
  130668. ** The integrity-check code calculates the same checksum in two ways:
  130669. **
  130670. ** 1. By scanning the contents of the FTS index, and
  130671. ** 2. By scanning and tokenizing the content table.
  130672. **
  130673. ** If the two checksums are identical, the integrity-check is deemed to have
  130674. ** passed.
  130675. */
  130676. static int fts3DoIntegrityCheck(
  130677. Fts3Table *p /* FTS3 table handle */
  130678. ){
  130679. int rc;
  130680. int bOk = 0;
  130681. rc = fts3IntegrityCheck(p, &bOk);
  130682. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  130683. return rc;
  130684. }
  130685. /*
  130686. ** Handle a 'special' INSERT of the form:
  130687. **
  130688. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  130689. **
  130690. ** Argument pVal contains the result of <expr>. Currently the only
  130691. ** meaningful value to insert is the text 'optimize'.
  130692. */
  130693. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  130694. int rc; /* Return Code */
  130695. const char *zVal = (const char *)sqlite3_value_text(pVal);
  130696. int nVal = sqlite3_value_bytes(pVal);
  130697. if( !zVal ){
  130698. return SQLITE_NOMEM;
  130699. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  130700. rc = fts3DoOptimize(p, 0);
  130701. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  130702. rc = fts3DoRebuild(p);
  130703. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  130704. rc = fts3DoIntegrityCheck(p);
  130705. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  130706. rc = fts3DoIncrmerge(p, &zVal[6]);
  130707. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  130708. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  130709. #ifdef SQLITE_TEST
  130710. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  130711. p->nNodeSize = atoi(&zVal[9]);
  130712. rc = SQLITE_OK;
  130713. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  130714. p->nMaxPendingData = atoi(&zVal[11]);
  130715. rc = SQLITE_OK;
  130716. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  130717. p->bNoIncrDoclist = atoi(&zVal[21]);
  130718. rc = SQLITE_OK;
  130719. #endif
  130720. }else{
  130721. rc = SQLITE_ERROR;
  130722. }
  130723. return rc;
  130724. }
  130725. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  130726. /*
  130727. ** Delete all cached deferred doclists. Deferred doclists are cached
  130728. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  130729. */
  130730. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  130731. Fts3DeferredToken *pDef;
  130732. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  130733. fts3PendingListDelete(pDef->pList);
  130734. pDef->pList = 0;
  130735. }
  130736. }
  130737. /*
  130738. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  130739. ** this list using sqlite3Fts3DeferToken().
  130740. */
  130741. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  130742. Fts3DeferredToken *pDef;
  130743. Fts3DeferredToken *pNext;
  130744. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  130745. pNext = pDef->pNext;
  130746. fts3PendingListDelete(pDef->pList);
  130747. sqlite3_free(pDef);
  130748. }
  130749. pCsr->pDeferred = 0;
  130750. }
  130751. /*
  130752. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  130753. ** based on the row that pCsr currently points to.
  130754. **
  130755. ** A deferred-doclist is like any other doclist with position information
  130756. ** included, except that it only contains entries for a single row of the
  130757. ** table, not for all rows.
  130758. */
  130759. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  130760. int rc = SQLITE_OK; /* Return code */
  130761. if( pCsr->pDeferred ){
  130762. int i; /* Used to iterate through table columns */
  130763. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  130764. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  130765. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  130766. sqlite3_tokenizer *pT = p->pTokenizer;
  130767. sqlite3_tokenizer_module const *pModule = pT->pModule;
  130768. assert( pCsr->isRequireSeek==0 );
  130769. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  130770. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  130771. if( p->abNotindexed[i]==0 ){
  130772. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  130773. sqlite3_tokenizer_cursor *pTC = 0;
  130774. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  130775. while( rc==SQLITE_OK ){
  130776. char const *zToken; /* Buffer containing token */
  130777. int nToken = 0; /* Number of bytes in token */
  130778. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  130779. int iPos = 0; /* Position of token in zText */
  130780. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  130781. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  130782. Fts3PhraseToken *pPT = pDef->pToken;
  130783. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  130784. && (pPT->bFirst==0 || iPos==0)
  130785. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  130786. && (0==memcmp(zToken, pPT->z, pPT->n))
  130787. ){
  130788. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  130789. }
  130790. }
  130791. }
  130792. if( pTC ) pModule->xClose(pTC);
  130793. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130794. }
  130795. }
  130796. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  130797. if( pDef->pList ){
  130798. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  130799. }
  130800. }
  130801. }
  130802. return rc;
  130803. }
  130804. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  130805. Fts3DeferredToken *p,
  130806. char **ppData,
  130807. int *pnData
  130808. ){
  130809. char *pRet;
  130810. int nSkip;
  130811. sqlite3_int64 dummy;
  130812. *ppData = 0;
  130813. *pnData = 0;
  130814. if( p->pList==0 ){
  130815. return SQLITE_OK;
  130816. }
  130817. pRet = (char *)sqlite3_malloc(p->pList->nData);
  130818. if( !pRet ) return SQLITE_NOMEM;
  130819. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  130820. *pnData = p->pList->nData - nSkip;
  130821. *ppData = pRet;
  130822. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  130823. return SQLITE_OK;
  130824. }
  130825. /*
  130826. ** Add an entry for token pToken to the pCsr->pDeferred list.
  130827. */
  130828. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  130829. Fts3Cursor *pCsr, /* Fts3 table cursor */
  130830. Fts3PhraseToken *pToken, /* Token to defer */
  130831. int iCol /* Column that token must appear in (or -1) */
  130832. ){
  130833. Fts3DeferredToken *pDeferred;
  130834. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  130835. if( !pDeferred ){
  130836. return SQLITE_NOMEM;
  130837. }
  130838. memset(pDeferred, 0, sizeof(*pDeferred));
  130839. pDeferred->pToken = pToken;
  130840. pDeferred->pNext = pCsr->pDeferred;
  130841. pDeferred->iCol = iCol;
  130842. pCsr->pDeferred = pDeferred;
  130843. assert( pToken->pDeferred==0 );
  130844. pToken->pDeferred = pDeferred;
  130845. return SQLITE_OK;
  130846. }
  130847. #endif
  130848. /*
  130849. ** SQLite value pRowid contains the rowid of a row that may or may not be
  130850. ** present in the FTS3 table. If it is, delete it and adjust the contents
  130851. ** of subsiduary data structures accordingly.
  130852. */
  130853. static int fts3DeleteByRowid(
  130854. Fts3Table *p,
  130855. sqlite3_value *pRowid,
  130856. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  130857. u32 *aSzDel
  130858. ){
  130859. int rc = SQLITE_OK; /* Return code */
  130860. int bFound = 0; /* True if *pRowid really is in the table */
  130861. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  130862. if( bFound && rc==SQLITE_OK ){
  130863. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  130864. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  130865. if( rc==SQLITE_OK ){
  130866. if( isEmpty ){
  130867. /* Deleting this row means the whole table is empty. In this case
  130868. ** delete the contents of all three tables and throw away any
  130869. ** data in the pendingTerms hash table. */
  130870. rc = fts3DeleteAll(p, 1);
  130871. *pnChng = 0;
  130872. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  130873. }else{
  130874. *pnChng = *pnChng - 1;
  130875. if( p->zContentTbl==0 ){
  130876. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  130877. }
  130878. if( p->bHasDocsize ){
  130879. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  130880. }
  130881. }
  130882. }
  130883. }
  130884. return rc;
  130885. }
  130886. /*
  130887. ** This function does the work for the xUpdate method of FTS3 virtual
  130888. ** tables. The schema of the virtual table being:
  130889. **
  130890. ** CREATE TABLE <table name>(
  130891. ** <user columns>,
  130892. ** <table name> HIDDEN,
  130893. ** docid HIDDEN,
  130894. ** <langid> HIDDEN
  130895. ** );
  130896. **
  130897. **
  130898. */
  130899. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  130900. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  130901. int nArg, /* Size of argument array */
  130902. sqlite3_value **apVal, /* Array of arguments */
  130903. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  130904. ){
  130905. Fts3Table *p = (Fts3Table *)pVtab;
  130906. int rc = SQLITE_OK; /* Return Code */
  130907. int isRemove = 0; /* True for an UPDATE or DELETE */
  130908. u32 *aSzIns = 0; /* Sizes of inserted documents */
  130909. u32 *aSzDel = 0; /* Sizes of deleted documents */
  130910. int nChng = 0; /* Net change in number of documents */
  130911. int bInsertDone = 0;
  130912. assert( p->pSegments==0 );
  130913. assert(
  130914. nArg==1 /* DELETE operations */
  130915. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  130916. );
  130917. /* Check for a "special" INSERT operation. One of the form:
  130918. **
  130919. ** INSERT INTO xyz(xyz) VALUES('command');
  130920. */
  130921. if( nArg>1
  130922. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  130923. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  130924. ){
  130925. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  130926. goto update_out;
  130927. }
  130928. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  130929. rc = SQLITE_CONSTRAINT;
  130930. goto update_out;
  130931. }
  130932. /* Allocate space to hold the change in document sizes */
  130933. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  130934. if( aSzDel==0 ){
  130935. rc = SQLITE_NOMEM;
  130936. goto update_out;
  130937. }
  130938. aSzIns = &aSzDel[p->nColumn+1];
  130939. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  130940. rc = fts3Writelock(p);
  130941. if( rc!=SQLITE_OK ) goto update_out;
  130942. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  130943. ** value, then this operation requires constraint handling.
  130944. **
  130945. ** If the on-conflict mode is REPLACE, this means that the existing row
  130946. ** should be deleted from the database before inserting the new row. Or,
  130947. ** if the on-conflict mode is other than REPLACE, then this method must
  130948. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  130949. ** modify the database file.
  130950. */
  130951. if( nArg>1 && p->zContentTbl==0 ){
  130952. /* Find the value object that holds the new rowid value. */
  130953. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  130954. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  130955. pNewRowid = apVal[1];
  130956. }
  130957. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  130958. sqlite3_value_type(apVal[0])==SQLITE_NULL
  130959. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  130960. )){
  130961. /* The new rowid is not NULL (in this case the rowid will be
  130962. ** automatically assigned and there is no chance of a conflict), and
  130963. ** the statement is either an INSERT or an UPDATE that modifies the
  130964. ** rowid column. So if the conflict mode is REPLACE, then delete any
  130965. ** existing row with rowid=pNewRowid.
  130966. **
  130967. ** Or, if the conflict mode is not REPLACE, insert the new record into
  130968. ** the %_content table. If we hit the duplicate rowid constraint (or any
  130969. ** other error) while doing so, return immediately.
  130970. **
  130971. ** This branch may also run if pNewRowid contains a value that cannot
  130972. ** be losslessly converted to an integer. In this case, the eventual
  130973. ** call to fts3InsertData() (either just below or further on in this
  130974. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  130975. ** invoked, it will delete zero rows (since no row will have
  130976. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  130977. */
  130978. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  130979. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  130980. }else{
  130981. rc = fts3InsertData(p, apVal, pRowid);
  130982. bInsertDone = 1;
  130983. }
  130984. }
  130985. }
  130986. if( rc!=SQLITE_OK ){
  130987. goto update_out;
  130988. }
  130989. /* If this is a DELETE or UPDATE operation, remove the old record. */
  130990. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  130991. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  130992. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  130993. isRemove = 1;
  130994. }
  130995. /* If this is an INSERT or UPDATE operation, insert the new record. */
  130996. if( nArg>1 && rc==SQLITE_OK ){
  130997. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  130998. if( bInsertDone==0 ){
  130999. rc = fts3InsertData(p, apVal, pRowid);
  131000. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  131001. rc = FTS_CORRUPT_VTAB;
  131002. }
  131003. }
  131004. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  131005. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  131006. }
  131007. if( rc==SQLITE_OK ){
  131008. assert( p->iPrevDocid==*pRowid );
  131009. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  131010. }
  131011. if( p->bHasDocsize ){
  131012. fts3InsertDocsize(&rc, p, aSzIns);
  131013. }
  131014. nChng++;
  131015. }
  131016. if( p->bFts4 ){
  131017. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  131018. }
  131019. update_out:
  131020. sqlite3_free(aSzDel);
  131021. sqlite3Fts3SegmentsClose(p);
  131022. return rc;
  131023. }
  131024. /*
  131025. ** Flush any data in the pending-terms hash table to disk. If successful,
  131026. ** merge all segments in the database (including the new segment, if
  131027. ** there was any data to flush) into a single segment.
  131028. */
  131029. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  131030. int rc;
  131031. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  131032. if( rc==SQLITE_OK ){
  131033. rc = fts3DoOptimize(p, 1);
  131034. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  131035. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  131036. if( rc2!=SQLITE_OK ) rc = rc2;
  131037. }else{
  131038. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  131039. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  131040. }
  131041. }
  131042. sqlite3Fts3SegmentsClose(p);
  131043. return rc;
  131044. }
  131045. #endif
  131046. /************** End of fts3_write.c ******************************************/
  131047. /************** Begin file fts3_snippet.c ************************************/
  131048. /*
  131049. ** 2009 Oct 23
  131050. **
  131051. ** The author disclaims copyright to this source code. In place of
  131052. ** a legal notice, here is a blessing:
  131053. **
  131054. ** May you do good and not evil.
  131055. ** May you find forgiveness for yourself and forgive others.
  131056. ** May you share freely, never taking more than you give.
  131057. **
  131058. ******************************************************************************
  131059. */
  131060. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  131061. /* #include <string.h> */
  131062. /* #include <assert.h> */
  131063. /*
  131064. ** Characters that may appear in the second argument to matchinfo().
  131065. */
  131066. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  131067. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  131068. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  131069. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  131070. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  131071. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  131072. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  131073. /*
  131074. ** The default value for the second argument to matchinfo().
  131075. */
  131076. #define FTS3_MATCHINFO_DEFAULT "pcx"
  131077. /*
  131078. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  131079. ** Fts3Expr.aDoclist[]/nDoclist.
  131080. */
  131081. typedef struct LoadDoclistCtx LoadDoclistCtx;
  131082. struct LoadDoclistCtx {
  131083. Fts3Cursor *pCsr; /* FTS3 Cursor */
  131084. int nPhrase; /* Number of phrases seen so far */
  131085. int nToken; /* Number of tokens seen so far */
  131086. };
  131087. /*
  131088. ** The following types are used as part of the implementation of the
  131089. ** fts3BestSnippet() routine.
  131090. */
  131091. typedef struct SnippetIter SnippetIter;
  131092. typedef struct SnippetPhrase SnippetPhrase;
  131093. typedef struct SnippetFragment SnippetFragment;
  131094. struct SnippetIter {
  131095. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  131096. int iCol; /* Extract snippet from this column */
  131097. int nSnippet; /* Requested snippet length (in tokens) */
  131098. int nPhrase; /* Number of phrases in query */
  131099. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  131100. int iCurrent; /* First token of current snippet */
  131101. };
  131102. struct SnippetPhrase {
  131103. int nToken; /* Number of tokens in phrase */
  131104. char *pList; /* Pointer to start of phrase position list */
  131105. int iHead; /* Next value in position list */
  131106. char *pHead; /* Position list data following iHead */
  131107. int iTail; /* Next value in trailing position list */
  131108. char *pTail; /* Position list data following iTail */
  131109. };
  131110. struct SnippetFragment {
  131111. int iCol; /* Column snippet is extracted from */
  131112. int iPos; /* Index of first token in snippet */
  131113. u64 covered; /* Mask of query phrases covered */
  131114. u64 hlmask; /* Mask of snippet terms to highlight */
  131115. };
  131116. /*
  131117. ** This type is used as an fts3ExprIterate() context object while
  131118. ** accumulating the data returned by the matchinfo() function.
  131119. */
  131120. typedef struct MatchInfo MatchInfo;
  131121. struct MatchInfo {
  131122. Fts3Cursor *pCursor; /* FTS3 Cursor */
  131123. int nCol; /* Number of columns in table */
  131124. int nPhrase; /* Number of matchable phrases in query */
  131125. sqlite3_int64 nDoc; /* Number of docs in database */
  131126. u32 *aMatchinfo; /* Pre-allocated buffer */
  131127. };
  131128. /*
  131129. ** The snippet() and offsets() functions both return text values. An instance
  131130. ** of the following structure is used to accumulate those values while the
  131131. ** functions are running. See fts3StringAppend() for details.
  131132. */
  131133. typedef struct StrBuffer StrBuffer;
  131134. struct StrBuffer {
  131135. char *z; /* Pointer to buffer containing string */
  131136. int n; /* Length of z in bytes (excl. nul-term) */
  131137. int nAlloc; /* Allocated size of buffer z in bytes */
  131138. };
  131139. /*
  131140. ** This function is used to help iterate through a position-list. A position
  131141. ** list is a list of unique integers, sorted from smallest to largest. Each
  131142. ** element of the list is represented by an FTS3 varint that takes the value
  131143. ** of the difference between the current element and the previous one plus
  131144. ** two. For example, to store the position-list:
  131145. **
  131146. ** 4 9 113
  131147. **
  131148. ** the three varints:
  131149. **
  131150. ** 6 7 106
  131151. **
  131152. ** are encoded.
  131153. **
  131154. ** When this function is called, *pp points to the start of an element of
  131155. ** the list. *piPos contains the value of the previous entry in the list.
  131156. ** After it returns, *piPos contains the value of the next element of the
  131157. ** list and *pp is advanced to the following varint.
  131158. */
  131159. static void fts3GetDeltaPosition(char **pp, int *piPos){
  131160. int iVal;
  131161. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  131162. *piPos += (iVal-2);
  131163. }
  131164. /*
  131165. ** Helper function for fts3ExprIterate() (see below).
  131166. */
  131167. static int fts3ExprIterate2(
  131168. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  131169. int *piPhrase, /* Pointer to phrase counter */
  131170. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  131171. void *pCtx /* Second argument to pass to callback */
  131172. ){
  131173. int rc; /* Return code */
  131174. int eType = pExpr->eType; /* Type of expression node pExpr */
  131175. if( eType!=FTSQUERY_PHRASE ){
  131176. assert( pExpr->pLeft && pExpr->pRight );
  131177. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  131178. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  131179. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  131180. }
  131181. }else{
  131182. rc = x(pExpr, *piPhrase, pCtx);
  131183. (*piPhrase)++;
  131184. }
  131185. return rc;
  131186. }
  131187. /*
  131188. ** Iterate through all phrase nodes in an FTS3 query, except those that
  131189. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  131190. ** For each phrase node found, the supplied callback function is invoked.
  131191. **
  131192. ** If the callback function returns anything other than SQLITE_OK,
  131193. ** the iteration is abandoned and the error code returned immediately.
  131194. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  131195. ** all eligible phrase nodes.
  131196. */
  131197. static int fts3ExprIterate(
  131198. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  131199. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  131200. void *pCtx /* Second argument to pass to callback */
  131201. ){
  131202. int iPhrase = 0; /* Variable used as the phrase counter */
  131203. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  131204. }
  131205. /*
  131206. ** This is an fts3ExprIterate() callback used while loading the doclists
  131207. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  131208. ** fts3ExprLoadDoclists().
  131209. */
  131210. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131211. int rc = SQLITE_OK;
  131212. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131213. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  131214. UNUSED_PARAMETER(iPhrase);
  131215. p->nPhrase++;
  131216. p->nToken += pPhrase->nToken;
  131217. return rc;
  131218. }
  131219. /*
  131220. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  131221. ** pCsr.
  131222. **
  131223. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  131224. ** phrases in the expression (all phrases except those directly or
  131225. ** indirectly descended from the right-hand-side of a NOT operator). If
  131226. ** pnToken is not NULL, then it is set to the number of tokens in all
  131227. ** matchable phrases of the expression.
  131228. */
  131229. static int fts3ExprLoadDoclists(
  131230. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  131231. int *pnPhrase, /* OUT: Number of phrases in query */
  131232. int *pnToken /* OUT: Number of tokens in query */
  131233. ){
  131234. int rc; /* Return Code */
  131235. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  131236. sCtx.pCsr = pCsr;
  131237. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  131238. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  131239. if( pnToken ) *pnToken = sCtx.nToken;
  131240. return rc;
  131241. }
  131242. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131243. (*(int *)ctx)++;
  131244. UNUSED_PARAMETER(pExpr);
  131245. UNUSED_PARAMETER(iPhrase);
  131246. return SQLITE_OK;
  131247. }
  131248. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  131249. int nPhrase = 0;
  131250. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  131251. return nPhrase;
  131252. }
  131253. /*
  131254. ** Advance the position list iterator specified by the first two
  131255. ** arguments so that it points to the first element with a value greater
  131256. ** than or equal to parameter iNext.
  131257. */
  131258. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  131259. char *pIter = *ppIter;
  131260. if( pIter ){
  131261. int iIter = *piIter;
  131262. while( iIter<iNext ){
  131263. if( 0==(*pIter & 0xFE) ){
  131264. iIter = -1;
  131265. pIter = 0;
  131266. break;
  131267. }
  131268. fts3GetDeltaPosition(&pIter, &iIter);
  131269. }
  131270. *piIter = iIter;
  131271. *ppIter = pIter;
  131272. }
  131273. }
  131274. /*
  131275. ** Advance the snippet iterator to the next candidate snippet.
  131276. */
  131277. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  131278. int i; /* Loop counter */
  131279. if( pIter->iCurrent<0 ){
  131280. /* The SnippetIter object has just been initialized. The first snippet
  131281. ** candidate always starts at offset 0 (even if this candidate has a
  131282. ** score of 0.0).
  131283. */
  131284. pIter->iCurrent = 0;
  131285. /* Advance the 'head' iterator of each phrase to the first offset that
  131286. ** is greater than or equal to (iNext+nSnippet).
  131287. */
  131288. for(i=0; i<pIter->nPhrase; i++){
  131289. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131290. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  131291. }
  131292. }else{
  131293. int iStart;
  131294. int iEnd = 0x7FFFFFFF;
  131295. for(i=0; i<pIter->nPhrase; i++){
  131296. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131297. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  131298. iEnd = pPhrase->iHead;
  131299. }
  131300. }
  131301. if( iEnd==0x7FFFFFFF ){
  131302. return 1;
  131303. }
  131304. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  131305. for(i=0; i<pIter->nPhrase; i++){
  131306. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131307. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  131308. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  131309. }
  131310. }
  131311. return 0;
  131312. }
  131313. /*
  131314. ** Retrieve information about the current candidate snippet of snippet
  131315. ** iterator pIter.
  131316. */
  131317. static void fts3SnippetDetails(
  131318. SnippetIter *pIter, /* Snippet iterator */
  131319. u64 mCovered, /* Bitmask of phrases already covered */
  131320. int *piToken, /* OUT: First token of proposed snippet */
  131321. int *piScore, /* OUT: "Score" for this snippet */
  131322. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  131323. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  131324. ){
  131325. int iStart = pIter->iCurrent; /* First token of snippet */
  131326. int iScore = 0; /* Score of this snippet */
  131327. int i; /* Loop counter */
  131328. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  131329. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  131330. for(i=0; i<pIter->nPhrase; i++){
  131331. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131332. if( pPhrase->pTail ){
  131333. char *pCsr = pPhrase->pTail;
  131334. int iCsr = pPhrase->iTail;
  131335. while( iCsr<(iStart+pIter->nSnippet) ){
  131336. int j;
  131337. u64 mPhrase = (u64)1 << i;
  131338. u64 mPos = (u64)1 << (iCsr - iStart);
  131339. assert( iCsr>=iStart );
  131340. if( (mCover|mCovered)&mPhrase ){
  131341. iScore++;
  131342. }else{
  131343. iScore += 1000;
  131344. }
  131345. mCover |= mPhrase;
  131346. for(j=0; j<pPhrase->nToken; j++){
  131347. mHighlight |= (mPos>>j);
  131348. }
  131349. if( 0==(*pCsr & 0x0FE) ) break;
  131350. fts3GetDeltaPosition(&pCsr, &iCsr);
  131351. }
  131352. }
  131353. }
  131354. /* Set the output variables before returning. */
  131355. *piToken = iStart;
  131356. *piScore = iScore;
  131357. *pmCover = mCover;
  131358. *pmHighlight = mHighlight;
  131359. }
  131360. /*
  131361. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  131362. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  131363. */
  131364. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131365. SnippetIter *p = (SnippetIter *)ctx;
  131366. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  131367. char *pCsr;
  131368. int rc;
  131369. pPhrase->nToken = pExpr->pPhrase->nToken;
  131370. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  131371. assert( rc==SQLITE_OK || pCsr==0 );
  131372. if( pCsr ){
  131373. int iFirst = 0;
  131374. pPhrase->pList = pCsr;
  131375. fts3GetDeltaPosition(&pCsr, &iFirst);
  131376. assert( iFirst>=0 );
  131377. pPhrase->pHead = pCsr;
  131378. pPhrase->pTail = pCsr;
  131379. pPhrase->iHead = iFirst;
  131380. pPhrase->iTail = iFirst;
  131381. }else{
  131382. assert( rc!=SQLITE_OK || (
  131383. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  131384. ));
  131385. }
  131386. return rc;
  131387. }
  131388. /*
  131389. ** Select the fragment of text consisting of nFragment contiguous tokens
  131390. ** from column iCol that represent the "best" snippet. The best snippet
  131391. ** is the snippet with the highest score, where scores are calculated
  131392. ** by adding:
  131393. **
  131394. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  131395. **
  131396. ** (b) +1000 points for the first occurrence of each matchable phrase in
  131397. ** the snippet for which the corresponding mCovered bit is not set.
  131398. **
  131399. ** The selected snippet parameters are stored in structure *pFragment before
  131400. ** returning. The score of the selected snippet is stored in *piScore
  131401. ** before returning.
  131402. */
  131403. static int fts3BestSnippet(
  131404. int nSnippet, /* Desired snippet length */
  131405. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  131406. int iCol, /* Index of column to create snippet from */
  131407. u64 mCovered, /* Mask of phrases already covered */
  131408. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  131409. SnippetFragment *pFragment, /* OUT: Best snippet found */
  131410. int *piScore /* OUT: Score of snippet pFragment */
  131411. ){
  131412. int rc; /* Return Code */
  131413. int nList; /* Number of phrases in expression */
  131414. SnippetIter sIter; /* Iterates through snippet candidates */
  131415. int nByte; /* Number of bytes of space to allocate */
  131416. int iBestScore = -1; /* Best snippet score found so far */
  131417. int i; /* Loop counter */
  131418. memset(&sIter, 0, sizeof(sIter));
  131419. /* Iterate through the phrases in the expression to count them. The same
  131420. ** callback makes sure the doclists are loaded for each phrase.
  131421. */
  131422. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  131423. if( rc!=SQLITE_OK ){
  131424. return rc;
  131425. }
  131426. /* Now that it is known how many phrases there are, allocate and zero
  131427. ** the required space using malloc().
  131428. */
  131429. nByte = sizeof(SnippetPhrase) * nList;
  131430. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  131431. if( !sIter.aPhrase ){
  131432. return SQLITE_NOMEM;
  131433. }
  131434. memset(sIter.aPhrase, 0, nByte);
  131435. /* Initialize the contents of the SnippetIter object. Then iterate through
  131436. ** the set of phrases in the expression to populate the aPhrase[] array.
  131437. */
  131438. sIter.pCsr = pCsr;
  131439. sIter.iCol = iCol;
  131440. sIter.nSnippet = nSnippet;
  131441. sIter.nPhrase = nList;
  131442. sIter.iCurrent = -1;
  131443. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  131444. /* Set the *pmSeen output variable. */
  131445. for(i=0; i<nList; i++){
  131446. if( sIter.aPhrase[i].pHead ){
  131447. *pmSeen |= (u64)1 << i;
  131448. }
  131449. }
  131450. /* Loop through all candidate snippets. Store the best snippet in
  131451. ** *pFragment. Store its associated 'score' in iBestScore.
  131452. */
  131453. pFragment->iCol = iCol;
  131454. while( !fts3SnippetNextCandidate(&sIter) ){
  131455. int iPos;
  131456. int iScore;
  131457. u64 mCover;
  131458. u64 mHighlight;
  131459. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  131460. assert( iScore>=0 );
  131461. if( iScore>iBestScore ){
  131462. pFragment->iPos = iPos;
  131463. pFragment->hlmask = mHighlight;
  131464. pFragment->covered = mCover;
  131465. iBestScore = iScore;
  131466. }
  131467. }
  131468. sqlite3_free(sIter.aPhrase);
  131469. *piScore = iBestScore;
  131470. return SQLITE_OK;
  131471. }
  131472. /*
  131473. ** Append a string to the string-buffer passed as the first argument.
  131474. **
  131475. ** If nAppend is negative, then the length of the string zAppend is
  131476. ** determined using strlen().
  131477. */
  131478. static int fts3StringAppend(
  131479. StrBuffer *pStr, /* Buffer to append to */
  131480. const char *zAppend, /* Pointer to data to append to buffer */
  131481. int nAppend /* Size of zAppend in bytes (or -1) */
  131482. ){
  131483. if( nAppend<0 ){
  131484. nAppend = (int)strlen(zAppend);
  131485. }
  131486. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  131487. ** to grow the buffer until so that it is big enough to accomadate the
  131488. ** appended data.
  131489. */
  131490. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  131491. int nAlloc = pStr->nAlloc+nAppend+100;
  131492. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  131493. if( !zNew ){
  131494. return SQLITE_NOMEM;
  131495. }
  131496. pStr->z = zNew;
  131497. pStr->nAlloc = nAlloc;
  131498. }
  131499. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  131500. /* Append the data to the string buffer. */
  131501. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  131502. pStr->n += nAppend;
  131503. pStr->z[pStr->n] = '\0';
  131504. return SQLITE_OK;
  131505. }
  131506. /*
  131507. ** The fts3BestSnippet() function often selects snippets that end with a
  131508. ** query term. That is, the final term of the snippet is always a term
  131509. ** that requires highlighting. For example, if 'X' is a highlighted term
  131510. ** and '.' is a non-highlighted term, BestSnippet() may select:
  131511. **
  131512. ** ........X.....X
  131513. **
  131514. ** This function "shifts" the beginning of the snippet forward in the
  131515. ** document so that there are approximately the same number of
  131516. ** non-highlighted terms to the right of the final highlighted term as there
  131517. ** are to the left of the first highlighted term. For example, to this:
  131518. **
  131519. ** ....X.....X....
  131520. **
  131521. ** This is done as part of extracting the snippet text, not when selecting
  131522. ** the snippet. Snippet selection is done based on doclists only, so there
  131523. ** is no way for fts3BestSnippet() to know whether or not the document
  131524. ** actually contains terms that follow the final highlighted term.
  131525. */
  131526. static int fts3SnippetShift(
  131527. Fts3Table *pTab, /* FTS3 table snippet comes from */
  131528. int iLangid, /* Language id to use in tokenizing */
  131529. int nSnippet, /* Number of tokens desired for snippet */
  131530. const char *zDoc, /* Document text to extract snippet from */
  131531. int nDoc, /* Size of buffer zDoc in bytes */
  131532. int *piPos, /* IN/OUT: First token of snippet */
  131533. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  131534. ){
  131535. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  131536. if( hlmask ){
  131537. int nLeft; /* Tokens to the left of first highlight */
  131538. int nRight; /* Tokens to the right of last highlight */
  131539. int nDesired; /* Ideal number of tokens to shift forward */
  131540. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  131541. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  131542. nDesired = (nLeft-nRight)/2;
  131543. /* Ideally, the start of the snippet should be pushed forward in the
  131544. ** document nDesired tokens. This block checks if there are actually
  131545. ** nDesired tokens to the right of the snippet. If so, *piPos and
  131546. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  131547. ** right. Otherwise, the snippet is shifted by the number of tokens
  131548. ** available.
  131549. */
  131550. if( nDesired>0 ){
  131551. int nShift; /* Number of tokens to shift snippet by */
  131552. int iCurrent = 0; /* Token counter */
  131553. int rc; /* Return Code */
  131554. sqlite3_tokenizer_module *pMod;
  131555. sqlite3_tokenizer_cursor *pC;
  131556. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  131557. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  131558. ** or more tokens in zDoc/nDoc.
  131559. */
  131560. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  131561. if( rc!=SQLITE_OK ){
  131562. return rc;
  131563. }
  131564. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  131565. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  131566. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  131567. }
  131568. pMod->xClose(pC);
  131569. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  131570. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  131571. assert( nShift<=nDesired );
  131572. if( nShift>0 ){
  131573. *piPos += nShift;
  131574. *pHlmask = hlmask >> nShift;
  131575. }
  131576. }
  131577. }
  131578. return SQLITE_OK;
  131579. }
  131580. /*
  131581. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  131582. ** append it to string buffer pOut.
  131583. */
  131584. static int fts3SnippetText(
  131585. Fts3Cursor *pCsr, /* FTS3 Cursor */
  131586. SnippetFragment *pFragment, /* Snippet to extract */
  131587. int iFragment, /* Fragment number */
  131588. int isLast, /* True for final fragment in snippet */
  131589. int nSnippet, /* Number of tokens in extracted snippet */
  131590. const char *zOpen, /* String inserted before highlighted term */
  131591. const char *zClose, /* String inserted after highlighted term */
  131592. const char *zEllipsis, /* String inserted between snippets */
  131593. StrBuffer *pOut /* Write output here */
  131594. ){
  131595. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131596. int rc; /* Return code */
  131597. const char *zDoc; /* Document text to extract snippet from */
  131598. int nDoc; /* Size of zDoc in bytes */
  131599. int iCurrent = 0; /* Current token number of document */
  131600. int iEnd = 0; /* Byte offset of end of current token */
  131601. int isShiftDone = 0; /* True after snippet is shifted */
  131602. int iPos = pFragment->iPos; /* First token of snippet */
  131603. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  131604. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  131605. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  131606. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  131607. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  131608. if( zDoc==0 ){
  131609. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  131610. return SQLITE_NOMEM;
  131611. }
  131612. return SQLITE_OK;
  131613. }
  131614. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  131615. /* Open a token cursor on the document. */
  131616. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  131617. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  131618. if( rc!=SQLITE_OK ){
  131619. return rc;
  131620. }
  131621. while( rc==SQLITE_OK ){
  131622. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  131623. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  131624. int iBegin = 0; /* Offset in zDoc of start of token */
  131625. int iFin = 0; /* Offset in zDoc of end of token */
  131626. int isHighlight = 0; /* True for highlighted terms */
  131627. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  131628. ** in the FTS code the variable that the third argument to xNext points to
  131629. ** is initialized to zero before the first (*but not necessarily
  131630. ** subsequent*) call to xNext(). This is done for a particular application
  131631. ** that needs to know whether or not the tokenizer is being used for
  131632. ** snippet generation or for some other purpose.
  131633. **
  131634. ** Extreme care is required when writing code to depend on this
  131635. ** initialization. It is not a documented part of the tokenizer interface.
  131636. ** If a tokenizer is used directly by any code outside of FTS, this
  131637. ** convention might not be respected. */
  131638. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  131639. if( rc!=SQLITE_OK ){
  131640. if( rc==SQLITE_DONE ){
  131641. /* Special case - the last token of the snippet is also the last token
  131642. ** of the column. Append any punctuation that occurred between the end
  131643. ** of the previous token and the end of the document to the output.
  131644. ** Then break out of the loop. */
  131645. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  131646. }
  131647. break;
  131648. }
  131649. if( iCurrent<iPos ){ continue; }
  131650. if( !isShiftDone ){
  131651. int n = nDoc - iBegin;
  131652. rc = fts3SnippetShift(
  131653. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  131654. );
  131655. isShiftDone = 1;
  131656. /* Now that the shift has been done, check if the initial "..." are
  131657. ** required. They are required if (a) this is not the first fragment,
  131658. ** or (b) this fragment does not begin at position 0 of its column.
  131659. */
  131660. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  131661. rc = fts3StringAppend(pOut, zEllipsis, -1);
  131662. }
  131663. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  131664. }
  131665. if( iCurrent>=(iPos+nSnippet) ){
  131666. if( isLast ){
  131667. rc = fts3StringAppend(pOut, zEllipsis, -1);
  131668. }
  131669. break;
  131670. }
  131671. /* Set isHighlight to true if this term should be highlighted. */
  131672. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  131673. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  131674. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  131675. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  131676. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  131677. iEnd = iFin;
  131678. }
  131679. pMod->xClose(pC);
  131680. return rc;
  131681. }
  131682. /*
  131683. ** This function is used to count the entries in a column-list (a
  131684. ** delta-encoded list of term offsets within a single column of a single
  131685. ** row). When this function is called, *ppCollist should point to the
  131686. ** beginning of the first varint in the column-list (the varint that
  131687. ** contains the position of the first matching term in the column data).
  131688. ** Before returning, *ppCollist is set to point to the first byte after
  131689. ** the last varint in the column-list (either the 0x00 signifying the end
  131690. ** of the position-list, or the 0x01 that precedes the column number of
  131691. ** the next column in the position-list).
  131692. **
  131693. ** The number of elements in the column-list is returned.
  131694. */
  131695. static int fts3ColumnlistCount(char **ppCollist){
  131696. char *pEnd = *ppCollist;
  131697. char c = 0;
  131698. int nEntry = 0;
  131699. /* A column-list is terminated by either a 0x01 or 0x00. */
  131700. while( 0xFE & (*pEnd | c) ){
  131701. c = *pEnd++ & 0x80;
  131702. if( !c ) nEntry++;
  131703. }
  131704. *ppCollist = pEnd;
  131705. return nEntry;
  131706. }
  131707. /*
  131708. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  131709. ** for a single query.
  131710. **
  131711. ** fts3ExprIterate() callback to load the 'global' elements of a
  131712. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  131713. ** of the matchinfo array that are constant for all rows returned by the
  131714. ** current query.
  131715. **
  131716. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  131717. ** function populates Matchinfo.aMatchinfo[] as follows:
  131718. **
  131719. ** for(iCol=0; iCol<nCol; iCol++){
  131720. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  131721. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  131722. ** }
  131723. **
  131724. ** where X is the number of matches for phrase iPhrase is column iCol of all
  131725. ** rows of the table. Y is the number of rows for which column iCol contains
  131726. ** at least one instance of phrase iPhrase.
  131727. **
  131728. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  131729. ** Y values are set to nDoc, where nDoc is the number of documents in the
  131730. ** file system. This is done because the full-text index doclist is required
  131731. ** to calculate these values properly, and the full-text index doclist is
  131732. ** not available for deferred tokens.
  131733. */
  131734. static int fts3ExprGlobalHitsCb(
  131735. Fts3Expr *pExpr, /* Phrase expression node */
  131736. int iPhrase, /* Phrase number (numbered from zero) */
  131737. void *pCtx /* Pointer to MatchInfo structure */
  131738. ){
  131739. MatchInfo *p = (MatchInfo *)pCtx;
  131740. return sqlite3Fts3EvalPhraseStats(
  131741. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  131742. );
  131743. }
  131744. /*
  131745. ** fts3ExprIterate() callback used to collect the "local" part of the
  131746. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  131747. ** array that are different for each row returned by the query.
  131748. */
  131749. static int fts3ExprLocalHitsCb(
  131750. Fts3Expr *pExpr, /* Phrase expression node */
  131751. int iPhrase, /* Phrase number */
  131752. void *pCtx /* Pointer to MatchInfo structure */
  131753. ){
  131754. int rc = SQLITE_OK;
  131755. MatchInfo *p = (MatchInfo *)pCtx;
  131756. int iStart = iPhrase * p->nCol * 3;
  131757. int i;
  131758. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  131759. char *pCsr;
  131760. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  131761. if( pCsr ){
  131762. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  131763. }else{
  131764. p->aMatchinfo[iStart+i*3] = 0;
  131765. }
  131766. }
  131767. return rc;
  131768. }
  131769. static int fts3MatchinfoCheck(
  131770. Fts3Table *pTab,
  131771. char cArg,
  131772. char **pzErr
  131773. ){
  131774. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  131775. || (cArg==FTS3_MATCHINFO_NCOL)
  131776. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  131777. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  131778. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  131779. || (cArg==FTS3_MATCHINFO_LCS)
  131780. || (cArg==FTS3_MATCHINFO_HITS)
  131781. ){
  131782. return SQLITE_OK;
  131783. }
  131784. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  131785. return SQLITE_ERROR;
  131786. }
  131787. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  131788. int nVal; /* Number of integers output by cArg */
  131789. switch( cArg ){
  131790. case FTS3_MATCHINFO_NDOC:
  131791. case FTS3_MATCHINFO_NPHRASE:
  131792. case FTS3_MATCHINFO_NCOL:
  131793. nVal = 1;
  131794. break;
  131795. case FTS3_MATCHINFO_AVGLENGTH:
  131796. case FTS3_MATCHINFO_LENGTH:
  131797. case FTS3_MATCHINFO_LCS:
  131798. nVal = pInfo->nCol;
  131799. break;
  131800. default:
  131801. assert( cArg==FTS3_MATCHINFO_HITS );
  131802. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  131803. break;
  131804. }
  131805. return nVal;
  131806. }
  131807. static int fts3MatchinfoSelectDoctotal(
  131808. Fts3Table *pTab,
  131809. sqlite3_stmt **ppStmt,
  131810. sqlite3_int64 *pnDoc,
  131811. const char **paLen
  131812. ){
  131813. sqlite3_stmt *pStmt;
  131814. const char *a;
  131815. sqlite3_int64 nDoc;
  131816. if( !*ppStmt ){
  131817. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  131818. if( rc!=SQLITE_OK ) return rc;
  131819. }
  131820. pStmt = *ppStmt;
  131821. assert( sqlite3_data_count(pStmt)==1 );
  131822. a = sqlite3_column_blob(pStmt, 0);
  131823. a += sqlite3Fts3GetVarint(a, &nDoc);
  131824. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  131825. *pnDoc = (u32)nDoc;
  131826. if( paLen ) *paLen = a;
  131827. return SQLITE_OK;
  131828. }
  131829. /*
  131830. ** An instance of the following structure is used to store state while
  131831. ** iterating through a multi-column position-list corresponding to the
  131832. ** hits for a single phrase on a single row in order to calculate the
  131833. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  131834. */
  131835. typedef struct LcsIterator LcsIterator;
  131836. struct LcsIterator {
  131837. Fts3Expr *pExpr; /* Pointer to phrase expression */
  131838. int iPosOffset; /* Tokens count up to end of this phrase */
  131839. char *pRead; /* Cursor used to iterate through aDoclist */
  131840. int iPos; /* Current position */
  131841. };
  131842. /*
  131843. ** If LcsIterator.iCol is set to the following value, the iterator has
  131844. ** finished iterating through all offsets for all columns.
  131845. */
  131846. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  131847. static int fts3MatchinfoLcsCb(
  131848. Fts3Expr *pExpr, /* Phrase expression node */
  131849. int iPhrase, /* Phrase number (numbered from zero) */
  131850. void *pCtx /* Pointer to MatchInfo structure */
  131851. ){
  131852. LcsIterator *aIter = (LcsIterator *)pCtx;
  131853. aIter[iPhrase].pExpr = pExpr;
  131854. return SQLITE_OK;
  131855. }
  131856. /*
  131857. ** Advance the iterator passed as an argument to the next position. Return
  131858. ** 1 if the iterator is at EOF or if it now points to the start of the
  131859. ** position list for the next column.
  131860. */
  131861. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  131862. char *pRead = pIter->pRead;
  131863. sqlite3_int64 iRead;
  131864. int rc = 0;
  131865. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  131866. if( iRead==0 || iRead==1 ){
  131867. pRead = 0;
  131868. rc = 1;
  131869. }else{
  131870. pIter->iPos += (int)(iRead-2);
  131871. }
  131872. pIter->pRead = pRead;
  131873. return rc;
  131874. }
  131875. /*
  131876. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  131877. **
  131878. ** If the call is successful, the longest-common-substring lengths for each
  131879. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  131880. ** array before returning. SQLITE_OK is returned in this case.
  131881. **
  131882. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  131883. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  131884. ** undefined.
  131885. */
  131886. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  131887. LcsIterator *aIter;
  131888. int i;
  131889. int iCol;
  131890. int nToken = 0;
  131891. /* Allocate and populate the array of LcsIterator objects. The array
  131892. ** contains one element for each matchable phrase in the query.
  131893. **/
  131894. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  131895. if( !aIter ) return SQLITE_NOMEM;
  131896. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  131897. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  131898. for(i=0; i<pInfo->nPhrase; i++){
  131899. LcsIterator *pIter = &aIter[i];
  131900. nToken -= pIter->pExpr->pPhrase->nToken;
  131901. pIter->iPosOffset = nToken;
  131902. }
  131903. for(iCol=0; iCol<pInfo->nCol; iCol++){
  131904. int nLcs = 0; /* LCS value for this column */
  131905. int nLive = 0; /* Number of iterators in aIter not at EOF */
  131906. for(i=0; i<pInfo->nPhrase; i++){
  131907. int rc;
  131908. LcsIterator *pIt = &aIter[i];
  131909. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  131910. if( rc!=SQLITE_OK ) return rc;
  131911. if( pIt->pRead ){
  131912. pIt->iPos = pIt->iPosOffset;
  131913. fts3LcsIteratorAdvance(&aIter[i]);
  131914. nLive++;
  131915. }
  131916. }
  131917. while( nLive>0 ){
  131918. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  131919. int nThisLcs = 0; /* LCS for the current iterator positions */
  131920. for(i=0; i<pInfo->nPhrase; i++){
  131921. LcsIterator *pIter = &aIter[i];
  131922. if( pIter->pRead==0 ){
  131923. /* This iterator is already at EOF for this column. */
  131924. nThisLcs = 0;
  131925. }else{
  131926. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  131927. pAdv = pIter;
  131928. }
  131929. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  131930. nThisLcs++;
  131931. }else{
  131932. nThisLcs = 1;
  131933. }
  131934. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  131935. }
  131936. }
  131937. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  131938. }
  131939. pInfo->aMatchinfo[iCol] = nLcs;
  131940. }
  131941. sqlite3_free(aIter);
  131942. return SQLITE_OK;
  131943. }
  131944. /*
  131945. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  131946. ** be returned by the matchinfo() function. Argument zArg contains the
  131947. ** format string passed as the second argument to matchinfo (or the
  131948. ** default value "pcx" if no second argument was specified). The format
  131949. ** string has already been validated and the pInfo->aMatchinfo[] array
  131950. ** is guaranteed to be large enough for the output.
  131951. **
  131952. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  131953. ** If it is false, then assume that those fields that do not change between
  131954. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  131955. ** have already been populated.
  131956. **
  131957. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  131958. ** occurs. If a value other than SQLITE_OK is returned, the state the
  131959. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  131960. */
  131961. static int fts3MatchinfoValues(
  131962. Fts3Cursor *pCsr, /* FTS3 cursor object */
  131963. int bGlobal, /* True to grab the global stats */
  131964. MatchInfo *pInfo, /* Matchinfo context object */
  131965. const char *zArg /* Matchinfo format string */
  131966. ){
  131967. int rc = SQLITE_OK;
  131968. int i;
  131969. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131970. sqlite3_stmt *pSelect = 0;
  131971. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  131972. switch( zArg[i] ){
  131973. case FTS3_MATCHINFO_NPHRASE:
  131974. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  131975. break;
  131976. case FTS3_MATCHINFO_NCOL:
  131977. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  131978. break;
  131979. case FTS3_MATCHINFO_NDOC:
  131980. if( bGlobal ){
  131981. sqlite3_int64 nDoc = 0;
  131982. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  131983. pInfo->aMatchinfo[0] = (u32)nDoc;
  131984. }
  131985. break;
  131986. case FTS3_MATCHINFO_AVGLENGTH:
  131987. if( bGlobal ){
  131988. sqlite3_int64 nDoc; /* Number of rows in table */
  131989. const char *a; /* Aggregate column length array */
  131990. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  131991. if( rc==SQLITE_OK ){
  131992. int iCol;
  131993. for(iCol=0; iCol<pInfo->nCol; iCol++){
  131994. u32 iVal;
  131995. sqlite3_int64 nToken;
  131996. a += sqlite3Fts3GetVarint(a, &nToken);
  131997. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  131998. pInfo->aMatchinfo[iCol] = iVal;
  131999. }
  132000. }
  132001. }
  132002. break;
  132003. case FTS3_MATCHINFO_LENGTH: {
  132004. sqlite3_stmt *pSelectDocsize = 0;
  132005. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  132006. if( rc==SQLITE_OK ){
  132007. int iCol;
  132008. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  132009. for(iCol=0; iCol<pInfo->nCol; iCol++){
  132010. sqlite3_int64 nToken;
  132011. a += sqlite3Fts3GetVarint(a, &nToken);
  132012. pInfo->aMatchinfo[iCol] = (u32)nToken;
  132013. }
  132014. }
  132015. sqlite3_reset(pSelectDocsize);
  132016. break;
  132017. }
  132018. case FTS3_MATCHINFO_LCS:
  132019. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  132020. if( rc==SQLITE_OK ){
  132021. rc = fts3MatchinfoLcs(pCsr, pInfo);
  132022. }
  132023. break;
  132024. default: {
  132025. Fts3Expr *pExpr;
  132026. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  132027. pExpr = pCsr->pExpr;
  132028. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  132029. if( rc!=SQLITE_OK ) break;
  132030. if( bGlobal ){
  132031. if( pCsr->pDeferred ){
  132032. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  132033. if( rc!=SQLITE_OK ) break;
  132034. }
  132035. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  132036. if( rc!=SQLITE_OK ) break;
  132037. }
  132038. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  132039. break;
  132040. }
  132041. }
  132042. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  132043. }
  132044. sqlite3_reset(pSelect);
  132045. return rc;
  132046. }
  132047. /*
  132048. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  132049. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  132050. */
  132051. static int fts3GetMatchinfo(
  132052. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  132053. const char *zArg /* Second argument to matchinfo() function */
  132054. ){
  132055. MatchInfo sInfo;
  132056. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132057. int rc = SQLITE_OK;
  132058. int bGlobal = 0; /* Collect 'global' stats as well as local */
  132059. memset(&sInfo, 0, sizeof(MatchInfo));
  132060. sInfo.pCursor = pCsr;
  132061. sInfo.nCol = pTab->nColumn;
  132062. /* If there is cached matchinfo() data, but the format string for the
  132063. ** cache does not match the format string for this request, discard
  132064. ** the cached data. */
  132065. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  132066. assert( pCsr->aMatchinfo );
  132067. sqlite3_free(pCsr->aMatchinfo);
  132068. pCsr->zMatchinfo = 0;
  132069. pCsr->aMatchinfo = 0;
  132070. }
  132071. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  132072. ** matchinfo function has been called for this query. In this case
  132073. ** allocate the array used to accumulate the matchinfo data and
  132074. ** initialize those elements that are constant for every row.
  132075. */
  132076. if( pCsr->aMatchinfo==0 ){
  132077. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  132078. int nArg; /* Bytes in zArg */
  132079. int i; /* Used to iterate through zArg */
  132080. /* Determine the number of phrases in the query */
  132081. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  132082. sInfo.nPhrase = pCsr->nPhrase;
  132083. /* Determine the number of integers in the buffer returned by this call. */
  132084. for(i=0; zArg[i]; i++){
  132085. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  132086. }
  132087. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  132088. nArg = (int)strlen(zArg);
  132089. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  132090. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  132091. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  132092. pCsr->nMatchinfo = nMatchinfo;
  132093. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  132094. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  132095. pCsr->isMatchinfoNeeded = 1;
  132096. bGlobal = 1;
  132097. }
  132098. sInfo.aMatchinfo = pCsr->aMatchinfo;
  132099. sInfo.nPhrase = pCsr->nPhrase;
  132100. if( pCsr->isMatchinfoNeeded ){
  132101. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  132102. pCsr->isMatchinfoNeeded = 0;
  132103. }
  132104. return rc;
  132105. }
  132106. /*
  132107. ** Implementation of snippet() function.
  132108. */
  132109. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  132110. sqlite3_context *pCtx, /* SQLite function call context */
  132111. Fts3Cursor *pCsr, /* Cursor object */
  132112. const char *zStart, /* Snippet start text - "<b>" */
  132113. const char *zEnd, /* Snippet end text - "</b>" */
  132114. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  132115. int iCol, /* Extract snippet from this column */
  132116. int nToken /* Approximate number of tokens in snippet */
  132117. ){
  132118. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132119. int rc = SQLITE_OK;
  132120. int i;
  132121. StrBuffer res = {0, 0, 0};
  132122. /* The returned text includes up to four fragments of text extracted from
  132123. ** the data in the current row. The first iteration of the for(...) loop
  132124. ** below attempts to locate a single fragment of text nToken tokens in
  132125. ** size that contains at least one instance of all phrases in the query
  132126. ** expression that appear in the current row. If such a fragment of text
  132127. ** cannot be found, the second iteration of the loop attempts to locate
  132128. ** a pair of fragments, and so on.
  132129. */
  132130. int nSnippet = 0; /* Number of fragments in this snippet */
  132131. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  132132. int nFToken = -1; /* Number of tokens in each fragment */
  132133. if( !pCsr->pExpr ){
  132134. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  132135. return;
  132136. }
  132137. for(nSnippet=1; 1; nSnippet++){
  132138. int iSnip; /* Loop counter 0..nSnippet-1 */
  132139. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  132140. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  132141. if( nToken>=0 ){
  132142. nFToken = (nToken+nSnippet-1) / nSnippet;
  132143. }else{
  132144. nFToken = -1 * nToken;
  132145. }
  132146. for(iSnip=0; iSnip<nSnippet; iSnip++){
  132147. int iBestScore = -1; /* Best score of columns checked so far */
  132148. int iRead; /* Used to iterate through columns */
  132149. SnippetFragment *pFragment = &aSnippet[iSnip];
  132150. memset(pFragment, 0, sizeof(*pFragment));
  132151. /* Loop through all columns of the table being considered for snippets.
  132152. ** If the iCol argument to this function was negative, this means all
  132153. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  132154. */
  132155. for(iRead=0; iRead<pTab->nColumn; iRead++){
  132156. SnippetFragment sF = {0, 0, 0, 0};
  132157. int iS;
  132158. if( iCol>=0 && iRead!=iCol ) continue;
  132159. /* Find the best snippet of nFToken tokens in column iRead. */
  132160. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  132161. if( rc!=SQLITE_OK ){
  132162. goto snippet_out;
  132163. }
  132164. if( iS>iBestScore ){
  132165. *pFragment = sF;
  132166. iBestScore = iS;
  132167. }
  132168. }
  132169. mCovered |= pFragment->covered;
  132170. }
  132171. /* If all query phrases seen by fts3BestSnippet() are present in at least
  132172. ** one of the nSnippet snippet fragments, break out of the loop.
  132173. */
  132174. assert( (mCovered&mSeen)==mCovered );
  132175. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  132176. }
  132177. assert( nFToken>0 );
  132178. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  132179. rc = fts3SnippetText(pCsr, &aSnippet[i],
  132180. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  132181. );
  132182. }
  132183. snippet_out:
  132184. sqlite3Fts3SegmentsClose(pTab);
  132185. if( rc!=SQLITE_OK ){
  132186. sqlite3_result_error_code(pCtx, rc);
  132187. sqlite3_free(res.z);
  132188. }else{
  132189. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  132190. }
  132191. }
  132192. typedef struct TermOffset TermOffset;
  132193. typedef struct TermOffsetCtx TermOffsetCtx;
  132194. struct TermOffset {
  132195. char *pList; /* Position-list */
  132196. int iPos; /* Position just read from pList */
  132197. int iOff; /* Offset of this term from read positions */
  132198. };
  132199. struct TermOffsetCtx {
  132200. Fts3Cursor *pCsr;
  132201. int iCol; /* Column of table to populate aTerm for */
  132202. int iTerm;
  132203. sqlite3_int64 iDocid;
  132204. TermOffset *aTerm;
  132205. };
  132206. /*
  132207. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  132208. */
  132209. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  132210. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  132211. int nTerm; /* Number of tokens in phrase */
  132212. int iTerm; /* For looping through nTerm phrase terms */
  132213. char *pList; /* Pointer to position list for phrase */
  132214. int iPos = 0; /* First position in position-list */
  132215. int rc;
  132216. UNUSED_PARAMETER(iPhrase);
  132217. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  132218. nTerm = pExpr->pPhrase->nToken;
  132219. if( pList ){
  132220. fts3GetDeltaPosition(&pList, &iPos);
  132221. assert( iPos>=0 );
  132222. }
  132223. for(iTerm=0; iTerm<nTerm; iTerm++){
  132224. TermOffset *pT = &p->aTerm[p->iTerm++];
  132225. pT->iOff = nTerm-iTerm-1;
  132226. pT->pList = pList;
  132227. pT->iPos = iPos;
  132228. }
  132229. return rc;
  132230. }
  132231. /*
  132232. ** Implementation of offsets() function.
  132233. */
  132234. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  132235. sqlite3_context *pCtx, /* SQLite function call context */
  132236. Fts3Cursor *pCsr /* Cursor object */
  132237. ){
  132238. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132239. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  132240. int rc; /* Return Code */
  132241. int nToken; /* Number of tokens in query */
  132242. int iCol; /* Column currently being processed */
  132243. StrBuffer res = {0, 0, 0}; /* Result string */
  132244. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  132245. if( !pCsr->pExpr ){
  132246. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  132247. return;
  132248. }
  132249. memset(&sCtx, 0, sizeof(sCtx));
  132250. assert( pCsr->isRequireSeek==0 );
  132251. /* Count the number of terms in the query */
  132252. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  132253. if( rc!=SQLITE_OK ) goto offsets_out;
  132254. /* Allocate the array of TermOffset iterators. */
  132255. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  132256. if( 0==sCtx.aTerm ){
  132257. rc = SQLITE_NOMEM;
  132258. goto offsets_out;
  132259. }
  132260. sCtx.iDocid = pCsr->iPrevId;
  132261. sCtx.pCsr = pCsr;
  132262. /* Loop through the table columns, appending offset information to
  132263. ** string-buffer res for each column.
  132264. */
  132265. for(iCol=0; iCol<pTab->nColumn; iCol++){
  132266. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  132267. const char *ZDUMMY; /* Dummy argument used with xNext() */
  132268. int NDUMMY = 0; /* Dummy argument used with xNext() */
  132269. int iStart = 0;
  132270. int iEnd = 0;
  132271. int iCurrent = 0;
  132272. const char *zDoc;
  132273. int nDoc;
  132274. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  132275. ** no way that this operation can fail, so the return code from
  132276. ** fts3ExprIterate() can be discarded.
  132277. */
  132278. sCtx.iCol = iCol;
  132279. sCtx.iTerm = 0;
  132280. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  132281. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  132282. ** in column iCol, jump immediately to the next iteration of the loop.
  132283. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  132284. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  132285. ** to the caller.
  132286. */
  132287. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  132288. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  132289. if( zDoc==0 ){
  132290. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  132291. continue;
  132292. }
  132293. rc = SQLITE_NOMEM;
  132294. goto offsets_out;
  132295. }
  132296. /* Initialize a tokenizer iterator to iterate through column iCol. */
  132297. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  132298. zDoc, nDoc, &pC
  132299. );
  132300. if( rc!=SQLITE_OK ) goto offsets_out;
  132301. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  132302. while( rc==SQLITE_OK ){
  132303. int i; /* Used to loop through terms */
  132304. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  132305. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  132306. for(i=0; i<nToken; i++){
  132307. TermOffset *pT = &sCtx.aTerm[i];
  132308. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  132309. iMinPos = pT->iPos-pT->iOff;
  132310. pTerm = pT;
  132311. }
  132312. }
  132313. if( !pTerm ){
  132314. /* All offsets for this column have been gathered. */
  132315. rc = SQLITE_DONE;
  132316. }else{
  132317. assert( iCurrent<=iMinPos );
  132318. if( 0==(0xFE&*pTerm->pList) ){
  132319. pTerm->pList = 0;
  132320. }else{
  132321. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  132322. }
  132323. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  132324. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  132325. }
  132326. if( rc==SQLITE_OK ){
  132327. char aBuffer[64];
  132328. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  132329. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  132330. );
  132331. rc = fts3StringAppend(&res, aBuffer, -1);
  132332. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  132333. rc = FTS_CORRUPT_VTAB;
  132334. }
  132335. }
  132336. }
  132337. if( rc==SQLITE_DONE ){
  132338. rc = SQLITE_OK;
  132339. }
  132340. pMod->xClose(pC);
  132341. if( rc!=SQLITE_OK ) goto offsets_out;
  132342. }
  132343. offsets_out:
  132344. sqlite3_free(sCtx.aTerm);
  132345. assert( rc!=SQLITE_DONE );
  132346. sqlite3Fts3SegmentsClose(pTab);
  132347. if( rc!=SQLITE_OK ){
  132348. sqlite3_result_error_code(pCtx, rc);
  132349. sqlite3_free(res.z);
  132350. }else{
  132351. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  132352. }
  132353. return;
  132354. }
  132355. /*
  132356. ** Implementation of matchinfo() function.
  132357. */
  132358. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  132359. sqlite3_context *pContext, /* Function call context */
  132360. Fts3Cursor *pCsr, /* FTS3 table cursor */
  132361. const char *zArg /* Second arg to matchinfo() function */
  132362. ){
  132363. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132364. int rc;
  132365. int i;
  132366. const char *zFormat;
  132367. if( zArg ){
  132368. for(i=0; zArg[i]; i++){
  132369. char *zErr = 0;
  132370. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  132371. sqlite3_result_error(pContext, zErr, -1);
  132372. sqlite3_free(zErr);
  132373. return;
  132374. }
  132375. }
  132376. zFormat = zArg;
  132377. }else{
  132378. zFormat = FTS3_MATCHINFO_DEFAULT;
  132379. }
  132380. if( !pCsr->pExpr ){
  132381. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  132382. return;
  132383. }
  132384. /* Retrieve matchinfo() data. */
  132385. rc = fts3GetMatchinfo(pCsr, zFormat);
  132386. sqlite3Fts3SegmentsClose(pTab);
  132387. if( rc!=SQLITE_OK ){
  132388. sqlite3_result_error_code(pContext, rc);
  132389. }else{
  132390. int n = pCsr->nMatchinfo * sizeof(u32);
  132391. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  132392. }
  132393. }
  132394. #endif
  132395. /************** End of fts3_snippet.c ****************************************/
  132396. /************** Begin file fts3_unicode.c ************************************/
  132397. /*
  132398. ** 2012 May 24
  132399. **
  132400. ** The author disclaims copyright to this source code. In place of
  132401. ** a legal notice, here is a blessing:
  132402. **
  132403. ** May you do good and not evil.
  132404. ** May you find forgiveness for yourself and forgive others.
  132405. ** May you share freely, never taking more than you give.
  132406. **
  132407. ******************************************************************************
  132408. **
  132409. ** Implementation of the "unicode" full-text-search tokenizer.
  132410. */
  132411. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  132412. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132413. /* #include <assert.h> */
  132414. /* #include <stdlib.h> */
  132415. /* #include <stdio.h> */
  132416. /* #include <string.h> */
  132417. /*
  132418. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  132419. ** from the sqlite3 source file utf.c. If this file is compiled as part
  132420. ** of the amalgamation, they are not required.
  132421. */
  132422. #ifndef SQLITE_AMALGAMATION
  132423. static const unsigned char sqlite3Utf8Trans1[] = {
  132424. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132425. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  132426. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  132427. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  132428. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132429. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  132430. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132431. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  132432. };
  132433. #define READ_UTF8(zIn, zTerm, c) \
  132434. c = *(zIn++); \
  132435. if( c>=0xc0 ){ \
  132436. c = sqlite3Utf8Trans1[c-0xc0]; \
  132437. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  132438. c = (c<<6) + (0x3f & *(zIn++)); \
  132439. } \
  132440. if( c<0x80 \
  132441. || (c&0xFFFFF800)==0xD800 \
  132442. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  132443. }
  132444. #define WRITE_UTF8(zOut, c) { \
  132445. if( c<0x00080 ){ \
  132446. *zOut++ = (u8)(c&0xFF); \
  132447. } \
  132448. else if( c<0x00800 ){ \
  132449. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  132450. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132451. } \
  132452. else if( c<0x10000 ){ \
  132453. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  132454. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  132455. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132456. }else{ \
  132457. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  132458. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  132459. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  132460. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132461. } \
  132462. }
  132463. #endif /* ifndef SQLITE_AMALGAMATION */
  132464. typedef struct unicode_tokenizer unicode_tokenizer;
  132465. typedef struct unicode_cursor unicode_cursor;
  132466. struct unicode_tokenizer {
  132467. sqlite3_tokenizer base;
  132468. int bRemoveDiacritic;
  132469. int nException;
  132470. int *aiException;
  132471. };
  132472. struct unicode_cursor {
  132473. sqlite3_tokenizer_cursor base;
  132474. const unsigned char *aInput; /* Input text being tokenized */
  132475. int nInput; /* Size of aInput[] in bytes */
  132476. int iOff; /* Current offset within aInput[] */
  132477. int iToken; /* Index of next token to be returned */
  132478. char *zToken; /* storage for current token */
  132479. int nAlloc; /* space allocated at zToken */
  132480. };
  132481. /*
  132482. ** Destroy a tokenizer allocated by unicodeCreate().
  132483. */
  132484. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  132485. if( pTokenizer ){
  132486. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  132487. sqlite3_free(p->aiException);
  132488. sqlite3_free(p);
  132489. }
  132490. return SQLITE_OK;
  132491. }
  132492. /*
  132493. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  132494. ** statement has specified that the tokenizer for this table shall consider
  132495. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  132496. ** token characters (if bAlnum==1).
  132497. **
  132498. ** For each codepoint in the zIn/nIn string, this function checks if the
  132499. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  132500. ** If so, no action is taken. Otherwise, the codepoint is added to the
  132501. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  132502. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  132503. ** codepoints in the aiException[] array.
  132504. **
  132505. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  132506. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  132507. ** It is not possible to change the behavior of the tokenizer with respect
  132508. ** to these codepoints.
  132509. */
  132510. static int unicodeAddExceptions(
  132511. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  132512. int bAlnum, /* Replace Isalnum() return value with this */
  132513. const char *zIn, /* Array of characters to make exceptions */
  132514. int nIn /* Length of z in bytes */
  132515. ){
  132516. const unsigned char *z = (const unsigned char *)zIn;
  132517. const unsigned char *zTerm = &z[nIn];
  132518. int iCode;
  132519. int nEntry = 0;
  132520. assert( bAlnum==0 || bAlnum==1 );
  132521. while( z<zTerm ){
  132522. READ_UTF8(z, zTerm, iCode);
  132523. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  132524. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  132525. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  132526. ){
  132527. nEntry++;
  132528. }
  132529. }
  132530. if( nEntry ){
  132531. int *aNew; /* New aiException[] array */
  132532. int nNew; /* Number of valid entries in array aNew[] */
  132533. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  132534. if( aNew==0 ) return SQLITE_NOMEM;
  132535. nNew = p->nException;
  132536. z = (const unsigned char *)zIn;
  132537. while( z<zTerm ){
  132538. READ_UTF8(z, zTerm, iCode);
  132539. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  132540. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  132541. ){
  132542. int i, j;
  132543. for(i=0; i<nNew && aNew[i]<iCode; i++);
  132544. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  132545. aNew[i] = iCode;
  132546. nNew++;
  132547. }
  132548. }
  132549. p->aiException = aNew;
  132550. p->nException = nNew;
  132551. }
  132552. return SQLITE_OK;
  132553. }
  132554. /*
  132555. ** Return true if the p->aiException[] array contains the value iCode.
  132556. */
  132557. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  132558. if( p->nException>0 ){
  132559. int *a = p->aiException;
  132560. int iLo = 0;
  132561. int iHi = p->nException-1;
  132562. while( iHi>=iLo ){
  132563. int iTest = (iHi + iLo) / 2;
  132564. if( iCode==a[iTest] ){
  132565. return 1;
  132566. }else if( iCode>a[iTest] ){
  132567. iLo = iTest+1;
  132568. }else{
  132569. iHi = iTest-1;
  132570. }
  132571. }
  132572. }
  132573. return 0;
  132574. }
  132575. /*
  132576. ** Return true if, for the purposes of tokenization, codepoint iCode is
  132577. ** considered a token character (not a separator).
  132578. */
  132579. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  132580. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  132581. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  132582. }
  132583. /*
  132584. ** Create a new tokenizer instance.
  132585. */
  132586. static int unicodeCreate(
  132587. int nArg, /* Size of array argv[] */
  132588. const char * const *azArg, /* Tokenizer creation arguments */
  132589. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  132590. ){
  132591. unicode_tokenizer *pNew; /* New tokenizer object */
  132592. int i;
  132593. int rc = SQLITE_OK;
  132594. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  132595. if( pNew==NULL ) return SQLITE_NOMEM;
  132596. memset(pNew, 0, sizeof(unicode_tokenizer));
  132597. pNew->bRemoveDiacritic = 1;
  132598. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  132599. const char *z = azArg[i];
  132600. int n = strlen(z);
  132601. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  132602. pNew->bRemoveDiacritic = 1;
  132603. }
  132604. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  132605. pNew->bRemoveDiacritic = 0;
  132606. }
  132607. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  132608. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  132609. }
  132610. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  132611. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  132612. }
  132613. else{
  132614. /* Unrecognized argument */
  132615. rc = SQLITE_ERROR;
  132616. }
  132617. }
  132618. if( rc!=SQLITE_OK ){
  132619. unicodeDestroy((sqlite3_tokenizer *)pNew);
  132620. pNew = 0;
  132621. }
  132622. *pp = (sqlite3_tokenizer *)pNew;
  132623. return rc;
  132624. }
  132625. /*
  132626. ** Prepare to begin tokenizing a particular string. The input
  132627. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  132628. ** used to incrementally tokenize this string is returned in
  132629. ** *ppCursor.
  132630. */
  132631. static int unicodeOpen(
  132632. sqlite3_tokenizer *p, /* The tokenizer */
  132633. const char *aInput, /* Input string */
  132634. int nInput, /* Size of string aInput in bytes */
  132635. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  132636. ){
  132637. unicode_cursor *pCsr;
  132638. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  132639. if( pCsr==0 ){
  132640. return SQLITE_NOMEM;
  132641. }
  132642. memset(pCsr, 0, sizeof(unicode_cursor));
  132643. pCsr->aInput = (const unsigned char *)aInput;
  132644. if( aInput==0 ){
  132645. pCsr->nInput = 0;
  132646. }else if( nInput<0 ){
  132647. pCsr->nInput = (int)strlen(aInput);
  132648. }else{
  132649. pCsr->nInput = nInput;
  132650. }
  132651. *pp = &pCsr->base;
  132652. UNUSED_PARAMETER(p);
  132653. return SQLITE_OK;
  132654. }
  132655. /*
  132656. ** Close a tokenization cursor previously opened by a call to
  132657. ** simpleOpen() above.
  132658. */
  132659. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  132660. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  132661. sqlite3_free(pCsr->zToken);
  132662. sqlite3_free(pCsr);
  132663. return SQLITE_OK;
  132664. }
  132665. /*
  132666. ** Extract the next token from a tokenization cursor. The cursor must
  132667. ** have been opened by a prior call to simpleOpen().
  132668. */
  132669. static int unicodeNext(
  132670. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  132671. const char **paToken, /* OUT: Token text */
  132672. int *pnToken, /* OUT: Number of bytes at *paToken */
  132673. int *piStart, /* OUT: Starting offset of token */
  132674. int *piEnd, /* OUT: Ending offset of token */
  132675. int *piPos /* OUT: Position integer of token */
  132676. ){
  132677. unicode_cursor *pCsr = (unicode_cursor *)pC;
  132678. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  132679. int iCode;
  132680. char *zOut;
  132681. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  132682. const unsigned char *zStart = z;
  132683. const unsigned char *zEnd;
  132684. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  132685. /* Scan past any delimiter characters before the start of the next token.
  132686. ** Return SQLITE_DONE early if this takes us all the way to the end of
  132687. ** the input. */
  132688. while( z<zTerm ){
  132689. READ_UTF8(z, zTerm, iCode);
  132690. if( unicodeIsAlnum(p, iCode) ) break;
  132691. zStart = z;
  132692. }
  132693. if( zStart>=zTerm ) return SQLITE_DONE;
  132694. zOut = pCsr->zToken;
  132695. do {
  132696. int iOut;
  132697. /* Grow the output buffer if required. */
  132698. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  132699. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  132700. if( !zNew ) return SQLITE_NOMEM;
  132701. zOut = &zNew[zOut - pCsr->zToken];
  132702. pCsr->zToken = zNew;
  132703. pCsr->nAlloc += 64;
  132704. }
  132705. /* Write the folded case of the last character read to the output */
  132706. zEnd = z;
  132707. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  132708. if( iOut ){
  132709. WRITE_UTF8(zOut, iOut);
  132710. }
  132711. /* If the cursor is not at EOF, read the next character */
  132712. if( z>=zTerm ) break;
  132713. READ_UTF8(z, zTerm, iCode);
  132714. }while( unicodeIsAlnum(p, iCode)
  132715. || sqlite3FtsUnicodeIsdiacritic(iCode)
  132716. );
  132717. /* Set the output variables and return. */
  132718. pCsr->iOff = (z - pCsr->aInput);
  132719. *paToken = pCsr->zToken;
  132720. *pnToken = zOut - pCsr->zToken;
  132721. *piStart = (zStart - pCsr->aInput);
  132722. *piEnd = (zEnd - pCsr->aInput);
  132723. *piPos = pCsr->iToken++;
  132724. return SQLITE_OK;
  132725. }
  132726. /*
  132727. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  132728. ** structure for the unicode tokenizer.
  132729. */
  132730. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  132731. static const sqlite3_tokenizer_module module = {
  132732. 0,
  132733. unicodeCreate,
  132734. unicodeDestroy,
  132735. unicodeOpen,
  132736. unicodeClose,
  132737. unicodeNext,
  132738. 0,
  132739. };
  132740. *ppModule = &module;
  132741. }
  132742. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  132743. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  132744. /************** End of fts3_unicode.c ****************************************/
  132745. /************** Begin file fts3_unicode2.c ***********************************/
  132746. /*
  132747. ** 2012 May 25
  132748. **
  132749. ** The author disclaims copyright to this source code. In place of
  132750. ** a legal notice, here is a blessing:
  132751. **
  132752. ** May you do good and not evil.
  132753. ** May you find forgiveness for yourself and forgive others.
  132754. ** May you share freely, never taking more than you give.
  132755. **
  132756. ******************************************************************************
  132757. */
  132758. /*
  132759. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  132760. */
  132761. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  132762. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  132763. /* #include <assert.h> */
  132764. /*
  132765. ** Return true if the argument corresponds to a unicode codepoint
  132766. ** classified as either a letter or a number. Otherwise false.
  132767. **
  132768. ** The results are undefined if the value passed to this function
  132769. ** is less than zero.
  132770. */
  132771. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  132772. /* Each unsigned integer in the following array corresponds to a contiguous
  132773. ** range of unicode codepoints that are not either letters or numbers (i.e.
  132774. ** codepoints for which this function should return 0).
  132775. **
  132776. ** The most significant 22 bits in each 32-bit value contain the first
  132777. ** codepoint in the range. The least significant 10 bits are used to store
  132778. ** the size of the range (always at least 1). In other words, the value
  132779. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  132780. ** C. It is not possible to represent a range larger than 1023 codepoints
  132781. ** using this format.
  132782. */
  132783. const static unsigned int aEntry[] = {
  132784. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  132785. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  132786. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  132787. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  132788. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  132789. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  132790. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  132791. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  132792. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  132793. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  132794. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  132795. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  132796. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  132797. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  132798. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  132799. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  132800. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  132801. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  132802. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  132803. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  132804. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  132805. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  132806. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  132807. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  132808. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  132809. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  132810. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  132811. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  132812. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  132813. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  132814. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  132815. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  132816. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  132817. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  132818. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  132819. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  132820. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  132821. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  132822. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  132823. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  132824. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  132825. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  132826. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  132827. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  132828. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  132829. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  132830. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  132831. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  132832. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  132833. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  132834. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  132835. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  132836. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  132837. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  132838. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  132839. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  132840. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  132841. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  132842. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  132843. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  132844. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  132845. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  132846. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  132847. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  132848. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  132849. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  132850. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  132851. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  132852. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  132853. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  132854. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  132855. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  132856. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  132857. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  132858. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  132859. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  132860. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  132861. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  132862. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  132863. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  132864. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  132865. 0x380400F0,
  132866. };
  132867. static const unsigned int aAscii[4] = {
  132868. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  132869. };
  132870. if( c<128 ){
  132871. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  132872. }else if( c<(1<<22) ){
  132873. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  132874. int iRes;
  132875. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  132876. int iLo = 0;
  132877. while( iHi>=iLo ){
  132878. int iTest = (iHi + iLo) / 2;
  132879. if( key >= aEntry[iTest] ){
  132880. iRes = iTest;
  132881. iLo = iTest+1;
  132882. }else{
  132883. iHi = iTest-1;
  132884. }
  132885. }
  132886. assert( aEntry[0]<key );
  132887. assert( key>=aEntry[iRes] );
  132888. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  132889. }
  132890. return 1;
  132891. }
  132892. /*
  132893. ** If the argument is a codepoint corresponding to a lowercase letter
  132894. ** in the ASCII range with a diacritic added, return the codepoint
  132895. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  132896. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  132897. ** E"). The resuls of passing a codepoint that corresponds to an
  132898. ** uppercase letter are undefined.
  132899. */
  132900. static int remove_diacritic(int c){
  132901. unsigned short aDia[] = {
  132902. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  132903. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  132904. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  132905. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  132906. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  132907. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  132908. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  132909. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  132910. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  132911. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  132912. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  132913. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  132914. 62924, 63050, 63082, 63274, 63390,
  132915. };
  132916. char aChar[] = {
  132917. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  132918. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  132919. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  132920. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  132921. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  132922. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  132923. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  132924. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  132925. 'e', 'i', 'o', 'u', 'y',
  132926. };
  132927. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  132928. int iRes = 0;
  132929. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  132930. int iLo = 0;
  132931. while( iHi>=iLo ){
  132932. int iTest = (iHi + iLo) / 2;
  132933. if( key >= aDia[iTest] ){
  132934. iRes = iTest;
  132935. iLo = iTest+1;
  132936. }else{
  132937. iHi = iTest-1;
  132938. }
  132939. }
  132940. assert( key>=aDia[iRes] );
  132941. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  132942. };
  132943. /*
  132944. ** Return true if the argument interpreted as a unicode codepoint
  132945. ** is a diacritical modifier character.
  132946. */
  132947. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  132948. unsigned int mask0 = 0x08029FDF;
  132949. unsigned int mask1 = 0x000361F8;
  132950. if( c<768 || c>817 ) return 0;
  132951. return (c < 768+32) ?
  132952. (mask0 & (1 << (c-768))) :
  132953. (mask1 & (1 << (c-768-32)));
  132954. }
  132955. /*
  132956. ** Interpret the argument as a unicode codepoint. If the codepoint
  132957. ** is an upper case character that has a lower case equivalent,
  132958. ** return the codepoint corresponding to the lower case version.
  132959. ** Otherwise, return a copy of the argument.
  132960. **
  132961. ** The results are undefined if the value passed to this function
  132962. ** is less than zero.
  132963. */
  132964. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  132965. /* Each entry in the following array defines a rule for folding a range
  132966. ** of codepoints to lower case. The rule applies to a range of nRange
  132967. ** codepoints starting at codepoint iCode.
  132968. **
  132969. ** If the least significant bit in flags is clear, then the rule applies
  132970. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  132971. ** need to be folded). Or, if it is set, then the rule only applies to
  132972. ** every second codepoint in the range, starting with codepoint C.
  132973. **
  132974. ** The 7 most significant bits in flags are an index into the aiOff[]
  132975. ** array. If a specific codepoint C does require folding, then its lower
  132976. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  132977. **
  132978. ** The contents of this array are generated by parsing the CaseFolding.txt
  132979. ** file distributed as part of the "Unicode Character Database". See
  132980. ** http://www.unicode.org for details.
  132981. */
  132982. static const struct TableEntry {
  132983. unsigned short iCode;
  132984. unsigned char flags;
  132985. unsigned char nRange;
  132986. } aEntry[] = {
  132987. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  132988. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  132989. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  132990. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  132991. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  132992. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  132993. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  132994. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  132995. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  132996. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  132997. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  132998. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  132999. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  133000. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  133001. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  133002. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  133003. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  133004. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  133005. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  133006. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  133007. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  133008. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  133009. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  133010. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  133011. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  133012. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  133013. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  133014. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  133015. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  133016. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  133017. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  133018. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  133019. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  133020. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  133021. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  133022. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  133023. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  133024. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  133025. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  133026. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  133027. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  133028. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  133029. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  133030. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  133031. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  133032. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  133033. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  133034. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  133035. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  133036. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  133037. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  133038. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  133039. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  133040. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  133041. {65313, 14, 26},
  133042. };
  133043. static const unsigned short aiOff[] = {
  133044. 1, 2, 8, 15, 16, 26, 28, 32,
  133045. 37, 38, 40, 48, 63, 64, 69, 71,
  133046. 79, 80, 116, 202, 203, 205, 206, 207,
  133047. 209, 210, 211, 213, 214, 217, 218, 219,
  133048. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  133049. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  133050. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  133051. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  133052. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  133053. 65514, 65521, 65527, 65528, 65529,
  133054. };
  133055. int ret = c;
  133056. assert( c>=0 );
  133057. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  133058. if( c<128 ){
  133059. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  133060. }else if( c<65536 ){
  133061. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  133062. int iLo = 0;
  133063. int iRes = -1;
  133064. while( iHi>=iLo ){
  133065. int iTest = (iHi + iLo) / 2;
  133066. int cmp = (c - aEntry[iTest].iCode);
  133067. if( cmp>=0 ){
  133068. iRes = iTest;
  133069. iLo = iTest+1;
  133070. }else{
  133071. iHi = iTest-1;
  133072. }
  133073. }
  133074. assert( iRes<0 || c>=aEntry[iRes].iCode );
  133075. if( iRes>=0 ){
  133076. const struct TableEntry *p = &aEntry[iRes];
  133077. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  133078. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  133079. assert( ret>0 );
  133080. }
  133081. }
  133082. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  133083. }
  133084. else if( c>=66560 && c<66600 ){
  133085. ret = c + 40;
  133086. }
  133087. return ret;
  133088. }
  133089. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  133090. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  133091. /************** End of fts3_unicode2.c ***************************************/
  133092. /************** Begin file rtree.c *******************************************/
  133093. /*
  133094. ** 2001 September 15
  133095. **
  133096. ** The author disclaims copyright to this source code. In place of
  133097. ** a legal notice, here is a blessing:
  133098. **
  133099. ** May you do good and not evil.
  133100. ** May you find forgiveness for yourself and forgive others.
  133101. ** May you share freely, never taking more than you give.
  133102. **
  133103. *************************************************************************
  133104. ** This file contains code for implementations of the r-tree and r*-tree
  133105. ** algorithms packaged as an SQLite virtual table module.
  133106. */
  133107. /*
  133108. ** Database Format of R-Tree Tables
  133109. ** --------------------------------
  133110. **
  133111. ** The data structure for a single virtual r-tree table is stored in three
  133112. ** native SQLite tables declared as follows. In each case, the '%' character
  133113. ** in the table name is replaced with the user-supplied name of the r-tree
  133114. ** table.
  133115. **
  133116. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  133117. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  133118. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  133119. **
  133120. ** The data for each node of the r-tree structure is stored in the %_node
  133121. ** table. For each node that is not the root node of the r-tree, there is
  133122. ** an entry in the %_parent table associating the node with its parent.
  133123. ** And for each row of data in the table, there is an entry in the %_rowid
  133124. ** table that maps from the entries rowid to the id of the node that it
  133125. ** is stored on.
  133126. **
  133127. ** The root node of an r-tree always exists, even if the r-tree table is
  133128. ** empty. The nodeno of the root node is always 1. All other nodes in the
  133129. ** table must be the same size as the root node. The content of each node
  133130. ** is formatted as follows:
  133131. **
  133132. ** 1. If the node is the root node (node 1), then the first 2 bytes
  133133. ** of the node contain the tree depth as a big-endian integer.
  133134. ** For non-root nodes, the first 2 bytes are left unused.
  133135. **
  133136. ** 2. The next 2 bytes contain the number of entries currently
  133137. ** stored in the node.
  133138. **
  133139. ** 3. The remainder of the node contains the node entries. Each entry
  133140. ** consists of a single 8-byte integer followed by an even number
  133141. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  133142. ** of a record. For internal nodes it is the node number of a
  133143. ** child page.
  133144. */
  133145. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  133146. /*
  133147. ** This file contains an implementation of a couple of different variants
  133148. ** of the r-tree algorithm. See the README file for further details. The
  133149. ** same data-structure is used for all, but the algorithms for insert and
  133150. ** delete operations vary. The variants used are selected at compile time
  133151. ** by defining the following symbols:
  133152. */
  133153. /* Either, both or none of the following may be set to activate
  133154. ** r*tree variant algorithms.
  133155. */
  133156. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  133157. #define VARIANT_RSTARTREE_REINSERT 1
  133158. /*
  133159. ** Exactly one of the following must be set to 1.
  133160. */
  133161. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  133162. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  133163. #define VARIANT_RSTARTREE_SPLIT 1
  133164. #define VARIANT_GUTTMAN_SPLIT \
  133165. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  133166. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  133167. #define PickNext QuadraticPickNext
  133168. #define PickSeeds QuadraticPickSeeds
  133169. #define AssignCells splitNodeGuttman
  133170. #endif
  133171. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  133172. #define PickNext LinearPickNext
  133173. #define PickSeeds LinearPickSeeds
  133174. #define AssignCells splitNodeGuttman
  133175. #endif
  133176. #if VARIANT_RSTARTREE_SPLIT
  133177. #define AssignCells splitNodeStartree
  133178. #endif
  133179. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  133180. # define NDEBUG 1
  133181. #endif
  133182. #ifndef SQLITE_CORE
  133183. SQLITE_EXTENSION_INIT1
  133184. #else
  133185. #endif
  133186. /* #include <string.h> */
  133187. /* #include <assert.h> */
  133188. #ifndef SQLITE_AMALGAMATION
  133189. #include "sqlite3rtree.h"
  133190. typedef sqlite3_int64 i64;
  133191. typedef unsigned char u8;
  133192. typedef unsigned int u32;
  133193. #endif
  133194. /* The following macro is used to suppress compiler warnings.
  133195. */
  133196. #ifndef UNUSED_PARAMETER
  133197. # define UNUSED_PARAMETER(x) (void)(x)
  133198. #endif
  133199. typedef struct Rtree Rtree;
  133200. typedef struct RtreeCursor RtreeCursor;
  133201. typedef struct RtreeNode RtreeNode;
  133202. typedef struct RtreeCell RtreeCell;
  133203. typedef struct RtreeConstraint RtreeConstraint;
  133204. typedef struct RtreeMatchArg RtreeMatchArg;
  133205. typedef struct RtreeGeomCallback RtreeGeomCallback;
  133206. typedef union RtreeCoord RtreeCoord;
  133207. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  133208. #define RTREE_MAX_DIMENSIONS 5
  133209. /* Size of hash table Rtree.aHash. This hash table is not expected to
  133210. ** ever contain very many entries, so a fixed number of buckets is
  133211. ** used.
  133212. */
  133213. #define HASHSIZE 128
  133214. /*
  133215. ** An rtree virtual-table object.
  133216. */
  133217. struct Rtree {
  133218. sqlite3_vtab base;
  133219. sqlite3 *db; /* Host database connection */
  133220. int iNodeSize; /* Size in bytes of each node in the node table */
  133221. int nDim; /* Number of dimensions */
  133222. int nBytesPerCell; /* Bytes consumed per cell */
  133223. int iDepth; /* Current depth of the r-tree structure */
  133224. char *zDb; /* Name of database containing r-tree table */
  133225. char *zName; /* Name of r-tree table */
  133226. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  133227. int nBusy; /* Current number of users of this structure */
  133228. /* List of nodes removed during a CondenseTree operation. List is
  133229. ** linked together via the pointer normally used for hash chains -
  133230. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  133231. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  133232. */
  133233. RtreeNode *pDeleted;
  133234. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  133235. /* Statements to read/write/delete a record from xxx_node */
  133236. sqlite3_stmt *pReadNode;
  133237. sqlite3_stmt *pWriteNode;
  133238. sqlite3_stmt *pDeleteNode;
  133239. /* Statements to read/write/delete a record from xxx_rowid */
  133240. sqlite3_stmt *pReadRowid;
  133241. sqlite3_stmt *pWriteRowid;
  133242. sqlite3_stmt *pDeleteRowid;
  133243. /* Statements to read/write/delete a record from xxx_parent */
  133244. sqlite3_stmt *pReadParent;
  133245. sqlite3_stmt *pWriteParent;
  133246. sqlite3_stmt *pDeleteParent;
  133247. int eCoordType;
  133248. };
  133249. /* Possible values for eCoordType: */
  133250. #define RTREE_COORD_REAL32 0
  133251. #define RTREE_COORD_INT32 1
  133252. /*
  133253. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  133254. ** only deal with integer coordinates. No floating point operations
  133255. ** will be done.
  133256. */
  133257. #ifdef SQLITE_RTREE_INT_ONLY
  133258. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  133259. typedef int RtreeValue; /* Low accuracy coordinate */
  133260. #else
  133261. typedef double RtreeDValue; /* High accuracy coordinate */
  133262. typedef float RtreeValue; /* Low accuracy coordinate */
  133263. #endif
  133264. /*
  133265. ** The minimum number of cells allowed for a node is a third of the
  133266. ** maximum. In Gutman's notation:
  133267. **
  133268. ** m = M/3
  133269. **
  133270. ** If an R*-tree "Reinsert" operation is required, the same number of
  133271. ** cells are removed from the overfull node and reinserted into the tree.
  133272. */
  133273. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  133274. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  133275. #define RTREE_MAXCELLS 51
  133276. /*
  133277. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  133278. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  133279. ** Therefore all non-root nodes must contain at least 3 entries. Since
  133280. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  133281. ** 40 or less.
  133282. */
  133283. #define RTREE_MAX_DEPTH 40
  133284. /*
  133285. ** An rtree cursor object.
  133286. */
  133287. struct RtreeCursor {
  133288. sqlite3_vtab_cursor base;
  133289. RtreeNode *pNode; /* Node cursor is currently pointing at */
  133290. int iCell; /* Index of current cell in pNode */
  133291. int iStrategy; /* Copy of idxNum search parameter */
  133292. int nConstraint; /* Number of entries in aConstraint */
  133293. RtreeConstraint *aConstraint; /* Search constraints. */
  133294. };
  133295. union RtreeCoord {
  133296. RtreeValue f;
  133297. int i;
  133298. };
  133299. /*
  133300. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  133301. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  133302. ** variable pRtree points to the Rtree structure associated with the
  133303. ** RtreeCoord.
  133304. */
  133305. #ifdef SQLITE_RTREE_INT_ONLY
  133306. # define DCOORD(coord) ((RtreeDValue)coord.i)
  133307. #else
  133308. # define DCOORD(coord) ( \
  133309. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  133310. ((double)coord.f) : \
  133311. ((double)coord.i) \
  133312. )
  133313. #endif
  133314. /*
  133315. ** A search constraint.
  133316. */
  133317. struct RtreeConstraint {
  133318. int iCoord; /* Index of constrained coordinate */
  133319. int op; /* Constraining operation */
  133320. RtreeDValue rValue; /* Constraint value. */
  133321. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  133322. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  133323. };
  133324. /* Possible values for RtreeConstraint.op */
  133325. #define RTREE_EQ 0x41
  133326. #define RTREE_LE 0x42
  133327. #define RTREE_LT 0x43
  133328. #define RTREE_GE 0x44
  133329. #define RTREE_GT 0x45
  133330. #define RTREE_MATCH 0x46
  133331. /*
  133332. ** An rtree structure node.
  133333. */
  133334. struct RtreeNode {
  133335. RtreeNode *pParent; /* Parent node */
  133336. i64 iNode;
  133337. int nRef;
  133338. int isDirty;
  133339. u8 *zData;
  133340. RtreeNode *pNext; /* Next node in this hash chain */
  133341. };
  133342. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  133343. /*
  133344. ** Structure to store a deserialized rtree record.
  133345. */
  133346. struct RtreeCell {
  133347. i64 iRowid;
  133348. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  133349. };
  133350. /*
  133351. ** Value for the first field of every RtreeMatchArg object. The MATCH
  133352. ** operator tests that the first field of a blob operand matches this
  133353. ** value to avoid operating on invalid blobs (which could cause a segfault).
  133354. */
  133355. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  133356. /*
  133357. ** An instance of this structure must be supplied as a blob argument to
  133358. ** the right-hand-side of an SQL MATCH operator used to constrain an
  133359. ** r-tree query.
  133360. */
  133361. struct RtreeMatchArg {
  133362. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  133363. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  133364. void *pContext;
  133365. int nParam;
  133366. RtreeDValue aParam[1];
  133367. };
  133368. /*
  133369. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  133370. ** a single instance of the following structure is allocated. It is used
  133371. ** as the context for the user-function created by by s_r_g_c(). The object
  133372. ** is eventually deleted by the destructor mechanism provided by
  133373. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  133374. ** the geometry callback function).
  133375. */
  133376. struct RtreeGeomCallback {
  133377. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  133378. void *pContext;
  133379. };
  133380. #ifndef MAX
  133381. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  133382. #endif
  133383. #ifndef MIN
  133384. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  133385. #endif
  133386. /*
  133387. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  133388. ** 64 bit integer. The deserialized value is returned.
  133389. */
  133390. static int readInt16(u8 *p){
  133391. return (p[0]<<8) + p[1];
  133392. }
  133393. static void readCoord(u8 *p, RtreeCoord *pCoord){
  133394. u32 i = (
  133395. (((u32)p[0]) << 24) +
  133396. (((u32)p[1]) << 16) +
  133397. (((u32)p[2]) << 8) +
  133398. (((u32)p[3]) << 0)
  133399. );
  133400. *(u32 *)pCoord = i;
  133401. }
  133402. static i64 readInt64(u8 *p){
  133403. return (
  133404. (((i64)p[0]) << 56) +
  133405. (((i64)p[1]) << 48) +
  133406. (((i64)p[2]) << 40) +
  133407. (((i64)p[3]) << 32) +
  133408. (((i64)p[4]) << 24) +
  133409. (((i64)p[5]) << 16) +
  133410. (((i64)p[6]) << 8) +
  133411. (((i64)p[7]) << 0)
  133412. );
  133413. }
  133414. /*
  133415. ** Functions to serialize a 16 bit integer, 32 bit real number and
  133416. ** 64 bit integer. The value returned is the number of bytes written
  133417. ** to the argument buffer (always 2, 4 and 8 respectively).
  133418. */
  133419. static int writeInt16(u8 *p, int i){
  133420. p[0] = (i>> 8)&0xFF;
  133421. p[1] = (i>> 0)&0xFF;
  133422. return 2;
  133423. }
  133424. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  133425. u32 i;
  133426. assert( sizeof(RtreeCoord)==4 );
  133427. assert( sizeof(u32)==4 );
  133428. i = *(u32 *)pCoord;
  133429. p[0] = (i>>24)&0xFF;
  133430. p[1] = (i>>16)&0xFF;
  133431. p[2] = (i>> 8)&0xFF;
  133432. p[3] = (i>> 0)&0xFF;
  133433. return 4;
  133434. }
  133435. static int writeInt64(u8 *p, i64 i){
  133436. p[0] = (i>>56)&0xFF;
  133437. p[1] = (i>>48)&0xFF;
  133438. p[2] = (i>>40)&0xFF;
  133439. p[3] = (i>>32)&0xFF;
  133440. p[4] = (i>>24)&0xFF;
  133441. p[5] = (i>>16)&0xFF;
  133442. p[6] = (i>> 8)&0xFF;
  133443. p[7] = (i>> 0)&0xFF;
  133444. return 8;
  133445. }
  133446. /*
  133447. ** Increment the reference count of node p.
  133448. */
  133449. static void nodeReference(RtreeNode *p){
  133450. if( p ){
  133451. p->nRef++;
  133452. }
  133453. }
  133454. /*
  133455. ** Clear the content of node p (set all bytes to 0x00).
  133456. */
  133457. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  133458. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  133459. p->isDirty = 1;
  133460. }
  133461. /*
  133462. ** Given a node number iNode, return the corresponding key to use
  133463. ** in the Rtree.aHash table.
  133464. */
  133465. static int nodeHash(i64 iNode){
  133466. return (
  133467. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  133468. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  133469. ) % HASHSIZE;
  133470. }
  133471. /*
  133472. ** Search the node hash table for node iNode. If found, return a pointer
  133473. ** to it. Otherwise, return 0.
  133474. */
  133475. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  133476. RtreeNode *p;
  133477. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  133478. return p;
  133479. }
  133480. /*
  133481. ** Add node pNode to the node hash table.
  133482. */
  133483. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  133484. int iHash;
  133485. assert( pNode->pNext==0 );
  133486. iHash = nodeHash(pNode->iNode);
  133487. pNode->pNext = pRtree->aHash[iHash];
  133488. pRtree->aHash[iHash] = pNode;
  133489. }
  133490. /*
  133491. ** Remove node pNode from the node hash table.
  133492. */
  133493. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  133494. RtreeNode **pp;
  133495. if( pNode->iNode!=0 ){
  133496. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  133497. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  133498. *pp = pNode->pNext;
  133499. pNode->pNext = 0;
  133500. }
  133501. }
  133502. /*
  133503. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  133504. ** indicating that node has not yet been assigned a node number. It is
  133505. ** assigned a node number when nodeWrite() is called to write the
  133506. ** node contents out to the database.
  133507. */
  133508. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  133509. RtreeNode *pNode;
  133510. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  133511. if( pNode ){
  133512. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  133513. pNode->zData = (u8 *)&pNode[1];
  133514. pNode->nRef = 1;
  133515. pNode->pParent = pParent;
  133516. pNode->isDirty = 1;
  133517. nodeReference(pParent);
  133518. }
  133519. return pNode;
  133520. }
  133521. /*
  133522. ** Obtain a reference to an r-tree node.
  133523. */
  133524. static int
  133525. nodeAcquire(
  133526. Rtree *pRtree, /* R-tree structure */
  133527. i64 iNode, /* Node number to load */
  133528. RtreeNode *pParent, /* Either the parent node or NULL */
  133529. RtreeNode **ppNode /* OUT: Acquired node */
  133530. ){
  133531. int rc;
  133532. int rc2 = SQLITE_OK;
  133533. RtreeNode *pNode;
  133534. /* Check if the requested node is already in the hash table. If so,
  133535. ** increase its reference count and return it.
  133536. */
  133537. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  133538. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  133539. if( pParent && !pNode->pParent ){
  133540. nodeReference(pParent);
  133541. pNode->pParent = pParent;
  133542. }
  133543. pNode->nRef++;
  133544. *ppNode = pNode;
  133545. return SQLITE_OK;
  133546. }
  133547. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  133548. rc = sqlite3_step(pRtree->pReadNode);
  133549. if( rc==SQLITE_ROW ){
  133550. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  133551. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  133552. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  133553. if( !pNode ){
  133554. rc2 = SQLITE_NOMEM;
  133555. }else{
  133556. pNode->pParent = pParent;
  133557. pNode->zData = (u8 *)&pNode[1];
  133558. pNode->nRef = 1;
  133559. pNode->iNode = iNode;
  133560. pNode->isDirty = 0;
  133561. pNode->pNext = 0;
  133562. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  133563. nodeReference(pParent);
  133564. }
  133565. }
  133566. }
  133567. rc = sqlite3_reset(pRtree->pReadNode);
  133568. if( rc==SQLITE_OK ) rc = rc2;
  133569. /* If the root node was just loaded, set pRtree->iDepth to the height
  133570. ** of the r-tree structure. A height of zero means all data is stored on
  133571. ** the root node. A height of one means the children of the root node
  133572. ** are the leaves, and so on. If the depth as specified on the root node
  133573. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  133574. */
  133575. if( pNode && iNode==1 ){
  133576. pRtree->iDepth = readInt16(pNode->zData);
  133577. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  133578. rc = SQLITE_CORRUPT_VTAB;
  133579. }
  133580. }
  133581. /* If no error has occurred so far, check if the "number of entries"
  133582. ** field on the node is too large. If so, set the return code to
  133583. ** SQLITE_CORRUPT_VTAB.
  133584. */
  133585. if( pNode && rc==SQLITE_OK ){
  133586. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  133587. rc = SQLITE_CORRUPT_VTAB;
  133588. }
  133589. }
  133590. if( rc==SQLITE_OK ){
  133591. if( pNode!=0 ){
  133592. nodeHashInsert(pRtree, pNode);
  133593. }else{
  133594. rc = SQLITE_CORRUPT_VTAB;
  133595. }
  133596. *ppNode = pNode;
  133597. }else{
  133598. sqlite3_free(pNode);
  133599. *ppNode = 0;
  133600. }
  133601. return rc;
  133602. }
  133603. /*
  133604. ** Overwrite cell iCell of node pNode with the contents of pCell.
  133605. */
  133606. static void nodeOverwriteCell(
  133607. Rtree *pRtree,
  133608. RtreeNode *pNode,
  133609. RtreeCell *pCell,
  133610. int iCell
  133611. ){
  133612. int ii;
  133613. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  133614. p += writeInt64(p, pCell->iRowid);
  133615. for(ii=0; ii<(pRtree->nDim*2); ii++){
  133616. p += writeCoord(p, &pCell->aCoord[ii]);
  133617. }
  133618. pNode->isDirty = 1;
  133619. }
  133620. /*
  133621. ** Remove cell the cell with index iCell from node pNode.
  133622. */
  133623. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  133624. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  133625. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  133626. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  133627. memmove(pDst, pSrc, nByte);
  133628. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  133629. pNode->isDirty = 1;
  133630. }
  133631. /*
  133632. ** Insert the contents of cell pCell into node pNode. If the insert
  133633. ** is successful, return SQLITE_OK.
  133634. **
  133635. ** If there is not enough free space in pNode, return SQLITE_FULL.
  133636. */
  133637. static int
  133638. nodeInsertCell(
  133639. Rtree *pRtree,
  133640. RtreeNode *pNode,
  133641. RtreeCell *pCell
  133642. ){
  133643. int nCell; /* Current number of cells in pNode */
  133644. int nMaxCell; /* Maximum number of cells for pNode */
  133645. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  133646. nCell = NCELL(pNode);
  133647. assert( nCell<=nMaxCell );
  133648. if( nCell<nMaxCell ){
  133649. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  133650. writeInt16(&pNode->zData[2], nCell+1);
  133651. pNode->isDirty = 1;
  133652. }
  133653. return (nCell==nMaxCell);
  133654. }
  133655. /*
  133656. ** If the node is dirty, write it out to the database.
  133657. */
  133658. static int
  133659. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  133660. int rc = SQLITE_OK;
  133661. if( pNode->isDirty ){
  133662. sqlite3_stmt *p = pRtree->pWriteNode;
  133663. if( pNode->iNode ){
  133664. sqlite3_bind_int64(p, 1, pNode->iNode);
  133665. }else{
  133666. sqlite3_bind_null(p, 1);
  133667. }
  133668. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  133669. sqlite3_step(p);
  133670. pNode->isDirty = 0;
  133671. rc = sqlite3_reset(p);
  133672. if( pNode->iNode==0 && rc==SQLITE_OK ){
  133673. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  133674. nodeHashInsert(pRtree, pNode);
  133675. }
  133676. }
  133677. return rc;
  133678. }
  133679. /*
  133680. ** Release a reference to a node. If the node is dirty and the reference
  133681. ** count drops to zero, the node data is written to the database.
  133682. */
  133683. static int
  133684. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  133685. int rc = SQLITE_OK;
  133686. if( pNode ){
  133687. assert( pNode->nRef>0 );
  133688. pNode->nRef--;
  133689. if( pNode->nRef==0 ){
  133690. if( pNode->iNode==1 ){
  133691. pRtree->iDepth = -1;
  133692. }
  133693. if( pNode->pParent ){
  133694. rc = nodeRelease(pRtree, pNode->pParent);
  133695. }
  133696. if( rc==SQLITE_OK ){
  133697. rc = nodeWrite(pRtree, pNode);
  133698. }
  133699. nodeHashDelete(pRtree, pNode);
  133700. sqlite3_free(pNode);
  133701. }
  133702. }
  133703. return rc;
  133704. }
  133705. /*
  133706. ** Return the 64-bit integer value associated with cell iCell of
  133707. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  133708. ** an internal node, then the 64-bit integer is a child page number.
  133709. */
  133710. static i64 nodeGetRowid(
  133711. Rtree *pRtree,
  133712. RtreeNode *pNode,
  133713. int iCell
  133714. ){
  133715. assert( iCell<NCELL(pNode) );
  133716. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  133717. }
  133718. /*
  133719. ** Return coordinate iCoord from cell iCell in node pNode.
  133720. */
  133721. static void nodeGetCoord(
  133722. Rtree *pRtree,
  133723. RtreeNode *pNode,
  133724. int iCell,
  133725. int iCoord,
  133726. RtreeCoord *pCoord /* Space to write result to */
  133727. ){
  133728. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  133729. }
  133730. /*
  133731. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  133732. ** to by pCell with the results.
  133733. */
  133734. static void nodeGetCell(
  133735. Rtree *pRtree,
  133736. RtreeNode *pNode,
  133737. int iCell,
  133738. RtreeCell *pCell
  133739. ){
  133740. int ii;
  133741. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  133742. for(ii=0; ii<pRtree->nDim*2; ii++){
  133743. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  133744. }
  133745. }
  133746. /* Forward declaration for the function that does the work of
  133747. ** the virtual table module xCreate() and xConnect() methods.
  133748. */
  133749. static int rtreeInit(
  133750. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  133751. );
  133752. /*
  133753. ** Rtree virtual table module xCreate method.
  133754. */
  133755. static int rtreeCreate(
  133756. sqlite3 *db,
  133757. void *pAux,
  133758. int argc, const char *const*argv,
  133759. sqlite3_vtab **ppVtab,
  133760. char **pzErr
  133761. ){
  133762. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  133763. }
  133764. /*
  133765. ** Rtree virtual table module xConnect method.
  133766. */
  133767. static int rtreeConnect(
  133768. sqlite3 *db,
  133769. void *pAux,
  133770. int argc, const char *const*argv,
  133771. sqlite3_vtab **ppVtab,
  133772. char **pzErr
  133773. ){
  133774. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  133775. }
  133776. /*
  133777. ** Increment the r-tree reference count.
  133778. */
  133779. static void rtreeReference(Rtree *pRtree){
  133780. pRtree->nBusy++;
  133781. }
  133782. /*
  133783. ** Decrement the r-tree reference count. When the reference count reaches
  133784. ** zero the structure is deleted.
  133785. */
  133786. static void rtreeRelease(Rtree *pRtree){
  133787. pRtree->nBusy--;
  133788. if( pRtree->nBusy==0 ){
  133789. sqlite3_finalize(pRtree->pReadNode);
  133790. sqlite3_finalize(pRtree->pWriteNode);
  133791. sqlite3_finalize(pRtree->pDeleteNode);
  133792. sqlite3_finalize(pRtree->pReadRowid);
  133793. sqlite3_finalize(pRtree->pWriteRowid);
  133794. sqlite3_finalize(pRtree->pDeleteRowid);
  133795. sqlite3_finalize(pRtree->pReadParent);
  133796. sqlite3_finalize(pRtree->pWriteParent);
  133797. sqlite3_finalize(pRtree->pDeleteParent);
  133798. sqlite3_free(pRtree);
  133799. }
  133800. }
  133801. /*
  133802. ** Rtree virtual table module xDisconnect method.
  133803. */
  133804. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  133805. rtreeRelease((Rtree *)pVtab);
  133806. return SQLITE_OK;
  133807. }
  133808. /*
  133809. ** Rtree virtual table module xDestroy method.
  133810. */
  133811. static int rtreeDestroy(sqlite3_vtab *pVtab){
  133812. Rtree *pRtree = (Rtree *)pVtab;
  133813. int rc;
  133814. char *zCreate = sqlite3_mprintf(
  133815. "DROP TABLE '%q'.'%q_node';"
  133816. "DROP TABLE '%q'.'%q_rowid';"
  133817. "DROP TABLE '%q'.'%q_parent';",
  133818. pRtree->zDb, pRtree->zName,
  133819. pRtree->zDb, pRtree->zName,
  133820. pRtree->zDb, pRtree->zName
  133821. );
  133822. if( !zCreate ){
  133823. rc = SQLITE_NOMEM;
  133824. }else{
  133825. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  133826. sqlite3_free(zCreate);
  133827. }
  133828. if( rc==SQLITE_OK ){
  133829. rtreeRelease(pRtree);
  133830. }
  133831. return rc;
  133832. }
  133833. /*
  133834. ** Rtree virtual table module xOpen method.
  133835. */
  133836. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  133837. int rc = SQLITE_NOMEM;
  133838. RtreeCursor *pCsr;
  133839. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  133840. if( pCsr ){
  133841. memset(pCsr, 0, sizeof(RtreeCursor));
  133842. pCsr->base.pVtab = pVTab;
  133843. rc = SQLITE_OK;
  133844. }
  133845. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  133846. return rc;
  133847. }
  133848. /*
  133849. ** Free the RtreeCursor.aConstraint[] array and its contents.
  133850. */
  133851. static void freeCursorConstraints(RtreeCursor *pCsr){
  133852. if( pCsr->aConstraint ){
  133853. int i; /* Used to iterate through constraint array */
  133854. for(i=0; i<pCsr->nConstraint; i++){
  133855. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  133856. if( pGeom ){
  133857. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  133858. sqlite3_free(pGeom);
  133859. }
  133860. }
  133861. sqlite3_free(pCsr->aConstraint);
  133862. pCsr->aConstraint = 0;
  133863. }
  133864. }
  133865. /*
  133866. ** Rtree virtual table module xClose method.
  133867. */
  133868. static int rtreeClose(sqlite3_vtab_cursor *cur){
  133869. Rtree *pRtree = (Rtree *)(cur->pVtab);
  133870. int rc;
  133871. RtreeCursor *pCsr = (RtreeCursor *)cur;
  133872. freeCursorConstraints(pCsr);
  133873. rc = nodeRelease(pRtree, pCsr->pNode);
  133874. sqlite3_free(pCsr);
  133875. return rc;
  133876. }
  133877. /*
  133878. ** Rtree virtual table module xEof method.
  133879. **
  133880. ** Return non-zero if the cursor does not currently point to a valid
  133881. ** record (i.e if the scan has finished), or zero otherwise.
  133882. */
  133883. static int rtreeEof(sqlite3_vtab_cursor *cur){
  133884. RtreeCursor *pCsr = (RtreeCursor *)cur;
  133885. return (pCsr->pNode==0);
  133886. }
  133887. /*
  133888. ** The r-tree constraint passed as the second argument to this function is
  133889. ** guaranteed to be a MATCH constraint.
  133890. */
  133891. static int testRtreeGeom(
  133892. Rtree *pRtree, /* R-Tree object */
  133893. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  133894. RtreeCell *pCell, /* Cell to test */
  133895. int *pbRes /* OUT: Test result */
  133896. ){
  133897. int i;
  133898. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  133899. int nCoord = pRtree->nDim*2;
  133900. assert( pConstraint->op==RTREE_MATCH );
  133901. assert( pConstraint->pGeom );
  133902. for(i=0; i<nCoord; i++){
  133903. aCoord[i] = DCOORD(pCell->aCoord[i]);
  133904. }
  133905. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  133906. }
  133907. /*
  133908. ** Cursor pCursor currently points to a cell in a non-leaf page.
  133909. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  133910. ** (excluded) by the constraints in the pCursor->aConstraint[]
  133911. ** array, or false otherwise.
  133912. **
  133913. ** Return SQLITE_OK if successful or an SQLite error code if an error
  133914. ** occurs within a geometry callback.
  133915. */
  133916. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  133917. RtreeCell cell;
  133918. int ii;
  133919. int bRes = 0;
  133920. int rc = SQLITE_OK;
  133921. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  133922. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  133923. RtreeConstraint *p = &pCursor->aConstraint[ii];
  133924. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  133925. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  133926. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  133927. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  133928. );
  133929. switch( p->op ){
  133930. case RTREE_LE: case RTREE_LT:
  133931. bRes = p->rValue<cell_min;
  133932. break;
  133933. case RTREE_GE: case RTREE_GT:
  133934. bRes = p->rValue>cell_max;
  133935. break;
  133936. case RTREE_EQ:
  133937. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  133938. break;
  133939. default: {
  133940. assert( p->op==RTREE_MATCH );
  133941. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  133942. bRes = !bRes;
  133943. break;
  133944. }
  133945. }
  133946. }
  133947. *pbEof = bRes;
  133948. return rc;
  133949. }
  133950. /*
  133951. ** Test if the cell that cursor pCursor currently points to
  133952. ** would be filtered (excluded) by the constraints in the
  133953. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  133954. ** returning. If the cell is not filtered (excluded) by the constraints,
  133955. ** set pbEof to zero.
  133956. **
  133957. ** Return SQLITE_OK if successful or an SQLite error code if an error
  133958. ** occurs within a geometry callback.
  133959. **
  133960. ** This function assumes that the cell is part of a leaf node.
  133961. */
  133962. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  133963. RtreeCell cell;
  133964. int ii;
  133965. *pbEof = 0;
  133966. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  133967. for(ii=0; ii<pCursor->nConstraint; ii++){
  133968. RtreeConstraint *p = &pCursor->aConstraint[ii];
  133969. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  133970. int res;
  133971. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  133972. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  133973. );
  133974. switch( p->op ){
  133975. case RTREE_LE: res = (coord<=p->rValue); break;
  133976. case RTREE_LT: res = (coord<p->rValue); break;
  133977. case RTREE_GE: res = (coord>=p->rValue); break;
  133978. case RTREE_GT: res = (coord>p->rValue); break;
  133979. case RTREE_EQ: res = (coord==p->rValue); break;
  133980. default: {
  133981. int rc;
  133982. assert( p->op==RTREE_MATCH );
  133983. rc = testRtreeGeom(pRtree, p, &cell, &res);
  133984. if( rc!=SQLITE_OK ){
  133985. return rc;
  133986. }
  133987. break;
  133988. }
  133989. }
  133990. if( !res ){
  133991. *pbEof = 1;
  133992. return SQLITE_OK;
  133993. }
  133994. }
  133995. return SQLITE_OK;
  133996. }
  133997. /*
  133998. ** Cursor pCursor currently points at a node that heads a sub-tree of
  133999. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  134000. ** to point to the left-most cell of the sub-tree that matches the
  134001. ** configured constraints.
  134002. */
  134003. static int descendToCell(
  134004. Rtree *pRtree,
  134005. RtreeCursor *pCursor,
  134006. int iHeight,
  134007. int *pEof /* OUT: Set to true if cannot descend */
  134008. ){
  134009. int isEof;
  134010. int rc;
  134011. int ii;
  134012. RtreeNode *pChild;
  134013. sqlite3_int64 iRowid;
  134014. RtreeNode *pSavedNode = pCursor->pNode;
  134015. int iSavedCell = pCursor->iCell;
  134016. assert( iHeight>=0 );
  134017. if( iHeight==0 ){
  134018. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  134019. }else{
  134020. rc = testRtreeCell(pRtree, pCursor, &isEof);
  134021. }
  134022. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  134023. goto descend_to_cell_out;
  134024. }
  134025. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  134026. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  134027. if( rc!=SQLITE_OK ){
  134028. goto descend_to_cell_out;
  134029. }
  134030. nodeRelease(pRtree, pCursor->pNode);
  134031. pCursor->pNode = pChild;
  134032. isEof = 1;
  134033. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  134034. pCursor->iCell = ii;
  134035. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  134036. if( rc!=SQLITE_OK ){
  134037. goto descend_to_cell_out;
  134038. }
  134039. }
  134040. if( isEof ){
  134041. assert( pCursor->pNode==pChild );
  134042. nodeReference(pSavedNode);
  134043. nodeRelease(pRtree, pChild);
  134044. pCursor->pNode = pSavedNode;
  134045. pCursor->iCell = iSavedCell;
  134046. }
  134047. descend_to_cell_out:
  134048. *pEof = isEof;
  134049. return rc;
  134050. }
  134051. /*
  134052. ** One of the cells in node pNode is guaranteed to have a 64-bit
  134053. ** integer value equal to iRowid. Return the index of this cell.
  134054. */
  134055. static int nodeRowidIndex(
  134056. Rtree *pRtree,
  134057. RtreeNode *pNode,
  134058. i64 iRowid,
  134059. int *piIndex
  134060. ){
  134061. int ii;
  134062. int nCell = NCELL(pNode);
  134063. for(ii=0; ii<nCell; ii++){
  134064. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  134065. *piIndex = ii;
  134066. return SQLITE_OK;
  134067. }
  134068. }
  134069. return SQLITE_CORRUPT_VTAB;
  134070. }
  134071. /*
  134072. ** Return the index of the cell containing a pointer to node pNode
  134073. ** in its parent. If pNode is the root node, return -1.
  134074. */
  134075. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  134076. RtreeNode *pParent = pNode->pParent;
  134077. if( pParent ){
  134078. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  134079. }
  134080. *piIndex = -1;
  134081. return SQLITE_OK;
  134082. }
  134083. /*
  134084. ** Rtree virtual table module xNext method.
  134085. */
  134086. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  134087. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  134088. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134089. int rc = SQLITE_OK;
  134090. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  134091. ** already at EOF. It is against the rules to call the xNext() method of
  134092. ** a cursor that has already reached EOF.
  134093. */
  134094. assert( pCsr->pNode );
  134095. if( pCsr->iStrategy==1 ){
  134096. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  134097. nodeRelease(pRtree, pCsr->pNode);
  134098. pCsr->pNode = 0;
  134099. }else{
  134100. /* Move to the next entry that matches the configured constraints. */
  134101. int iHeight = 0;
  134102. while( pCsr->pNode ){
  134103. RtreeNode *pNode = pCsr->pNode;
  134104. int nCell = NCELL(pNode);
  134105. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  134106. int isEof;
  134107. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  134108. if( rc!=SQLITE_OK || !isEof ){
  134109. return rc;
  134110. }
  134111. }
  134112. pCsr->pNode = pNode->pParent;
  134113. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  134114. if( rc!=SQLITE_OK ){
  134115. return rc;
  134116. }
  134117. nodeReference(pCsr->pNode);
  134118. nodeRelease(pRtree, pNode);
  134119. iHeight++;
  134120. }
  134121. }
  134122. return rc;
  134123. }
  134124. /*
  134125. ** Rtree virtual table module xRowid method.
  134126. */
  134127. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  134128. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  134129. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134130. assert(pCsr->pNode);
  134131. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  134132. return SQLITE_OK;
  134133. }
  134134. /*
  134135. ** Rtree virtual table module xColumn method.
  134136. */
  134137. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  134138. Rtree *pRtree = (Rtree *)cur->pVtab;
  134139. RtreeCursor *pCsr = (RtreeCursor *)cur;
  134140. if( i==0 ){
  134141. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  134142. sqlite3_result_int64(ctx, iRowid);
  134143. }else{
  134144. RtreeCoord c;
  134145. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  134146. #ifndef SQLITE_RTREE_INT_ONLY
  134147. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  134148. sqlite3_result_double(ctx, c.f);
  134149. }else
  134150. #endif
  134151. {
  134152. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  134153. sqlite3_result_int(ctx, c.i);
  134154. }
  134155. }
  134156. return SQLITE_OK;
  134157. }
  134158. /*
  134159. ** Use nodeAcquire() to obtain the leaf node containing the record with
  134160. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  134161. ** return SQLITE_OK. If there is no such record in the table, set
  134162. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  134163. ** to zero and return an SQLite error code.
  134164. */
  134165. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  134166. int rc;
  134167. *ppLeaf = 0;
  134168. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  134169. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  134170. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  134171. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  134172. sqlite3_reset(pRtree->pReadRowid);
  134173. }else{
  134174. rc = sqlite3_reset(pRtree->pReadRowid);
  134175. }
  134176. return rc;
  134177. }
  134178. /*
  134179. ** This function is called to configure the RtreeConstraint object passed
  134180. ** as the second argument for a MATCH constraint. The value passed as the
  134181. ** first argument to this function is the right-hand operand to the MATCH
  134182. ** operator.
  134183. */
  134184. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  134185. RtreeMatchArg *p;
  134186. sqlite3_rtree_geometry *pGeom;
  134187. int nBlob;
  134188. /* Check that value is actually a blob. */
  134189. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  134190. /* Check that the blob is roughly the right size. */
  134191. nBlob = sqlite3_value_bytes(pValue);
  134192. if( nBlob<(int)sizeof(RtreeMatchArg)
  134193. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  134194. ){
  134195. return SQLITE_ERROR;
  134196. }
  134197. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  134198. sizeof(sqlite3_rtree_geometry) + nBlob
  134199. );
  134200. if( !pGeom ) return SQLITE_NOMEM;
  134201. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  134202. p = (RtreeMatchArg *)&pGeom[1];
  134203. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  134204. if( p->magic!=RTREE_GEOMETRY_MAGIC
  134205. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  134206. ){
  134207. sqlite3_free(pGeom);
  134208. return SQLITE_ERROR;
  134209. }
  134210. pGeom->pContext = p->pContext;
  134211. pGeom->nParam = p->nParam;
  134212. pGeom->aParam = p->aParam;
  134213. pCons->xGeom = p->xGeom;
  134214. pCons->pGeom = pGeom;
  134215. return SQLITE_OK;
  134216. }
  134217. /*
  134218. ** Rtree virtual table module xFilter method.
  134219. */
  134220. static int rtreeFilter(
  134221. sqlite3_vtab_cursor *pVtabCursor,
  134222. int idxNum, const char *idxStr,
  134223. int argc, sqlite3_value **argv
  134224. ){
  134225. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  134226. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134227. RtreeNode *pRoot = 0;
  134228. int ii;
  134229. int rc = SQLITE_OK;
  134230. rtreeReference(pRtree);
  134231. freeCursorConstraints(pCsr);
  134232. pCsr->iStrategy = idxNum;
  134233. if( idxNum==1 ){
  134234. /* Special case - lookup by rowid. */
  134235. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  134236. i64 iRowid = sqlite3_value_int64(argv[0]);
  134237. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  134238. pCsr->pNode = pLeaf;
  134239. if( pLeaf ){
  134240. assert( rc==SQLITE_OK );
  134241. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  134242. }
  134243. }else{
  134244. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  134245. ** with the configured constraints.
  134246. */
  134247. if( argc>0 ){
  134248. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  134249. pCsr->nConstraint = argc;
  134250. if( !pCsr->aConstraint ){
  134251. rc = SQLITE_NOMEM;
  134252. }else{
  134253. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  134254. assert( (idxStr==0 && argc==0)
  134255. || (idxStr && (int)strlen(idxStr)==argc*2) );
  134256. for(ii=0; ii<argc; ii++){
  134257. RtreeConstraint *p = &pCsr->aConstraint[ii];
  134258. p->op = idxStr[ii*2];
  134259. p->iCoord = idxStr[ii*2+1]-'a';
  134260. if( p->op==RTREE_MATCH ){
  134261. /* A MATCH operator. The right-hand-side must be a blob that
  134262. ** can be cast into an RtreeMatchArg object. One created using
  134263. ** an sqlite3_rtree_geometry_callback() SQL user function.
  134264. */
  134265. rc = deserializeGeometry(argv[ii], p);
  134266. if( rc!=SQLITE_OK ){
  134267. break;
  134268. }
  134269. }else{
  134270. #ifdef SQLITE_RTREE_INT_ONLY
  134271. p->rValue = sqlite3_value_int64(argv[ii]);
  134272. #else
  134273. p->rValue = sqlite3_value_double(argv[ii]);
  134274. #endif
  134275. }
  134276. }
  134277. }
  134278. }
  134279. if( rc==SQLITE_OK ){
  134280. pCsr->pNode = 0;
  134281. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  134282. }
  134283. if( rc==SQLITE_OK ){
  134284. int isEof = 1;
  134285. int nCell = NCELL(pRoot);
  134286. pCsr->pNode = pRoot;
  134287. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  134288. assert( pCsr->pNode==pRoot );
  134289. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  134290. if( !isEof ){
  134291. break;
  134292. }
  134293. }
  134294. if( rc==SQLITE_OK && isEof ){
  134295. assert( pCsr->pNode==pRoot );
  134296. nodeRelease(pRtree, pRoot);
  134297. pCsr->pNode = 0;
  134298. }
  134299. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  134300. }
  134301. }
  134302. rtreeRelease(pRtree);
  134303. return rc;
  134304. }
  134305. /*
  134306. ** Rtree virtual table module xBestIndex method. There are three
  134307. ** table scan strategies to choose from (in order from most to
  134308. ** least desirable):
  134309. **
  134310. ** idxNum idxStr Strategy
  134311. ** ------------------------------------------------
  134312. ** 1 Unused Direct lookup by rowid.
  134313. ** 2 See below R-tree query or full-table scan.
  134314. ** ------------------------------------------------
  134315. **
  134316. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  134317. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  134318. ** constraint used. The first two bytes of idxStr correspond to
  134319. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  134320. ** (argvIndex==1) etc.
  134321. **
  134322. ** The first of each pair of bytes in idxStr identifies the constraint
  134323. ** operator as follows:
  134324. **
  134325. ** Operator Byte Value
  134326. ** ----------------------
  134327. ** = 0x41 ('A')
  134328. ** <= 0x42 ('B')
  134329. ** < 0x43 ('C')
  134330. ** >= 0x44 ('D')
  134331. ** > 0x45 ('E')
  134332. ** MATCH 0x46 ('F')
  134333. ** ----------------------
  134334. **
  134335. ** The second of each pair of bytes identifies the coordinate column
  134336. ** to which the constraint applies. The leftmost coordinate column
  134337. ** is 'a', the second from the left 'b' etc.
  134338. */
  134339. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  134340. int rc = SQLITE_OK;
  134341. int ii;
  134342. int iIdx = 0;
  134343. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  134344. memset(zIdxStr, 0, sizeof(zIdxStr));
  134345. UNUSED_PARAMETER(tab);
  134346. assert( pIdxInfo->idxStr==0 );
  134347. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  134348. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  134349. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  134350. /* We have an equality constraint on the rowid. Use strategy 1. */
  134351. int jj;
  134352. for(jj=0; jj<ii; jj++){
  134353. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  134354. pIdxInfo->aConstraintUsage[jj].omit = 0;
  134355. }
  134356. pIdxInfo->idxNum = 1;
  134357. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  134358. pIdxInfo->aConstraintUsage[jj].omit = 1;
  134359. /* This strategy involves a two rowid lookups on an B-Tree structures
  134360. ** and then a linear search of an R-Tree node. This should be
  134361. ** considered almost as quick as a direct rowid lookup (for which
  134362. ** sqlite uses an internal cost of 0.0).
  134363. */
  134364. pIdxInfo->estimatedCost = 10.0;
  134365. return SQLITE_OK;
  134366. }
  134367. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  134368. u8 op;
  134369. switch( p->op ){
  134370. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  134371. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  134372. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  134373. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  134374. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  134375. default:
  134376. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  134377. op = RTREE_MATCH;
  134378. break;
  134379. }
  134380. zIdxStr[iIdx++] = op;
  134381. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  134382. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  134383. pIdxInfo->aConstraintUsage[ii].omit = 1;
  134384. }
  134385. }
  134386. pIdxInfo->idxNum = 2;
  134387. pIdxInfo->needToFreeIdxStr = 1;
  134388. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  134389. return SQLITE_NOMEM;
  134390. }
  134391. assert( iIdx>=0 );
  134392. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  134393. return rc;
  134394. }
  134395. /*
  134396. ** Return the N-dimensional volumn of the cell stored in *p.
  134397. */
  134398. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  134399. RtreeDValue area = (RtreeDValue)1;
  134400. int ii;
  134401. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134402. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  134403. }
  134404. return area;
  134405. }
  134406. /*
  134407. ** Return the margin length of cell p. The margin length is the sum
  134408. ** of the objects size in each dimension.
  134409. */
  134410. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  134411. RtreeDValue margin = (RtreeDValue)0;
  134412. int ii;
  134413. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134414. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  134415. }
  134416. return margin;
  134417. }
  134418. /*
  134419. ** Store the union of cells p1 and p2 in p1.
  134420. */
  134421. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  134422. int ii;
  134423. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  134424. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134425. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  134426. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  134427. }
  134428. }else{
  134429. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134430. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  134431. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  134432. }
  134433. }
  134434. }
  134435. /*
  134436. ** Return true if the area covered by p2 is a subset of the area covered
  134437. ** by p1. False otherwise.
  134438. */
  134439. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  134440. int ii;
  134441. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  134442. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134443. RtreeCoord *a1 = &p1->aCoord[ii];
  134444. RtreeCoord *a2 = &p2->aCoord[ii];
  134445. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  134446. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  134447. ){
  134448. return 0;
  134449. }
  134450. }
  134451. return 1;
  134452. }
  134453. /*
  134454. ** Return the amount cell p would grow by if it were unioned with pCell.
  134455. */
  134456. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  134457. RtreeDValue area;
  134458. RtreeCell cell;
  134459. memcpy(&cell, p, sizeof(RtreeCell));
  134460. area = cellArea(pRtree, &cell);
  134461. cellUnion(pRtree, &cell, pCell);
  134462. return (cellArea(pRtree, &cell)-area);
  134463. }
  134464. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  134465. static RtreeDValue cellOverlap(
  134466. Rtree *pRtree,
  134467. RtreeCell *p,
  134468. RtreeCell *aCell,
  134469. int nCell,
  134470. int iExclude
  134471. ){
  134472. int ii;
  134473. RtreeDValue overlap = 0.0;
  134474. for(ii=0; ii<nCell; ii++){
  134475. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134476. if( ii!=iExclude )
  134477. #else
  134478. assert( iExclude==-1 );
  134479. UNUSED_PARAMETER(iExclude);
  134480. #endif
  134481. {
  134482. int jj;
  134483. RtreeDValue o = (RtreeDValue)1;
  134484. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  134485. RtreeDValue x1, x2;
  134486. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  134487. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  134488. if( x2<x1 ){
  134489. o = 0.0;
  134490. break;
  134491. }else{
  134492. o = o * (x2-x1);
  134493. }
  134494. }
  134495. overlap += o;
  134496. }
  134497. }
  134498. return overlap;
  134499. }
  134500. #endif
  134501. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134502. static RtreeDValue cellOverlapEnlargement(
  134503. Rtree *pRtree,
  134504. RtreeCell *p,
  134505. RtreeCell *pInsert,
  134506. RtreeCell *aCell,
  134507. int nCell,
  134508. int iExclude
  134509. ){
  134510. RtreeDValue before, after;
  134511. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  134512. cellUnion(pRtree, p, pInsert);
  134513. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  134514. return (after-before);
  134515. }
  134516. #endif
  134517. /*
  134518. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  134519. ** ChooseSubTree in r*tree terminology.
  134520. */
  134521. static int ChooseLeaf(
  134522. Rtree *pRtree, /* Rtree table */
  134523. RtreeCell *pCell, /* Cell to insert into rtree */
  134524. int iHeight, /* Height of sub-tree rooted at pCell */
  134525. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  134526. ){
  134527. int rc;
  134528. int ii;
  134529. RtreeNode *pNode;
  134530. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  134531. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  134532. int iCell;
  134533. sqlite3_int64 iBest = 0;
  134534. RtreeDValue fMinGrowth = 0.0;
  134535. RtreeDValue fMinArea = 0.0;
  134536. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134537. RtreeDValue fMinOverlap = 0.0;
  134538. RtreeDValue overlap;
  134539. #endif
  134540. int nCell = NCELL(pNode);
  134541. RtreeCell cell;
  134542. RtreeNode *pChild;
  134543. RtreeCell *aCell = 0;
  134544. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134545. if( ii==(pRtree->iDepth-1) ){
  134546. int jj;
  134547. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  134548. if( !aCell ){
  134549. rc = SQLITE_NOMEM;
  134550. nodeRelease(pRtree, pNode);
  134551. pNode = 0;
  134552. continue;
  134553. }
  134554. for(jj=0; jj<nCell; jj++){
  134555. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  134556. }
  134557. }
  134558. #endif
  134559. /* Select the child node which will be enlarged the least if pCell
  134560. ** is inserted into it. Resolve ties by choosing the entry with
  134561. ** the smallest area.
  134562. */
  134563. for(iCell=0; iCell<nCell; iCell++){
  134564. int bBest = 0;
  134565. RtreeDValue growth;
  134566. RtreeDValue area;
  134567. nodeGetCell(pRtree, pNode, iCell, &cell);
  134568. growth = cellGrowth(pRtree, &cell, pCell);
  134569. area = cellArea(pRtree, &cell);
  134570. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134571. if( ii==(pRtree->iDepth-1) ){
  134572. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  134573. }else{
  134574. overlap = 0.0;
  134575. }
  134576. if( (iCell==0)
  134577. || (overlap<fMinOverlap)
  134578. || (overlap==fMinOverlap && growth<fMinGrowth)
  134579. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  134580. ){
  134581. bBest = 1;
  134582. fMinOverlap = overlap;
  134583. }
  134584. #else
  134585. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  134586. bBest = 1;
  134587. }
  134588. #endif
  134589. if( bBest ){
  134590. fMinGrowth = growth;
  134591. fMinArea = area;
  134592. iBest = cell.iRowid;
  134593. }
  134594. }
  134595. sqlite3_free(aCell);
  134596. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  134597. nodeRelease(pRtree, pNode);
  134598. pNode = pChild;
  134599. }
  134600. *ppLeaf = pNode;
  134601. return rc;
  134602. }
  134603. /*
  134604. ** A cell with the same content as pCell has just been inserted into
  134605. ** the node pNode. This function updates the bounding box cells in
  134606. ** all ancestor elements.
  134607. */
  134608. static int AdjustTree(
  134609. Rtree *pRtree, /* Rtree table */
  134610. RtreeNode *pNode, /* Adjust ancestry of this node. */
  134611. RtreeCell *pCell /* This cell was just inserted */
  134612. ){
  134613. RtreeNode *p = pNode;
  134614. while( p->pParent ){
  134615. RtreeNode *pParent = p->pParent;
  134616. RtreeCell cell;
  134617. int iCell;
  134618. if( nodeParentIndex(pRtree, p, &iCell) ){
  134619. return SQLITE_CORRUPT_VTAB;
  134620. }
  134621. nodeGetCell(pRtree, pParent, iCell, &cell);
  134622. if( !cellContains(pRtree, &cell, pCell) ){
  134623. cellUnion(pRtree, &cell, pCell);
  134624. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  134625. }
  134626. p = pParent;
  134627. }
  134628. return SQLITE_OK;
  134629. }
  134630. /*
  134631. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  134632. */
  134633. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  134634. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  134635. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  134636. sqlite3_step(pRtree->pWriteRowid);
  134637. return sqlite3_reset(pRtree->pWriteRowid);
  134638. }
  134639. /*
  134640. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  134641. */
  134642. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  134643. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  134644. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  134645. sqlite3_step(pRtree->pWriteParent);
  134646. return sqlite3_reset(pRtree->pWriteParent);
  134647. }
  134648. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  134649. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  134650. /*
  134651. ** Implementation of the linear variant of the PickNext() function from
  134652. ** Guttman[84].
  134653. */
  134654. static RtreeCell *LinearPickNext(
  134655. Rtree *pRtree,
  134656. RtreeCell *aCell,
  134657. int nCell,
  134658. RtreeCell *pLeftBox,
  134659. RtreeCell *pRightBox,
  134660. int *aiUsed
  134661. ){
  134662. int ii;
  134663. for(ii=0; aiUsed[ii]; ii++);
  134664. aiUsed[ii] = 1;
  134665. return &aCell[ii];
  134666. }
  134667. /*
  134668. ** Implementation of the linear variant of the PickSeeds() function from
  134669. ** Guttman[84].
  134670. */
  134671. static void LinearPickSeeds(
  134672. Rtree *pRtree,
  134673. RtreeCell *aCell,
  134674. int nCell,
  134675. int *piLeftSeed,
  134676. int *piRightSeed
  134677. ){
  134678. int i;
  134679. int iLeftSeed = 0;
  134680. int iRightSeed = 1;
  134681. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  134682. /* Pick two "seed" cells from the array of cells. The algorithm used
  134683. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  134684. ** indices of the two seed cells in the array are stored in local
  134685. ** variables iLeftSeek and iRightSeed.
  134686. */
  134687. for(i=0; i<pRtree->nDim; i++){
  134688. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  134689. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  134690. RtreeDValue x3 = x1;
  134691. RtreeDValue x4 = x2;
  134692. int jj;
  134693. int iCellLeft = 0;
  134694. int iCellRight = 0;
  134695. for(jj=1; jj<nCell; jj++){
  134696. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  134697. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  134698. if( left<x1 ) x1 = left;
  134699. if( right>x4 ) x4 = right;
  134700. if( left>x3 ){
  134701. x3 = left;
  134702. iCellRight = jj;
  134703. }
  134704. if( right<x2 ){
  134705. x2 = right;
  134706. iCellLeft = jj;
  134707. }
  134708. }
  134709. if( x4!=x1 ){
  134710. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  134711. if( normalwidth>maxNormalInnerWidth ){
  134712. iLeftSeed = iCellLeft;
  134713. iRightSeed = iCellRight;
  134714. }
  134715. }
  134716. }
  134717. *piLeftSeed = iLeftSeed;
  134718. *piRightSeed = iRightSeed;
  134719. }
  134720. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  134721. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  134722. /*
  134723. ** Implementation of the quadratic variant of the PickNext() function from
  134724. ** Guttman[84].
  134725. */
  134726. static RtreeCell *QuadraticPickNext(
  134727. Rtree *pRtree,
  134728. RtreeCell *aCell,
  134729. int nCell,
  134730. RtreeCell *pLeftBox,
  134731. RtreeCell *pRightBox,
  134732. int *aiUsed
  134733. ){
  134734. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  134735. int iSelect = -1;
  134736. RtreeDValue fDiff;
  134737. int ii;
  134738. for(ii=0; ii<nCell; ii++){
  134739. if( aiUsed[ii]==0 ){
  134740. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  134741. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  134742. RtreeDValue diff = FABS(right-left);
  134743. if( iSelect<0 || diff>fDiff ){
  134744. fDiff = diff;
  134745. iSelect = ii;
  134746. }
  134747. }
  134748. }
  134749. aiUsed[iSelect] = 1;
  134750. return &aCell[iSelect];
  134751. }
  134752. /*
  134753. ** Implementation of the quadratic variant of the PickSeeds() function from
  134754. ** Guttman[84].
  134755. */
  134756. static void QuadraticPickSeeds(
  134757. Rtree *pRtree,
  134758. RtreeCell *aCell,
  134759. int nCell,
  134760. int *piLeftSeed,
  134761. int *piRightSeed
  134762. ){
  134763. int ii;
  134764. int jj;
  134765. int iLeftSeed = 0;
  134766. int iRightSeed = 1;
  134767. RtreeDValue fWaste = 0.0;
  134768. for(ii=0; ii<nCell; ii++){
  134769. for(jj=ii+1; jj<nCell; jj++){
  134770. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  134771. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  134772. RtreeDValue waste = growth - right;
  134773. if( waste>fWaste ){
  134774. iLeftSeed = ii;
  134775. iRightSeed = jj;
  134776. fWaste = waste;
  134777. }
  134778. }
  134779. }
  134780. *piLeftSeed = iLeftSeed;
  134781. *piRightSeed = iRightSeed;
  134782. }
  134783. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  134784. /*
  134785. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  134786. ** nIdx. The aIdx array contains the set of integers from 0 to
  134787. ** (nIdx-1) in no particular order. This function sorts the values
  134788. ** in aIdx according to the indexed values in aDistance. For
  134789. ** example, assuming the inputs:
  134790. **
  134791. ** aIdx = { 0, 1, 2, 3 }
  134792. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  134793. **
  134794. ** this function sets the aIdx array to contain:
  134795. **
  134796. ** aIdx = { 0, 1, 2, 3 }
  134797. **
  134798. ** The aSpare array is used as temporary working space by the
  134799. ** sorting algorithm.
  134800. */
  134801. static void SortByDistance(
  134802. int *aIdx,
  134803. int nIdx,
  134804. RtreeDValue *aDistance,
  134805. int *aSpare
  134806. ){
  134807. if( nIdx>1 ){
  134808. int iLeft = 0;
  134809. int iRight = 0;
  134810. int nLeft = nIdx/2;
  134811. int nRight = nIdx-nLeft;
  134812. int *aLeft = aIdx;
  134813. int *aRight = &aIdx[nLeft];
  134814. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  134815. SortByDistance(aRight, nRight, aDistance, aSpare);
  134816. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  134817. aLeft = aSpare;
  134818. while( iLeft<nLeft || iRight<nRight ){
  134819. if( iLeft==nLeft ){
  134820. aIdx[iLeft+iRight] = aRight[iRight];
  134821. iRight++;
  134822. }else if( iRight==nRight ){
  134823. aIdx[iLeft+iRight] = aLeft[iLeft];
  134824. iLeft++;
  134825. }else{
  134826. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  134827. RtreeDValue fRight = aDistance[aRight[iRight]];
  134828. if( fLeft<fRight ){
  134829. aIdx[iLeft+iRight] = aLeft[iLeft];
  134830. iLeft++;
  134831. }else{
  134832. aIdx[iLeft+iRight] = aRight[iRight];
  134833. iRight++;
  134834. }
  134835. }
  134836. }
  134837. #if 0
  134838. /* Check that the sort worked */
  134839. {
  134840. int jj;
  134841. for(jj=1; jj<nIdx; jj++){
  134842. RtreeDValue left = aDistance[aIdx[jj-1]];
  134843. RtreeDValue right = aDistance[aIdx[jj]];
  134844. assert( left<=right );
  134845. }
  134846. }
  134847. #endif
  134848. }
  134849. }
  134850. /*
  134851. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  134852. ** nIdx. The aIdx array contains the set of integers from 0 to
  134853. ** (nIdx-1) in no particular order. This function sorts the values
  134854. ** in aIdx according to dimension iDim of the cells in aCell. The
  134855. ** minimum value of dimension iDim is considered first, the
  134856. ** maximum used to break ties.
  134857. **
  134858. ** The aSpare array is used as temporary working space by the
  134859. ** sorting algorithm.
  134860. */
  134861. static void SortByDimension(
  134862. Rtree *pRtree,
  134863. int *aIdx,
  134864. int nIdx,
  134865. int iDim,
  134866. RtreeCell *aCell,
  134867. int *aSpare
  134868. ){
  134869. if( nIdx>1 ){
  134870. int iLeft = 0;
  134871. int iRight = 0;
  134872. int nLeft = nIdx/2;
  134873. int nRight = nIdx-nLeft;
  134874. int *aLeft = aIdx;
  134875. int *aRight = &aIdx[nLeft];
  134876. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  134877. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  134878. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  134879. aLeft = aSpare;
  134880. while( iLeft<nLeft || iRight<nRight ){
  134881. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  134882. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  134883. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  134884. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  134885. if( (iLeft!=nLeft) && ((iRight==nRight)
  134886. || (xleft1<xright1)
  134887. || (xleft1==xright1 && xleft2<xright2)
  134888. )){
  134889. aIdx[iLeft+iRight] = aLeft[iLeft];
  134890. iLeft++;
  134891. }else{
  134892. aIdx[iLeft+iRight] = aRight[iRight];
  134893. iRight++;
  134894. }
  134895. }
  134896. #if 0
  134897. /* Check that the sort worked */
  134898. {
  134899. int jj;
  134900. for(jj=1; jj<nIdx; jj++){
  134901. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  134902. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  134903. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  134904. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  134905. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  134906. }
  134907. }
  134908. #endif
  134909. }
  134910. }
  134911. #if VARIANT_RSTARTREE_SPLIT
  134912. /*
  134913. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  134914. */
  134915. static int splitNodeStartree(
  134916. Rtree *pRtree,
  134917. RtreeCell *aCell,
  134918. int nCell,
  134919. RtreeNode *pLeft,
  134920. RtreeNode *pRight,
  134921. RtreeCell *pBboxLeft,
  134922. RtreeCell *pBboxRight
  134923. ){
  134924. int **aaSorted;
  134925. int *aSpare;
  134926. int ii;
  134927. int iBestDim = 0;
  134928. int iBestSplit = 0;
  134929. RtreeDValue fBestMargin = 0.0;
  134930. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  134931. aaSorted = (int **)sqlite3_malloc(nByte);
  134932. if( !aaSorted ){
  134933. return SQLITE_NOMEM;
  134934. }
  134935. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  134936. memset(aaSorted, 0, nByte);
  134937. for(ii=0; ii<pRtree->nDim; ii++){
  134938. int jj;
  134939. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  134940. for(jj=0; jj<nCell; jj++){
  134941. aaSorted[ii][jj] = jj;
  134942. }
  134943. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  134944. }
  134945. for(ii=0; ii<pRtree->nDim; ii++){
  134946. RtreeDValue margin = 0.0;
  134947. RtreeDValue fBestOverlap = 0.0;
  134948. RtreeDValue fBestArea = 0.0;
  134949. int iBestLeft = 0;
  134950. int nLeft;
  134951. for(
  134952. nLeft=RTREE_MINCELLS(pRtree);
  134953. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  134954. nLeft++
  134955. ){
  134956. RtreeCell left;
  134957. RtreeCell right;
  134958. int kk;
  134959. RtreeDValue overlap;
  134960. RtreeDValue area;
  134961. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  134962. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  134963. for(kk=1; kk<(nCell-1); kk++){
  134964. if( kk<nLeft ){
  134965. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  134966. }else{
  134967. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  134968. }
  134969. }
  134970. margin += cellMargin(pRtree, &left);
  134971. margin += cellMargin(pRtree, &right);
  134972. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  134973. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  134974. if( (nLeft==RTREE_MINCELLS(pRtree))
  134975. || (overlap<fBestOverlap)
  134976. || (overlap==fBestOverlap && area<fBestArea)
  134977. ){
  134978. iBestLeft = nLeft;
  134979. fBestOverlap = overlap;
  134980. fBestArea = area;
  134981. }
  134982. }
  134983. if( ii==0 || margin<fBestMargin ){
  134984. iBestDim = ii;
  134985. fBestMargin = margin;
  134986. iBestSplit = iBestLeft;
  134987. }
  134988. }
  134989. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  134990. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  134991. for(ii=0; ii<nCell; ii++){
  134992. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  134993. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  134994. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  134995. nodeInsertCell(pRtree, pTarget, pCell);
  134996. cellUnion(pRtree, pBbox, pCell);
  134997. }
  134998. sqlite3_free(aaSorted);
  134999. return SQLITE_OK;
  135000. }
  135001. #endif
  135002. #if VARIANT_GUTTMAN_SPLIT
  135003. /*
  135004. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  135005. */
  135006. static int splitNodeGuttman(
  135007. Rtree *pRtree,
  135008. RtreeCell *aCell,
  135009. int nCell,
  135010. RtreeNode *pLeft,
  135011. RtreeNode *pRight,
  135012. RtreeCell *pBboxLeft,
  135013. RtreeCell *pBboxRight
  135014. ){
  135015. int iLeftSeed = 0;
  135016. int iRightSeed = 1;
  135017. int *aiUsed;
  135018. int i;
  135019. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  135020. if( !aiUsed ){
  135021. return SQLITE_NOMEM;
  135022. }
  135023. memset(aiUsed, 0, sizeof(int)*nCell);
  135024. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  135025. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  135026. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  135027. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  135028. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  135029. aiUsed[iLeftSeed] = 1;
  135030. aiUsed[iRightSeed] = 1;
  135031. for(i=nCell-2; i>0; i--){
  135032. RtreeCell *pNext;
  135033. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  135034. RtreeDValue diff =
  135035. cellGrowth(pRtree, pBboxLeft, pNext) -
  135036. cellGrowth(pRtree, pBboxRight, pNext)
  135037. ;
  135038. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  135039. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  135040. ){
  135041. nodeInsertCell(pRtree, pRight, pNext);
  135042. cellUnion(pRtree, pBboxRight, pNext);
  135043. }else{
  135044. nodeInsertCell(pRtree, pLeft, pNext);
  135045. cellUnion(pRtree, pBboxLeft, pNext);
  135046. }
  135047. }
  135048. sqlite3_free(aiUsed);
  135049. return SQLITE_OK;
  135050. }
  135051. #endif
  135052. static int updateMapping(
  135053. Rtree *pRtree,
  135054. i64 iRowid,
  135055. RtreeNode *pNode,
  135056. int iHeight
  135057. ){
  135058. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  135059. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  135060. if( iHeight>0 ){
  135061. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  135062. if( pChild ){
  135063. nodeRelease(pRtree, pChild->pParent);
  135064. nodeReference(pNode);
  135065. pChild->pParent = pNode;
  135066. }
  135067. }
  135068. return xSetMapping(pRtree, iRowid, pNode->iNode);
  135069. }
  135070. static int SplitNode(
  135071. Rtree *pRtree,
  135072. RtreeNode *pNode,
  135073. RtreeCell *pCell,
  135074. int iHeight
  135075. ){
  135076. int i;
  135077. int newCellIsRight = 0;
  135078. int rc = SQLITE_OK;
  135079. int nCell = NCELL(pNode);
  135080. RtreeCell *aCell;
  135081. int *aiUsed;
  135082. RtreeNode *pLeft = 0;
  135083. RtreeNode *pRight = 0;
  135084. RtreeCell leftbbox;
  135085. RtreeCell rightbbox;
  135086. /* Allocate an array and populate it with a copy of pCell and
  135087. ** all cells from node pLeft. Then zero the original node.
  135088. */
  135089. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  135090. if( !aCell ){
  135091. rc = SQLITE_NOMEM;
  135092. goto splitnode_out;
  135093. }
  135094. aiUsed = (int *)&aCell[nCell+1];
  135095. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  135096. for(i=0; i<nCell; i++){
  135097. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  135098. }
  135099. nodeZero(pRtree, pNode);
  135100. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  135101. nCell++;
  135102. if( pNode->iNode==1 ){
  135103. pRight = nodeNew(pRtree, pNode);
  135104. pLeft = nodeNew(pRtree, pNode);
  135105. pRtree->iDepth++;
  135106. pNode->isDirty = 1;
  135107. writeInt16(pNode->zData, pRtree->iDepth);
  135108. }else{
  135109. pLeft = pNode;
  135110. pRight = nodeNew(pRtree, pLeft->pParent);
  135111. nodeReference(pLeft);
  135112. }
  135113. if( !pLeft || !pRight ){
  135114. rc = SQLITE_NOMEM;
  135115. goto splitnode_out;
  135116. }
  135117. memset(pLeft->zData, 0, pRtree->iNodeSize);
  135118. memset(pRight->zData, 0, pRtree->iNodeSize);
  135119. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  135120. if( rc!=SQLITE_OK ){
  135121. goto splitnode_out;
  135122. }
  135123. /* Ensure both child nodes have node numbers assigned to them by calling
  135124. ** nodeWrite(). Node pRight always needs a node number, as it was created
  135125. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  135126. ** In this case avoid the all to nodeWrite().
  135127. */
  135128. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  135129. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  135130. ){
  135131. goto splitnode_out;
  135132. }
  135133. rightbbox.iRowid = pRight->iNode;
  135134. leftbbox.iRowid = pLeft->iNode;
  135135. if( pNode->iNode==1 ){
  135136. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  135137. if( rc!=SQLITE_OK ){
  135138. goto splitnode_out;
  135139. }
  135140. }else{
  135141. RtreeNode *pParent = pLeft->pParent;
  135142. int iCell;
  135143. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  135144. if( rc==SQLITE_OK ){
  135145. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  135146. rc = AdjustTree(pRtree, pParent, &leftbbox);
  135147. }
  135148. if( rc!=SQLITE_OK ){
  135149. goto splitnode_out;
  135150. }
  135151. }
  135152. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  135153. goto splitnode_out;
  135154. }
  135155. for(i=0; i<NCELL(pRight); i++){
  135156. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  135157. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  135158. if( iRowid==pCell->iRowid ){
  135159. newCellIsRight = 1;
  135160. }
  135161. if( rc!=SQLITE_OK ){
  135162. goto splitnode_out;
  135163. }
  135164. }
  135165. if( pNode->iNode==1 ){
  135166. for(i=0; i<NCELL(pLeft); i++){
  135167. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  135168. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  135169. if( rc!=SQLITE_OK ){
  135170. goto splitnode_out;
  135171. }
  135172. }
  135173. }else if( newCellIsRight==0 ){
  135174. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  135175. }
  135176. if( rc==SQLITE_OK ){
  135177. rc = nodeRelease(pRtree, pRight);
  135178. pRight = 0;
  135179. }
  135180. if( rc==SQLITE_OK ){
  135181. rc = nodeRelease(pRtree, pLeft);
  135182. pLeft = 0;
  135183. }
  135184. splitnode_out:
  135185. nodeRelease(pRtree, pRight);
  135186. nodeRelease(pRtree, pLeft);
  135187. sqlite3_free(aCell);
  135188. return rc;
  135189. }
  135190. /*
  135191. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  135192. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  135193. ** the pLeaf->pParent chain all the way up to the root node.
  135194. **
  135195. ** This operation is required when a row is deleted (or updated - an update
  135196. ** is implemented as a delete followed by an insert). SQLite provides the
  135197. ** rowid of the row to delete, which can be used to find the leaf on which
  135198. ** the entry resides (argument pLeaf). Once the leaf is located, this
  135199. ** function is called to determine its ancestry.
  135200. */
  135201. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  135202. int rc = SQLITE_OK;
  135203. RtreeNode *pChild = pLeaf;
  135204. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  135205. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  135206. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  135207. rc = sqlite3_step(pRtree->pReadParent);
  135208. if( rc==SQLITE_ROW ){
  135209. RtreeNode *pTest; /* Used to test for reference loops */
  135210. i64 iNode; /* Node number of parent node */
  135211. /* Before setting pChild->pParent, test that we are not creating a
  135212. ** loop of references (as we would if, say, pChild==pParent). We don't
  135213. ** want to do this as it leads to a memory leak when trying to delete
  135214. ** the referenced counted node structures.
  135215. */
  135216. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  135217. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  135218. if( !pTest ){
  135219. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  135220. }
  135221. }
  135222. rc = sqlite3_reset(pRtree->pReadParent);
  135223. if( rc==SQLITE_OK ) rc = rc2;
  135224. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  135225. pChild = pChild->pParent;
  135226. }
  135227. return rc;
  135228. }
  135229. static int deleteCell(Rtree *, RtreeNode *, int, int);
  135230. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  135231. int rc;
  135232. int rc2;
  135233. RtreeNode *pParent = 0;
  135234. int iCell;
  135235. assert( pNode->nRef==1 );
  135236. /* Remove the entry in the parent cell. */
  135237. rc = nodeParentIndex(pRtree, pNode, &iCell);
  135238. if( rc==SQLITE_OK ){
  135239. pParent = pNode->pParent;
  135240. pNode->pParent = 0;
  135241. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  135242. }
  135243. rc2 = nodeRelease(pRtree, pParent);
  135244. if( rc==SQLITE_OK ){
  135245. rc = rc2;
  135246. }
  135247. if( rc!=SQLITE_OK ){
  135248. return rc;
  135249. }
  135250. /* Remove the xxx_node entry. */
  135251. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  135252. sqlite3_step(pRtree->pDeleteNode);
  135253. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  135254. return rc;
  135255. }
  135256. /* Remove the xxx_parent entry. */
  135257. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  135258. sqlite3_step(pRtree->pDeleteParent);
  135259. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  135260. return rc;
  135261. }
  135262. /* Remove the node from the in-memory hash table and link it into
  135263. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  135264. */
  135265. nodeHashDelete(pRtree, pNode);
  135266. pNode->iNode = iHeight;
  135267. pNode->pNext = pRtree->pDeleted;
  135268. pNode->nRef++;
  135269. pRtree->pDeleted = pNode;
  135270. return SQLITE_OK;
  135271. }
  135272. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  135273. RtreeNode *pParent = pNode->pParent;
  135274. int rc = SQLITE_OK;
  135275. if( pParent ){
  135276. int ii;
  135277. int nCell = NCELL(pNode);
  135278. RtreeCell box; /* Bounding box for pNode */
  135279. nodeGetCell(pRtree, pNode, 0, &box);
  135280. for(ii=1; ii<nCell; ii++){
  135281. RtreeCell cell;
  135282. nodeGetCell(pRtree, pNode, ii, &cell);
  135283. cellUnion(pRtree, &box, &cell);
  135284. }
  135285. box.iRowid = pNode->iNode;
  135286. rc = nodeParentIndex(pRtree, pNode, &ii);
  135287. if( rc==SQLITE_OK ){
  135288. nodeOverwriteCell(pRtree, pParent, &box, ii);
  135289. rc = fixBoundingBox(pRtree, pParent);
  135290. }
  135291. }
  135292. return rc;
  135293. }
  135294. /*
  135295. ** Delete the cell at index iCell of node pNode. After removing the
  135296. ** cell, adjust the r-tree data structure if required.
  135297. */
  135298. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  135299. RtreeNode *pParent;
  135300. int rc;
  135301. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  135302. return rc;
  135303. }
  135304. /* Remove the cell from the node. This call just moves bytes around
  135305. ** the in-memory node image, so it cannot fail.
  135306. */
  135307. nodeDeleteCell(pRtree, pNode, iCell);
  135308. /* If the node is not the tree root and now has less than the minimum
  135309. ** number of cells, remove it from the tree. Otherwise, update the
  135310. ** cell in the parent node so that it tightly contains the updated
  135311. ** node.
  135312. */
  135313. pParent = pNode->pParent;
  135314. assert( pParent || pNode->iNode==1 );
  135315. if( pParent ){
  135316. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  135317. rc = removeNode(pRtree, pNode, iHeight);
  135318. }else{
  135319. rc = fixBoundingBox(pRtree, pNode);
  135320. }
  135321. }
  135322. return rc;
  135323. }
  135324. static int Reinsert(
  135325. Rtree *pRtree,
  135326. RtreeNode *pNode,
  135327. RtreeCell *pCell,
  135328. int iHeight
  135329. ){
  135330. int *aOrder;
  135331. int *aSpare;
  135332. RtreeCell *aCell;
  135333. RtreeDValue *aDistance;
  135334. int nCell;
  135335. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  135336. int iDim;
  135337. int ii;
  135338. int rc = SQLITE_OK;
  135339. int n;
  135340. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  135341. nCell = NCELL(pNode)+1;
  135342. n = (nCell+1)&(~1);
  135343. /* Allocate the buffers used by this operation. The allocation is
  135344. ** relinquished before this function returns.
  135345. */
  135346. aCell = (RtreeCell *)sqlite3_malloc(n * (
  135347. sizeof(RtreeCell) + /* aCell array */
  135348. sizeof(int) + /* aOrder array */
  135349. sizeof(int) + /* aSpare array */
  135350. sizeof(RtreeDValue) /* aDistance array */
  135351. ));
  135352. if( !aCell ){
  135353. return SQLITE_NOMEM;
  135354. }
  135355. aOrder = (int *)&aCell[n];
  135356. aSpare = (int *)&aOrder[n];
  135357. aDistance = (RtreeDValue *)&aSpare[n];
  135358. for(ii=0; ii<nCell; ii++){
  135359. if( ii==(nCell-1) ){
  135360. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  135361. }else{
  135362. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  135363. }
  135364. aOrder[ii] = ii;
  135365. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135366. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  135367. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  135368. }
  135369. }
  135370. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135371. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  135372. }
  135373. for(ii=0; ii<nCell; ii++){
  135374. aDistance[ii] = 0.0;
  135375. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135376. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  135377. DCOORD(aCell[ii].aCoord[iDim*2]));
  135378. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  135379. }
  135380. }
  135381. SortByDistance(aOrder, nCell, aDistance, aSpare);
  135382. nodeZero(pRtree, pNode);
  135383. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  135384. RtreeCell *p = &aCell[aOrder[ii]];
  135385. nodeInsertCell(pRtree, pNode, p);
  135386. if( p->iRowid==pCell->iRowid ){
  135387. if( iHeight==0 ){
  135388. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  135389. }else{
  135390. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  135391. }
  135392. }
  135393. }
  135394. if( rc==SQLITE_OK ){
  135395. rc = fixBoundingBox(pRtree, pNode);
  135396. }
  135397. for(; rc==SQLITE_OK && ii<nCell; ii++){
  135398. /* Find a node to store this cell in. pNode->iNode currently contains
  135399. ** the height of the sub-tree headed by the cell.
  135400. */
  135401. RtreeNode *pInsert;
  135402. RtreeCell *p = &aCell[aOrder[ii]];
  135403. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  135404. if( rc==SQLITE_OK ){
  135405. int rc2;
  135406. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  135407. rc2 = nodeRelease(pRtree, pInsert);
  135408. if( rc==SQLITE_OK ){
  135409. rc = rc2;
  135410. }
  135411. }
  135412. }
  135413. sqlite3_free(aCell);
  135414. return rc;
  135415. }
  135416. /*
  135417. ** Insert cell pCell into node pNode. Node pNode is the head of a
  135418. ** subtree iHeight high (leaf nodes have iHeight==0).
  135419. */
  135420. static int rtreeInsertCell(
  135421. Rtree *pRtree,
  135422. RtreeNode *pNode,
  135423. RtreeCell *pCell,
  135424. int iHeight
  135425. ){
  135426. int rc = SQLITE_OK;
  135427. if( iHeight>0 ){
  135428. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  135429. if( pChild ){
  135430. nodeRelease(pRtree, pChild->pParent);
  135431. nodeReference(pNode);
  135432. pChild->pParent = pNode;
  135433. }
  135434. }
  135435. if( nodeInsertCell(pRtree, pNode, pCell) ){
  135436. #if VARIANT_RSTARTREE_REINSERT
  135437. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  135438. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  135439. }else{
  135440. pRtree->iReinsertHeight = iHeight;
  135441. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  135442. }
  135443. #else
  135444. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  135445. #endif
  135446. }else{
  135447. rc = AdjustTree(pRtree, pNode, pCell);
  135448. if( rc==SQLITE_OK ){
  135449. if( iHeight==0 ){
  135450. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  135451. }else{
  135452. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  135453. }
  135454. }
  135455. }
  135456. return rc;
  135457. }
  135458. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  135459. int ii;
  135460. int rc = SQLITE_OK;
  135461. int nCell = NCELL(pNode);
  135462. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  135463. RtreeNode *pInsert;
  135464. RtreeCell cell;
  135465. nodeGetCell(pRtree, pNode, ii, &cell);
  135466. /* Find a node to store this cell in. pNode->iNode currently contains
  135467. ** the height of the sub-tree headed by the cell.
  135468. */
  135469. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  135470. if( rc==SQLITE_OK ){
  135471. int rc2;
  135472. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  135473. rc2 = nodeRelease(pRtree, pInsert);
  135474. if( rc==SQLITE_OK ){
  135475. rc = rc2;
  135476. }
  135477. }
  135478. }
  135479. return rc;
  135480. }
  135481. /*
  135482. ** Select a currently unused rowid for a new r-tree record.
  135483. */
  135484. static int newRowid(Rtree *pRtree, i64 *piRowid){
  135485. int rc;
  135486. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  135487. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  135488. sqlite3_step(pRtree->pWriteRowid);
  135489. rc = sqlite3_reset(pRtree->pWriteRowid);
  135490. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  135491. return rc;
  135492. }
  135493. /*
  135494. ** Remove the entry with rowid=iDelete from the r-tree structure.
  135495. */
  135496. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  135497. int rc; /* Return code */
  135498. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  135499. int iCell; /* Index of iDelete cell in pLeaf */
  135500. RtreeNode *pRoot; /* Root node of rtree structure */
  135501. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  135502. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  135503. /* Obtain a reference to the leaf node that contains the entry
  135504. ** about to be deleted.
  135505. */
  135506. if( rc==SQLITE_OK ){
  135507. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  135508. }
  135509. /* Delete the cell in question from the leaf node. */
  135510. if( rc==SQLITE_OK ){
  135511. int rc2;
  135512. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  135513. if( rc==SQLITE_OK ){
  135514. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  135515. }
  135516. rc2 = nodeRelease(pRtree, pLeaf);
  135517. if( rc==SQLITE_OK ){
  135518. rc = rc2;
  135519. }
  135520. }
  135521. /* Delete the corresponding entry in the <rtree>_rowid table. */
  135522. if( rc==SQLITE_OK ){
  135523. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  135524. sqlite3_step(pRtree->pDeleteRowid);
  135525. rc = sqlite3_reset(pRtree->pDeleteRowid);
  135526. }
  135527. /* Check if the root node now has exactly one child. If so, remove
  135528. ** it, schedule the contents of the child for reinsertion and
  135529. ** reduce the tree height by one.
  135530. **
  135531. ** This is equivalent to copying the contents of the child into
  135532. ** the root node (the operation that Gutman's paper says to perform
  135533. ** in this scenario).
  135534. */
  135535. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  135536. int rc2;
  135537. RtreeNode *pChild;
  135538. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  135539. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  135540. if( rc==SQLITE_OK ){
  135541. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  135542. }
  135543. rc2 = nodeRelease(pRtree, pChild);
  135544. if( rc==SQLITE_OK ) rc = rc2;
  135545. if( rc==SQLITE_OK ){
  135546. pRtree->iDepth--;
  135547. writeInt16(pRoot->zData, pRtree->iDepth);
  135548. pRoot->isDirty = 1;
  135549. }
  135550. }
  135551. /* Re-insert the contents of any underfull nodes removed from the tree. */
  135552. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  135553. if( rc==SQLITE_OK ){
  135554. rc = reinsertNodeContent(pRtree, pLeaf);
  135555. }
  135556. pRtree->pDeleted = pLeaf->pNext;
  135557. sqlite3_free(pLeaf);
  135558. }
  135559. /* Release the reference to the root node. */
  135560. if( rc==SQLITE_OK ){
  135561. rc = nodeRelease(pRtree, pRoot);
  135562. }else{
  135563. nodeRelease(pRtree, pRoot);
  135564. }
  135565. return rc;
  135566. }
  135567. /*
  135568. ** Rounding constants for float->double conversion.
  135569. */
  135570. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  135571. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  135572. #if !defined(SQLITE_RTREE_INT_ONLY)
  135573. /*
  135574. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  135575. ** while taking care to round toward negative or positive, respectively.
  135576. */
  135577. static RtreeValue rtreeValueDown(sqlite3_value *v){
  135578. double d = sqlite3_value_double(v);
  135579. float f = (float)d;
  135580. if( f>d ){
  135581. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  135582. }
  135583. return f;
  135584. }
  135585. static RtreeValue rtreeValueUp(sqlite3_value *v){
  135586. double d = sqlite3_value_double(v);
  135587. float f = (float)d;
  135588. if( f<d ){
  135589. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  135590. }
  135591. return f;
  135592. }
  135593. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  135594. /*
  135595. ** The xUpdate method for rtree module virtual tables.
  135596. */
  135597. static int rtreeUpdate(
  135598. sqlite3_vtab *pVtab,
  135599. int nData,
  135600. sqlite3_value **azData,
  135601. sqlite_int64 *pRowid
  135602. ){
  135603. Rtree *pRtree = (Rtree *)pVtab;
  135604. int rc = SQLITE_OK;
  135605. RtreeCell cell; /* New cell to insert if nData>1 */
  135606. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  135607. rtreeReference(pRtree);
  135608. assert(nData>=1);
  135609. /* Constraint handling. A write operation on an r-tree table may return
  135610. ** SQLITE_CONSTRAINT for two reasons:
  135611. **
  135612. ** 1. A duplicate rowid value, or
  135613. ** 2. The supplied data violates the "x2>=x1" constraint.
  135614. **
  135615. ** In the first case, if the conflict-handling mode is REPLACE, then
  135616. ** the conflicting row can be removed before proceeding. In the second
  135617. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  135618. ** conflict-handling mode specified by the user.
  135619. */
  135620. if( nData>1 ){
  135621. int ii;
  135622. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  135623. assert( nData==(pRtree->nDim*2 + 3) );
  135624. #ifndef SQLITE_RTREE_INT_ONLY
  135625. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  135626. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  135627. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  135628. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  135629. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  135630. rc = SQLITE_CONSTRAINT;
  135631. goto constraint;
  135632. }
  135633. }
  135634. }else
  135635. #endif
  135636. {
  135637. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  135638. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  135639. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  135640. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  135641. rc = SQLITE_CONSTRAINT;
  135642. goto constraint;
  135643. }
  135644. }
  135645. }
  135646. /* If a rowid value was supplied, check if it is already present in
  135647. ** the table. If so, the constraint has failed. */
  135648. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  135649. cell.iRowid = sqlite3_value_int64(azData[2]);
  135650. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  135651. || sqlite3_value_int64(azData[0])!=cell.iRowid
  135652. ){
  135653. int steprc;
  135654. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  135655. steprc = sqlite3_step(pRtree->pReadRowid);
  135656. rc = sqlite3_reset(pRtree->pReadRowid);
  135657. if( SQLITE_ROW==steprc ){
  135658. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  135659. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  135660. }else{
  135661. rc = SQLITE_CONSTRAINT;
  135662. goto constraint;
  135663. }
  135664. }
  135665. }
  135666. bHaveRowid = 1;
  135667. }
  135668. }
  135669. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  135670. ** record to delete from the r-tree table. The following block does
  135671. ** just that.
  135672. */
  135673. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  135674. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  135675. }
  135676. /* If the azData[] array contains more than one element, elements
  135677. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  135678. ** the r-tree structure.
  135679. */
  135680. if( rc==SQLITE_OK && nData>1 ){
  135681. /* Insert the new record into the r-tree */
  135682. RtreeNode *pLeaf = 0;
  135683. /* Figure out the rowid of the new row. */
  135684. if( bHaveRowid==0 ){
  135685. rc = newRowid(pRtree, &cell.iRowid);
  135686. }
  135687. *pRowid = cell.iRowid;
  135688. if( rc==SQLITE_OK ){
  135689. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  135690. }
  135691. if( rc==SQLITE_OK ){
  135692. int rc2;
  135693. pRtree->iReinsertHeight = -1;
  135694. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  135695. rc2 = nodeRelease(pRtree, pLeaf);
  135696. if( rc==SQLITE_OK ){
  135697. rc = rc2;
  135698. }
  135699. }
  135700. }
  135701. constraint:
  135702. rtreeRelease(pRtree);
  135703. return rc;
  135704. }
  135705. /*
  135706. ** The xRename method for rtree module virtual tables.
  135707. */
  135708. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  135709. Rtree *pRtree = (Rtree *)pVtab;
  135710. int rc = SQLITE_NOMEM;
  135711. char *zSql = sqlite3_mprintf(
  135712. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  135713. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  135714. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  135715. , pRtree->zDb, pRtree->zName, zNewName
  135716. , pRtree->zDb, pRtree->zName, zNewName
  135717. , pRtree->zDb, pRtree->zName, zNewName
  135718. );
  135719. if( zSql ){
  135720. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  135721. sqlite3_free(zSql);
  135722. }
  135723. return rc;
  135724. }
  135725. static sqlite3_module rtreeModule = {
  135726. 0, /* iVersion */
  135727. rtreeCreate, /* xCreate - create a table */
  135728. rtreeConnect, /* xConnect - connect to an existing table */
  135729. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  135730. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  135731. rtreeDestroy, /* xDestroy - Drop a table */
  135732. rtreeOpen, /* xOpen - open a cursor */
  135733. rtreeClose, /* xClose - close a cursor */
  135734. rtreeFilter, /* xFilter - configure scan constraints */
  135735. rtreeNext, /* xNext - advance a cursor */
  135736. rtreeEof, /* xEof */
  135737. rtreeColumn, /* xColumn - read data */
  135738. rtreeRowid, /* xRowid - read data */
  135739. rtreeUpdate, /* xUpdate - write data */
  135740. 0, /* xBegin - begin transaction */
  135741. 0, /* xSync - sync transaction */
  135742. 0, /* xCommit - commit transaction */
  135743. 0, /* xRollback - rollback transaction */
  135744. 0, /* xFindFunction - function overloading */
  135745. rtreeRename, /* xRename - rename the table */
  135746. 0, /* xSavepoint */
  135747. 0, /* xRelease */
  135748. 0 /* xRollbackTo */
  135749. };
  135750. static int rtreeSqlInit(
  135751. Rtree *pRtree,
  135752. sqlite3 *db,
  135753. const char *zDb,
  135754. const char *zPrefix,
  135755. int isCreate
  135756. ){
  135757. int rc = SQLITE_OK;
  135758. #define N_STATEMENT 9
  135759. static const char *azSql[N_STATEMENT] = {
  135760. /* Read and write the xxx_node table */
  135761. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  135762. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  135763. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  135764. /* Read and write the xxx_rowid table */
  135765. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  135766. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  135767. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  135768. /* Read and write the xxx_parent table */
  135769. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  135770. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  135771. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  135772. };
  135773. sqlite3_stmt **appStmt[N_STATEMENT];
  135774. int i;
  135775. pRtree->db = db;
  135776. if( isCreate ){
  135777. char *zCreate = sqlite3_mprintf(
  135778. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  135779. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  135780. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  135781. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  135782. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  135783. );
  135784. if( !zCreate ){
  135785. return SQLITE_NOMEM;
  135786. }
  135787. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  135788. sqlite3_free(zCreate);
  135789. if( rc!=SQLITE_OK ){
  135790. return rc;
  135791. }
  135792. }
  135793. appStmt[0] = &pRtree->pReadNode;
  135794. appStmt[1] = &pRtree->pWriteNode;
  135795. appStmt[2] = &pRtree->pDeleteNode;
  135796. appStmt[3] = &pRtree->pReadRowid;
  135797. appStmt[4] = &pRtree->pWriteRowid;
  135798. appStmt[5] = &pRtree->pDeleteRowid;
  135799. appStmt[6] = &pRtree->pReadParent;
  135800. appStmt[7] = &pRtree->pWriteParent;
  135801. appStmt[8] = &pRtree->pDeleteParent;
  135802. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  135803. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  135804. if( zSql ){
  135805. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  135806. }else{
  135807. rc = SQLITE_NOMEM;
  135808. }
  135809. sqlite3_free(zSql);
  135810. }
  135811. return rc;
  135812. }
  135813. /*
  135814. ** The second argument to this function contains the text of an SQL statement
  135815. ** that returns a single integer value. The statement is compiled and executed
  135816. ** using database connection db. If successful, the integer value returned
  135817. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  135818. ** code is returned and the value of *piVal after returning is not defined.
  135819. */
  135820. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  135821. int rc = SQLITE_NOMEM;
  135822. if( zSql ){
  135823. sqlite3_stmt *pStmt = 0;
  135824. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  135825. if( rc==SQLITE_OK ){
  135826. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135827. *piVal = sqlite3_column_int(pStmt, 0);
  135828. }
  135829. rc = sqlite3_finalize(pStmt);
  135830. }
  135831. }
  135832. return rc;
  135833. }
  135834. /*
  135835. ** This function is called from within the xConnect() or xCreate() method to
  135836. ** determine the node-size used by the rtree table being created or connected
  135837. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  135838. ** Otherwise, an SQLite error code is returned.
  135839. **
  135840. ** If this function is being called as part of an xConnect(), then the rtree
  135841. ** table already exists. In this case the node-size is determined by inspecting
  135842. ** the root node of the tree.
  135843. **
  135844. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  135845. ** This ensures that each node is stored on a single database page. If the
  135846. ** database page-size is so large that more than RTREE_MAXCELLS entries
  135847. ** would fit in a single node, use a smaller node-size.
  135848. */
  135849. static int getNodeSize(
  135850. sqlite3 *db, /* Database handle */
  135851. Rtree *pRtree, /* Rtree handle */
  135852. int isCreate, /* True for xCreate, false for xConnect */
  135853. char **pzErr /* OUT: Error message, if any */
  135854. ){
  135855. int rc;
  135856. char *zSql;
  135857. if( isCreate ){
  135858. int iPageSize = 0;
  135859. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  135860. rc = getIntFromStmt(db, zSql, &iPageSize);
  135861. if( rc==SQLITE_OK ){
  135862. pRtree->iNodeSize = iPageSize-64;
  135863. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  135864. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  135865. }
  135866. }else{
  135867. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135868. }
  135869. }else{
  135870. zSql = sqlite3_mprintf(
  135871. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  135872. pRtree->zDb, pRtree->zName
  135873. );
  135874. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  135875. if( rc!=SQLITE_OK ){
  135876. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135877. }
  135878. }
  135879. sqlite3_free(zSql);
  135880. return rc;
  135881. }
  135882. /*
  135883. ** This function is the implementation of both the xConnect and xCreate
  135884. ** methods of the r-tree virtual table.
  135885. **
  135886. ** argv[0] -> module name
  135887. ** argv[1] -> database name
  135888. ** argv[2] -> table name
  135889. ** argv[...] -> column names...
  135890. */
  135891. static int rtreeInit(
  135892. sqlite3 *db, /* Database connection */
  135893. void *pAux, /* One of the RTREE_COORD_* constants */
  135894. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  135895. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  135896. char **pzErr, /* OUT: Error message, if any */
  135897. int isCreate /* True for xCreate, false for xConnect */
  135898. ){
  135899. int rc = SQLITE_OK;
  135900. Rtree *pRtree;
  135901. int nDb; /* Length of string argv[1] */
  135902. int nName; /* Length of string argv[2] */
  135903. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  135904. const char *aErrMsg[] = {
  135905. 0, /* 0 */
  135906. "Wrong number of columns for an rtree table", /* 1 */
  135907. "Too few columns for an rtree table", /* 2 */
  135908. "Too many columns for an rtree table" /* 3 */
  135909. };
  135910. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  135911. if( aErrMsg[iErr] ){
  135912. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  135913. return SQLITE_ERROR;
  135914. }
  135915. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  135916. /* Allocate the sqlite3_vtab structure */
  135917. nDb = (int)strlen(argv[1]);
  135918. nName = (int)strlen(argv[2]);
  135919. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  135920. if( !pRtree ){
  135921. return SQLITE_NOMEM;
  135922. }
  135923. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  135924. pRtree->nBusy = 1;
  135925. pRtree->base.pModule = &rtreeModule;
  135926. pRtree->zDb = (char *)&pRtree[1];
  135927. pRtree->zName = &pRtree->zDb[nDb+1];
  135928. pRtree->nDim = (argc-4)/2;
  135929. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  135930. pRtree->eCoordType = eCoordType;
  135931. memcpy(pRtree->zDb, argv[1], nDb);
  135932. memcpy(pRtree->zName, argv[2], nName);
  135933. /* Figure out the node size to use. */
  135934. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  135935. /* Create/Connect to the underlying relational database schema. If
  135936. ** that is successful, call sqlite3_declare_vtab() to configure
  135937. ** the r-tree table schema.
  135938. */
  135939. if( rc==SQLITE_OK ){
  135940. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  135941. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135942. }else{
  135943. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  135944. char *zTmp;
  135945. int ii;
  135946. for(ii=4; zSql && ii<argc; ii++){
  135947. zTmp = zSql;
  135948. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  135949. sqlite3_free(zTmp);
  135950. }
  135951. if( zSql ){
  135952. zTmp = zSql;
  135953. zSql = sqlite3_mprintf("%s);", zTmp);
  135954. sqlite3_free(zTmp);
  135955. }
  135956. if( !zSql ){
  135957. rc = SQLITE_NOMEM;
  135958. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  135959. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135960. }
  135961. sqlite3_free(zSql);
  135962. }
  135963. }
  135964. if( rc==SQLITE_OK ){
  135965. *ppVtab = (sqlite3_vtab *)pRtree;
  135966. }else{
  135967. rtreeRelease(pRtree);
  135968. }
  135969. return rc;
  135970. }
  135971. /*
  135972. ** Implementation of a scalar function that decodes r-tree nodes to
  135973. ** human readable strings. This can be used for debugging and analysis.
  135974. **
  135975. ** The scalar function takes two arguments, a blob of data containing
  135976. ** an r-tree node, and the number of dimensions the r-tree indexes.
  135977. ** For a two-dimensional r-tree structure called "rt", to deserialize
  135978. ** all nodes, a statement like:
  135979. **
  135980. ** SELECT rtreenode(2, data) FROM rt_node;
  135981. **
  135982. ** The human readable string takes the form of a Tcl list with one
  135983. ** entry for each cell in the r-tree node. Each entry is itself a
  135984. ** list, containing the 8-byte rowid/pageno followed by the
  135985. ** <num-dimension>*2 coordinates.
  135986. */
  135987. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  135988. char *zText = 0;
  135989. RtreeNode node;
  135990. Rtree tree;
  135991. int ii;
  135992. UNUSED_PARAMETER(nArg);
  135993. memset(&node, 0, sizeof(RtreeNode));
  135994. memset(&tree, 0, sizeof(Rtree));
  135995. tree.nDim = sqlite3_value_int(apArg[0]);
  135996. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  135997. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  135998. for(ii=0; ii<NCELL(&node); ii++){
  135999. char zCell[512];
  136000. int nCell = 0;
  136001. RtreeCell cell;
  136002. int jj;
  136003. nodeGetCell(&tree, &node, ii, &cell);
  136004. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  136005. nCell = (int)strlen(zCell);
  136006. for(jj=0; jj<tree.nDim*2; jj++){
  136007. #ifndef SQLITE_RTREE_INT_ONLY
  136008. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  136009. (double)cell.aCoord[jj].f);
  136010. #else
  136011. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  136012. cell.aCoord[jj].i);
  136013. #endif
  136014. nCell = (int)strlen(zCell);
  136015. }
  136016. if( zText ){
  136017. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  136018. sqlite3_free(zText);
  136019. zText = zTextNew;
  136020. }else{
  136021. zText = sqlite3_mprintf("{%s}", zCell);
  136022. }
  136023. }
  136024. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  136025. }
  136026. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  136027. UNUSED_PARAMETER(nArg);
  136028. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  136029. || sqlite3_value_bytes(apArg[0])<2
  136030. ){
  136031. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  136032. }else{
  136033. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  136034. sqlite3_result_int(ctx, readInt16(zBlob));
  136035. }
  136036. }
  136037. /*
  136038. ** Register the r-tree module with database handle db. This creates the
  136039. ** virtual table module "rtree" and the debugging/analysis scalar
  136040. ** function "rtreenode".
  136041. */
  136042. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  136043. const int utf8 = SQLITE_UTF8;
  136044. int rc;
  136045. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  136046. if( rc==SQLITE_OK ){
  136047. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  136048. }
  136049. if( rc==SQLITE_OK ){
  136050. #ifdef SQLITE_RTREE_INT_ONLY
  136051. void *c = (void *)RTREE_COORD_INT32;
  136052. #else
  136053. void *c = (void *)RTREE_COORD_REAL32;
  136054. #endif
  136055. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  136056. }
  136057. if( rc==SQLITE_OK ){
  136058. void *c = (void *)RTREE_COORD_INT32;
  136059. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  136060. }
  136061. return rc;
  136062. }
  136063. /*
  136064. ** A version of sqlite3_free() that can be used as a callback. This is used
  136065. ** in two places - as the destructor for the blob value returned by the
  136066. ** invocation of a geometry function, and as the destructor for the geometry
  136067. ** functions themselves.
  136068. */
  136069. static void doSqlite3Free(void *p){
  136070. sqlite3_free(p);
  136071. }
  136072. /*
  136073. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  136074. ** scalar user function. This C function is the callback used for all such
  136075. ** registered SQL functions.
  136076. **
  136077. ** The scalar user functions return a blob that is interpreted by r-tree
  136078. ** table MATCH operators.
  136079. */
  136080. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  136081. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  136082. RtreeMatchArg *pBlob;
  136083. int nBlob;
  136084. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  136085. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  136086. if( !pBlob ){
  136087. sqlite3_result_error_nomem(ctx);
  136088. }else{
  136089. int i;
  136090. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  136091. pBlob->xGeom = pGeomCtx->xGeom;
  136092. pBlob->pContext = pGeomCtx->pContext;
  136093. pBlob->nParam = nArg;
  136094. for(i=0; i<nArg; i++){
  136095. #ifdef SQLITE_RTREE_INT_ONLY
  136096. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  136097. #else
  136098. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  136099. #endif
  136100. }
  136101. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  136102. }
  136103. }
  136104. /*
  136105. ** Register a new geometry function for use with the r-tree MATCH operator.
  136106. */
  136107. SQLITE_API int sqlite3_rtree_geometry_callback(
  136108. sqlite3 *db,
  136109. const char *zGeom,
  136110. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  136111. void *pContext
  136112. ){
  136113. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  136114. /* Allocate and populate the context object. */
  136115. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  136116. if( !pGeomCtx ) return SQLITE_NOMEM;
  136117. pGeomCtx->xGeom = xGeom;
  136118. pGeomCtx->pContext = pContext;
  136119. /* Create the new user-function. Register a destructor function to delete
  136120. ** the context object when it is no longer required. */
  136121. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  136122. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  136123. );
  136124. }
  136125. #if !SQLITE_CORE
  136126. #ifdef _WIN32
  136127. __declspec(dllexport)
  136128. #endif
  136129. SQLITE_API int sqlite3_rtree_init(
  136130. sqlite3 *db,
  136131. char **pzErrMsg,
  136132. const sqlite3_api_routines *pApi
  136133. ){
  136134. SQLITE_EXTENSION_INIT2(pApi)
  136135. return sqlite3RtreeInit(db);
  136136. }
  136137. #endif
  136138. #endif
  136139. /************** End of rtree.c ***********************************************/
  136140. /************** Begin file icu.c *********************************************/
  136141. /*
  136142. ** 2007 May 6
  136143. **
  136144. ** The author disclaims copyright to this source code. In place of
  136145. ** a legal notice, here is a blessing:
  136146. **
  136147. ** May you do good and not evil.
  136148. ** May you find forgiveness for yourself and forgive others.
  136149. ** May you share freely, never taking more than you give.
  136150. **
  136151. *************************************************************************
  136152. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  136153. **
  136154. ** This file implements an integration between the ICU library
  136155. ** ("International Components for Unicode", an open-source library
  136156. ** for handling unicode data) and SQLite. The integration uses
  136157. ** ICU to provide the following to SQLite:
  136158. **
  136159. ** * An implementation of the SQL regexp() function (and hence REGEXP
  136160. ** operator) using the ICU uregex_XX() APIs.
  136161. **
  136162. ** * Implementations of the SQL scalar upper() and lower() functions
  136163. ** for case mapping.
  136164. **
  136165. ** * Integration of ICU and SQLite collation sequences.
  136166. **
  136167. ** * An implementation of the LIKE operator that uses ICU to
  136168. ** provide case-independent matching.
  136169. */
  136170. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  136171. /* Include ICU headers */
  136172. #include <unicode/utypes.h>
  136173. #include <unicode/uregex.h>
  136174. #include <unicode/ustring.h>
  136175. #include <unicode/ucol.h>
  136176. /* #include <assert.h> */
  136177. #ifndef SQLITE_CORE
  136178. SQLITE_EXTENSION_INIT1
  136179. #else
  136180. #endif
  136181. /*
  136182. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  136183. ** operator.
  136184. */
  136185. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  136186. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  136187. #endif
  136188. /*
  136189. ** Version of sqlite3_free() that is always a function, never a macro.
  136190. */
  136191. static void xFree(void *p){
  136192. sqlite3_free(p);
  136193. }
  136194. /*
  136195. ** Compare two UTF-8 strings for equality where the first string is
  136196. ** a "LIKE" expression. Return true (1) if they are the same and
  136197. ** false (0) if they are different.
  136198. */
  136199. static int icuLikeCompare(
  136200. const uint8_t *zPattern, /* LIKE pattern */
  136201. const uint8_t *zString, /* The UTF-8 string to compare against */
  136202. const UChar32 uEsc /* The escape character */
  136203. ){
  136204. static const int MATCH_ONE = (UChar32)'_';
  136205. static const int MATCH_ALL = (UChar32)'%';
  136206. int iPattern = 0; /* Current byte index in zPattern */
  136207. int iString = 0; /* Current byte index in zString */
  136208. int prevEscape = 0; /* True if the previous character was uEsc */
  136209. while( zPattern[iPattern]!=0 ){
  136210. /* Read (and consume) the next character from the input pattern. */
  136211. UChar32 uPattern;
  136212. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  136213. assert(uPattern!=0);
  136214. /* There are now 4 possibilities:
  136215. **
  136216. ** 1. uPattern is an unescaped match-all character "%",
  136217. ** 2. uPattern is an unescaped match-one character "_",
  136218. ** 3. uPattern is an unescaped escape character, or
  136219. ** 4. uPattern is to be handled as an ordinary character
  136220. */
  136221. if( !prevEscape && uPattern==MATCH_ALL ){
  136222. /* Case 1. */
  136223. uint8_t c;
  136224. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  136225. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  136226. ** test string.
  136227. */
  136228. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  136229. if( c==MATCH_ONE ){
  136230. if( zString[iString]==0 ) return 0;
  136231. U8_FWD_1_UNSAFE(zString, iString);
  136232. }
  136233. iPattern++;
  136234. }
  136235. if( zPattern[iPattern]==0 ) return 1;
  136236. while( zString[iString] ){
  136237. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  136238. return 1;
  136239. }
  136240. U8_FWD_1_UNSAFE(zString, iString);
  136241. }
  136242. return 0;
  136243. }else if( !prevEscape && uPattern==MATCH_ONE ){
  136244. /* Case 2. */
  136245. if( zString[iString]==0 ) return 0;
  136246. U8_FWD_1_UNSAFE(zString, iString);
  136247. }else if( !prevEscape && uPattern==uEsc){
  136248. /* Case 3. */
  136249. prevEscape = 1;
  136250. }else{
  136251. /* Case 4. */
  136252. UChar32 uString;
  136253. U8_NEXT_UNSAFE(zString, iString, uString);
  136254. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  136255. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  136256. if( uString!=uPattern ){
  136257. return 0;
  136258. }
  136259. prevEscape = 0;
  136260. }
  136261. }
  136262. return zString[iString]==0;
  136263. }
  136264. /*
  136265. ** Implementation of the like() SQL function. This function implements
  136266. ** the build-in LIKE operator. The first argument to the function is the
  136267. ** pattern and the second argument is the string. So, the SQL statements:
  136268. **
  136269. ** A LIKE B
  136270. **
  136271. ** is implemented as like(B, A). If there is an escape character E,
  136272. **
  136273. ** A LIKE B ESCAPE E
  136274. **
  136275. ** is mapped to like(B, A, E).
  136276. */
  136277. static void icuLikeFunc(
  136278. sqlite3_context *context,
  136279. int argc,
  136280. sqlite3_value **argv
  136281. ){
  136282. const unsigned char *zA = sqlite3_value_text(argv[0]);
  136283. const unsigned char *zB = sqlite3_value_text(argv[1]);
  136284. UChar32 uEsc = 0;
  136285. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  136286. ** of deep recursion and N*N behavior in patternCompare().
  136287. */
  136288. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  136289. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  136290. return;
  136291. }
  136292. if( argc==3 ){
  136293. /* The escape character string must consist of a single UTF-8 character.
  136294. ** Otherwise, return an error.
  136295. */
  136296. int nE= sqlite3_value_bytes(argv[2]);
  136297. const unsigned char *zE = sqlite3_value_text(argv[2]);
  136298. int i = 0;
  136299. if( zE==0 ) return;
  136300. U8_NEXT(zE, i, nE, uEsc);
  136301. if( i!=nE){
  136302. sqlite3_result_error(context,
  136303. "ESCAPE expression must be a single character", -1);
  136304. return;
  136305. }
  136306. }
  136307. if( zA && zB ){
  136308. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  136309. }
  136310. }
  136311. /*
  136312. ** This function is called when an ICU function called from within
  136313. ** the implementation of an SQL scalar function returns an error.
  136314. **
  136315. ** The scalar function context passed as the first argument is
  136316. ** loaded with an error message based on the following two args.
  136317. */
  136318. static void icuFunctionError(
  136319. sqlite3_context *pCtx, /* SQLite scalar function context */
  136320. const char *zName, /* Name of ICU function that failed */
  136321. UErrorCode e /* Error code returned by ICU function */
  136322. ){
  136323. char zBuf[128];
  136324. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  136325. zBuf[127] = '\0';
  136326. sqlite3_result_error(pCtx, zBuf, -1);
  136327. }
  136328. /*
  136329. ** Function to delete compiled regexp objects. Registered as
  136330. ** a destructor function with sqlite3_set_auxdata().
  136331. */
  136332. static void icuRegexpDelete(void *p){
  136333. URegularExpression *pExpr = (URegularExpression *)p;
  136334. uregex_close(pExpr);
  136335. }
  136336. /*
  136337. ** Implementation of SQLite REGEXP operator. This scalar function takes
  136338. ** two arguments. The first is a regular expression pattern to compile
  136339. ** the second is a string to match against that pattern. If either
  136340. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  136341. ** is 1 if the string matches the pattern, or 0 otherwise.
  136342. **
  136343. ** SQLite maps the regexp() function to the regexp() operator such
  136344. ** that the following two are equivalent:
  136345. **
  136346. ** zString REGEXP zPattern
  136347. ** regexp(zPattern, zString)
  136348. **
  136349. ** Uses the following ICU regexp APIs:
  136350. **
  136351. ** uregex_open()
  136352. ** uregex_matches()
  136353. ** uregex_close()
  136354. */
  136355. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  136356. UErrorCode status = U_ZERO_ERROR;
  136357. URegularExpression *pExpr;
  136358. UBool res;
  136359. const UChar *zString = sqlite3_value_text16(apArg[1]);
  136360. (void)nArg; /* Unused parameter */
  136361. /* If the left hand side of the regexp operator is NULL,
  136362. ** then the result is also NULL.
  136363. */
  136364. if( !zString ){
  136365. return;
  136366. }
  136367. pExpr = sqlite3_get_auxdata(p, 0);
  136368. if( !pExpr ){
  136369. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  136370. if( !zPattern ){
  136371. return;
  136372. }
  136373. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  136374. if( U_SUCCESS(status) ){
  136375. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  136376. }else{
  136377. assert(!pExpr);
  136378. icuFunctionError(p, "uregex_open", status);
  136379. return;
  136380. }
  136381. }
  136382. /* Configure the text that the regular expression operates on. */
  136383. uregex_setText(pExpr, zString, -1, &status);
  136384. if( !U_SUCCESS(status) ){
  136385. icuFunctionError(p, "uregex_setText", status);
  136386. return;
  136387. }
  136388. /* Attempt the match */
  136389. res = uregex_matches(pExpr, 0, &status);
  136390. if( !U_SUCCESS(status) ){
  136391. icuFunctionError(p, "uregex_matches", status);
  136392. return;
  136393. }
  136394. /* Set the text that the regular expression operates on to a NULL
  136395. ** pointer. This is not really necessary, but it is tidier than
  136396. ** leaving the regular expression object configured with an invalid
  136397. ** pointer after this function returns.
  136398. */
  136399. uregex_setText(pExpr, 0, 0, &status);
  136400. /* Return 1 or 0. */
  136401. sqlite3_result_int(p, res ? 1 : 0);
  136402. }
  136403. /*
  136404. ** Implementations of scalar functions for case mapping - upper() and
  136405. ** lower(). Function upper() converts its input to upper-case (ABC).
  136406. ** Function lower() converts to lower-case (abc).
  136407. **
  136408. ** ICU provides two types of case mapping, "general" case mapping and
  136409. ** "language specific". Refer to ICU documentation for the differences
  136410. ** between the two.
  136411. **
  136412. ** To utilise "general" case mapping, the upper() or lower() scalar
  136413. ** functions are invoked with one argument:
  136414. **
  136415. ** upper('ABC') -> 'abc'
  136416. ** lower('abc') -> 'ABC'
  136417. **
  136418. ** To access ICU "language specific" case mapping, upper() or lower()
  136419. ** should be invoked with two arguments. The second argument is the name
  136420. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  136421. ** as the second argument is the same as invoking the 1 argument version
  136422. ** of upper() or lower().
  136423. **
  136424. ** lower('I', 'en_us') -> 'i'
  136425. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  136426. **
  136427. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  136428. */
  136429. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  136430. const UChar *zInput;
  136431. UChar *zOutput;
  136432. int nInput;
  136433. int nOutput;
  136434. UErrorCode status = U_ZERO_ERROR;
  136435. const char *zLocale = 0;
  136436. assert(nArg==1 || nArg==2);
  136437. if( nArg==2 ){
  136438. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  136439. }
  136440. zInput = sqlite3_value_text16(apArg[0]);
  136441. if( !zInput ){
  136442. return;
  136443. }
  136444. nInput = sqlite3_value_bytes16(apArg[0]);
  136445. nOutput = nInput * 2 + 2;
  136446. zOutput = sqlite3_malloc(nOutput);
  136447. if( !zOutput ){
  136448. return;
  136449. }
  136450. if( sqlite3_user_data(p) ){
  136451. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  136452. }else{
  136453. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  136454. }
  136455. if( !U_SUCCESS(status) ){
  136456. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  136457. return;
  136458. }
  136459. sqlite3_result_text16(p, zOutput, -1, xFree);
  136460. }
  136461. /*
  136462. ** Collation sequence destructor function. The pCtx argument points to
  136463. ** a UCollator structure previously allocated using ucol_open().
  136464. */
  136465. static void icuCollationDel(void *pCtx){
  136466. UCollator *p = (UCollator *)pCtx;
  136467. ucol_close(p);
  136468. }
  136469. /*
  136470. ** Collation sequence comparison function. The pCtx argument points to
  136471. ** a UCollator structure previously allocated using ucol_open().
  136472. */
  136473. static int icuCollationColl(
  136474. void *pCtx,
  136475. int nLeft,
  136476. const void *zLeft,
  136477. int nRight,
  136478. const void *zRight
  136479. ){
  136480. UCollationResult res;
  136481. UCollator *p = (UCollator *)pCtx;
  136482. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  136483. switch( res ){
  136484. case UCOL_LESS: return -1;
  136485. case UCOL_GREATER: return +1;
  136486. case UCOL_EQUAL: return 0;
  136487. }
  136488. assert(!"Unexpected return value from ucol_strcoll()");
  136489. return 0;
  136490. }
  136491. /*
  136492. ** Implementation of the scalar function icu_load_collation().
  136493. **
  136494. ** This scalar function is used to add ICU collation based collation
  136495. ** types to an SQLite database connection. It is intended to be called
  136496. ** as follows:
  136497. **
  136498. ** SELECT icu_load_collation(<locale>, <collation-name>);
  136499. **
  136500. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  136501. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  136502. ** collation sequence to create.
  136503. */
  136504. static void icuLoadCollation(
  136505. sqlite3_context *p,
  136506. int nArg,
  136507. sqlite3_value **apArg
  136508. ){
  136509. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  136510. UErrorCode status = U_ZERO_ERROR;
  136511. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  136512. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  136513. UCollator *pUCollator; /* ICU library collation object */
  136514. int rc; /* Return code from sqlite3_create_collation_x() */
  136515. assert(nArg==2);
  136516. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  136517. zName = (const char *)sqlite3_value_text(apArg[1]);
  136518. if( !zLocale || !zName ){
  136519. return;
  136520. }
  136521. pUCollator = ucol_open(zLocale, &status);
  136522. if( !U_SUCCESS(status) ){
  136523. icuFunctionError(p, "ucol_open", status);
  136524. return;
  136525. }
  136526. assert(p);
  136527. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  136528. icuCollationColl, icuCollationDel
  136529. );
  136530. if( rc!=SQLITE_OK ){
  136531. ucol_close(pUCollator);
  136532. sqlite3_result_error(p, "Error registering collation function", -1);
  136533. }
  136534. }
  136535. /*
  136536. ** Register the ICU extension functions with database db.
  136537. */
  136538. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  136539. struct IcuScalar {
  136540. const char *zName; /* Function name */
  136541. int nArg; /* Number of arguments */
  136542. int enc; /* Optimal text encoding */
  136543. void *pContext; /* sqlite3_user_data() context */
  136544. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  136545. } scalars[] = {
  136546. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  136547. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  136548. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  136549. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  136550. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  136551. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  136552. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  136553. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  136554. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  136555. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  136556. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  136557. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  136558. };
  136559. int rc = SQLITE_OK;
  136560. int i;
  136561. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  136562. struct IcuScalar *p = &scalars[i];
  136563. rc = sqlite3_create_function(
  136564. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  136565. );
  136566. }
  136567. return rc;
  136568. }
  136569. #if !SQLITE_CORE
  136570. #ifdef _WIN32
  136571. __declspec(dllexport)
  136572. #endif
  136573. SQLITE_API int sqlite3_icu_init(
  136574. sqlite3 *db,
  136575. char **pzErrMsg,
  136576. const sqlite3_api_routines *pApi
  136577. ){
  136578. SQLITE_EXTENSION_INIT2(pApi)
  136579. return sqlite3IcuInit(db);
  136580. }
  136581. #endif
  136582. #endif
  136583. /************** End of icu.c *************************************************/
  136584. /************** Begin file fts3_icu.c ****************************************/
  136585. /*
  136586. ** 2007 June 22
  136587. **
  136588. ** The author disclaims copyright to this source code. In place of
  136589. ** a legal notice, here is a blessing:
  136590. **
  136591. ** May you do good and not evil.
  136592. ** May you find forgiveness for yourself and forgive others.
  136593. ** May you share freely, never taking more than you give.
  136594. **
  136595. *************************************************************************
  136596. ** This file implements a tokenizer for fts3 based on the ICU library.
  136597. */
  136598. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136599. #ifdef SQLITE_ENABLE_ICU
  136600. /* #include <assert.h> */
  136601. /* #include <string.h> */
  136602. #include <unicode/ubrk.h>
  136603. /* #include <unicode/ucol.h> */
  136604. /* #include <unicode/ustring.h> */
  136605. #include <unicode/utf16.h>
  136606. typedef struct IcuTokenizer IcuTokenizer;
  136607. typedef struct IcuCursor IcuCursor;
  136608. struct IcuTokenizer {
  136609. sqlite3_tokenizer base;
  136610. char *zLocale;
  136611. };
  136612. struct IcuCursor {
  136613. sqlite3_tokenizer_cursor base;
  136614. UBreakIterator *pIter; /* ICU break-iterator object */
  136615. int nChar; /* Number of UChar elements in pInput */
  136616. UChar *aChar; /* Copy of input using utf-16 encoding */
  136617. int *aOffset; /* Offsets of each character in utf-8 input */
  136618. int nBuffer;
  136619. char *zBuffer;
  136620. int iToken;
  136621. };
  136622. /*
  136623. ** Create a new tokenizer instance.
  136624. */
  136625. static int icuCreate(
  136626. int argc, /* Number of entries in argv[] */
  136627. const char * const *argv, /* Tokenizer creation arguments */
  136628. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  136629. ){
  136630. IcuTokenizer *p;
  136631. int n = 0;
  136632. if( argc>0 ){
  136633. n = strlen(argv[0])+1;
  136634. }
  136635. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  136636. if( !p ){
  136637. return SQLITE_NOMEM;
  136638. }
  136639. memset(p, 0, sizeof(IcuTokenizer));
  136640. if( n ){
  136641. p->zLocale = (char *)&p[1];
  136642. memcpy(p->zLocale, argv[0], n);
  136643. }
  136644. *ppTokenizer = (sqlite3_tokenizer *)p;
  136645. return SQLITE_OK;
  136646. }
  136647. /*
  136648. ** Destroy a tokenizer
  136649. */
  136650. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  136651. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  136652. sqlite3_free(p);
  136653. return SQLITE_OK;
  136654. }
  136655. /*
  136656. ** Prepare to begin tokenizing a particular string. The input
  136657. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  136658. ** used to incrementally tokenize this string is returned in
  136659. ** *ppCursor.
  136660. */
  136661. static int icuOpen(
  136662. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  136663. const char *zInput, /* Input string */
  136664. int nInput, /* Length of zInput in bytes */
  136665. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  136666. ){
  136667. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  136668. IcuCursor *pCsr;
  136669. const int32_t opt = U_FOLD_CASE_DEFAULT;
  136670. UErrorCode status = U_ZERO_ERROR;
  136671. int nChar;
  136672. UChar32 c;
  136673. int iInput = 0;
  136674. int iOut = 0;
  136675. *ppCursor = 0;
  136676. if( zInput==0 ){
  136677. nInput = 0;
  136678. zInput = "";
  136679. }else if( nInput<0 ){
  136680. nInput = strlen(zInput);
  136681. }
  136682. nChar = nInput+1;
  136683. pCsr = (IcuCursor *)sqlite3_malloc(
  136684. sizeof(IcuCursor) + /* IcuCursor */
  136685. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  136686. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  136687. );
  136688. if( !pCsr ){
  136689. return SQLITE_NOMEM;
  136690. }
  136691. memset(pCsr, 0, sizeof(IcuCursor));
  136692. pCsr->aChar = (UChar *)&pCsr[1];
  136693. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  136694. pCsr->aOffset[iOut] = iInput;
  136695. U8_NEXT(zInput, iInput, nInput, c);
  136696. while( c>0 ){
  136697. int isError = 0;
  136698. c = u_foldCase(c, opt);
  136699. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  136700. if( isError ){
  136701. sqlite3_free(pCsr);
  136702. return SQLITE_ERROR;
  136703. }
  136704. pCsr->aOffset[iOut] = iInput;
  136705. if( iInput<nInput ){
  136706. U8_NEXT(zInput, iInput, nInput, c);
  136707. }else{
  136708. c = 0;
  136709. }
  136710. }
  136711. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  136712. if( !U_SUCCESS(status) ){
  136713. sqlite3_free(pCsr);
  136714. return SQLITE_ERROR;
  136715. }
  136716. pCsr->nChar = iOut;
  136717. ubrk_first(pCsr->pIter);
  136718. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  136719. return SQLITE_OK;
  136720. }
  136721. /*
  136722. ** Close a tokenization cursor previously opened by a call to icuOpen().
  136723. */
  136724. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  136725. IcuCursor *pCsr = (IcuCursor *)pCursor;
  136726. ubrk_close(pCsr->pIter);
  136727. sqlite3_free(pCsr->zBuffer);
  136728. sqlite3_free(pCsr);
  136729. return SQLITE_OK;
  136730. }
  136731. /*
  136732. ** Extract the next token from a tokenization cursor.
  136733. */
  136734. static int icuNext(
  136735. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  136736. const char **ppToken, /* OUT: *ppToken is the token text */
  136737. int *pnBytes, /* OUT: Number of bytes in token */
  136738. int *piStartOffset, /* OUT: Starting offset of token */
  136739. int *piEndOffset, /* OUT: Ending offset of token */
  136740. int *piPosition /* OUT: Position integer of token */
  136741. ){
  136742. IcuCursor *pCsr = (IcuCursor *)pCursor;
  136743. int iStart = 0;
  136744. int iEnd = 0;
  136745. int nByte = 0;
  136746. while( iStart==iEnd ){
  136747. UChar32 c;
  136748. iStart = ubrk_current(pCsr->pIter);
  136749. iEnd = ubrk_next(pCsr->pIter);
  136750. if( iEnd==UBRK_DONE ){
  136751. return SQLITE_DONE;
  136752. }
  136753. while( iStart<iEnd ){
  136754. int iWhite = iStart;
  136755. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  136756. if( u_isspace(c) ){
  136757. iStart = iWhite;
  136758. }else{
  136759. break;
  136760. }
  136761. }
  136762. assert(iStart<=iEnd);
  136763. }
  136764. do {
  136765. UErrorCode status = U_ZERO_ERROR;
  136766. if( nByte ){
  136767. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  136768. if( !zNew ){
  136769. return SQLITE_NOMEM;
  136770. }
  136771. pCsr->zBuffer = zNew;
  136772. pCsr->nBuffer = nByte;
  136773. }
  136774. u_strToUTF8(
  136775. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  136776. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  136777. &status /* Output success/failure */
  136778. );
  136779. } while( nByte>pCsr->nBuffer );
  136780. *ppToken = pCsr->zBuffer;
  136781. *pnBytes = nByte;
  136782. *piStartOffset = pCsr->aOffset[iStart];
  136783. *piEndOffset = pCsr->aOffset[iEnd];
  136784. *piPosition = pCsr->iToken++;
  136785. return SQLITE_OK;
  136786. }
  136787. /*
  136788. ** The set of routines that implement the simple tokenizer
  136789. */
  136790. static const sqlite3_tokenizer_module icuTokenizerModule = {
  136791. 0, /* iVersion */
  136792. icuCreate, /* xCreate */
  136793. icuDestroy, /* xCreate */
  136794. icuOpen, /* xOpen */
  136795. icuClose, /* xClose */
  136796. icuNext, /* xNext */
  136797. };
  136798. /*
  136799. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  136800. */
  136801. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  136802. sqlite3_tokenizer_module const**ppModule
  136803. ){
  136804. *ppModule = &icuTokenizerModule;
  136805. }
  136806. #endif /* defined(SQLITE_ENABLE_ICU) */
  136807. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136808. /************** End of fts3_icu.c ********************************************/